diff --git a/src/test/java/org/olat/restapi/AuthenticationTest.java b/src/test/java/org/olat/restapi/AuthenticationTest.java index e6d4f4572571fb01d9b5f8ddf775f2538e5e9f2c..64f3b72330df5ce93aadb8c6b16a8e5d3688c930 100644 --- a/src/test/java/org/olat/restapi/AuthenticationTest.java +++ b/src/test/java/org/olat/restapi/AuthenticationTest.java @@ -27,26 +27,21 @@ package org.olat.restapi; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.Cookie; -import org.apache.commons.httpclient.Credentials; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.UsernamePasswordCredentials; -import org.apache.commons.httpclient.auth.AuthScope; -import org.apache.commons.httpclient.methods.GetMethod; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; +import org.apache.http.cookie.Cookie; import org.apache.http.util.EntityUtils; import org.junit.Test; import org.olat.core.util.StringHelper; @@ -71,22 +66,23 @@ public class AuthenticationTest extends OlatJerseyTestCase { } @Test - public void testSessionCookieLogin() throws HttpException, IOException { + public void testSessionCookieLogin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("administrator").queryParam("password", "openolat").build(); - GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, true); - HttpClient c = getHttpClient(); - int code = c.executeMethod(method); - assertEquals(200, code); - String response = method.getResponseBodyAsString(); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, true); + HttpResponse code = conn.execute(method); + assertEquals(200, code.getStatusLine().getStatusCode()); + String response = EntityUtils.toString(code.getEntity()); assertTrue(response.startsWith("<hello")); assertTrue(response.endsWith("Hello administrator</hello>")); - Cookie[] cookies = c.getState().getCookies(); + List<Cookie> cookies = conn.getCookieStore().getCookies(); assertNotNull(cookies); - assertTrue(cookies.length > 0); + assertTrue(cookies.size() > 0); } @Test - public void testSessionCookieLoginHttpClient4() throws HttpException, IOException { + public void testSessionCookieLoginHttpClient4() throws IOException, URISyntaxException { URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("administrator").queryParam("password", "openolat").build(); RestConnection conn = new RestConnection(); @@ -104,46 +100,46 @@ public class AuthenticationTest extends OlatJerseyTestCase { } @Test - public void testWrongPassword() throws HttpException, IOException { + public void testWrongPassword() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("administrator").queryParam("password", "blabla").build(); - GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, true); - HttpClient c = getHttpClient(); - int code = c.executeMethod(method); - assertEquals(401, code); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, true); + HttpResponse code = conn.execute(method); + assertEquals(401, code.getStatusLine().getStatusCode()); } @Test - public void testUnkownUser() throws HttpException, IOException { + public void testUnkownUser() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path("treuitr").queryParam("password", "blabla").build(); - GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, true); - HttpClient c = getHttpClient(); - int code = c.executeMethod(method); - assertEquals(401, code); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, true); + HttpResponse code = conn.execute(method); + assertEquals(401, code.getStatusLine().getStatusCode()); } @Test - public void testBasicAuthentication() throws HttpException, IOException { + public void testBasicAuthentication() throws IOException, URISyntaxException { //path is protected - GetMethod method1 = createGet("/users/version", MediaType.TEXT_PLAIN, false); - method1.setRequestHeader("Authorization", "Basic " + Base64Encoder.encode("administrator:openolat")); - int code1 = getHttpClient().executeMethod(method1); - method1.releaseConnection(); - assertEquals(code1, 200); - String securityToken = getToken(method1); + RestConnection conn = new RestConnection(); + URI uri = UriBuilder.fromUri(getContextURI()).path("users").path("version").build(); + HttpGet method1 = conn.createGet(uri, MediaType.TEXT_PLAIN, false); + method1.setHeader("Authorization", "Basic " + Base64Encoder.encode("administrator:openolat")); + HttpResponse code1 = conn.execute(method1); + assertEquals(200, code1.getStatusLine().getStatusCode()); + String securityToken = conn.getSecurityToken(); assertTrue(StringHelper.containsNonWhitespace(securityToken)); } @Test - public void testWebStandardAuthentication() throws HttpException, IOException { - HttpClient c = getHttpClient(); - Credentials creds = new UsernamePasswordCredentials("administrator", "openolat"); - c.getState().setCredentials(AuthScope.ANY, creds); - - GetMethod method = createGet("/users/version", MediaType.TEXT_PLAIN, false); - int code = c.executeMethod(method); - method.releaseConnection(); - assertEquals(code, 200); - String securityToken = getToken(method); + public void testWebStandardAuthentication() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + conn.setCredentials("administrator", "openolat"); + + URI uri = UriBuilder.fromUri(getContextURI()).path("users").path("version").build(); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, false); + HttpResponse code = conn.execute(method); + assertEquals(200, code.getStatusLine().getStatusCode()); + String securityToken = conn.getSecurityToken(); assertTrue(StringHelper.containsNonWhitespace(securityToken)); } } diff --git a/src/test/java/org/olat/restapi/CatalogTest.java b/src/test/java/org/olat/restapi/CatalogTest.java index f7fab9da53dfdeb63a0983454eb4627566bc08db..17b798baf0c95d993e7091e0edc2fe4e079201e3 100644 --- a/src/test/java/org/olat/restapi/CatalogTest.java +++ b/src/test/java/org/olat/restapi/CatalogTest.java @@ -149,9 +149,8 @@ public class CatalogTest extends OlatJerseyTestCase { DBFactory.getInstance().intermediateCommit(); } - @After @Override + @After public void tearDown() throws Exception { - super.tearDown(); DBFactory.getInstance().closeSession(); } diff --git a/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java b/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java index 8590813882e83b754f02fd71ffb10781af0283f8..14cf725c3903bd8ac61bb6c04a504e34edce2d3e 100644 --- a/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java +++ b/src/test/java/org/olat/restapi/CourseGroupMgmtTest.java @@ -33,17 +33,19 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.After; @@ -140,9 +142,7 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { } @After - @Override public void tearDown() throws Exception { - super.tearDown(); try { DBFactory.getInstance().closeSession(); } catch (Exception e) { @@ -154,15 +154,16 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { @Test - public void testGetCourseGroups() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetCourseGroups() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); - String request = "/repo/courses/" + course.getResourceableId() + "/groups"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); List<GroupVO> vos = parseGroupArray(body); assertNotNull(vos); assertEquals(2, vos.size());//g1 and g2 @@ -171,22 +172,24 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetCourseGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String request = "/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey(); - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetCourseGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + GroupVO vo = parse(body, GroupVO.class); assertNotNull(vo); assertEquals(g1.getKey(), vo.getKey()); } @Test - public void testPutCourseGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testPutCourseGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); GroupVO vo = new GroupVO(); vo.setName("hello"); @@ -194,16 +197,14 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { vo.setMinParticipants(new Integer(-1)); vo.setMaxParticipants(new Integer(-1)); - String stringuifiedAuth = stringuified(vo); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - String request = "/repo/courses/" + course.getResourceableId() + "/groups"; - PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - method.setRequestEntity(entity); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); GroupVO responseVo = parse(body, GroupVO.class); assertNotNull(responseVo); assertEquals(vo.getName(), responseVo.getName()); @@ -219,8 +220,9 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testUpdateCourseGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testUpdateCourseGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); GroupVO vo = new GroupVO(); vo.setKey(g1.getKey()); @@ -230,14 +232,12 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { vo.setMaxParticipants(g1.getMaxParticipants()); vo.setType(g1.getType()); - String stringuifiedAuth = stringuified(vo); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - String request = "/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey(); - PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true); - method.setRequestEntity(entity); - int code = c.executeMethod(method); - method.releaseConnection(); - assertTrue(code == 200 || code == 201); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey()).build(); + HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + HttpResponse response = conn.execute(method); + + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); BusinessGroupManager bgm = BusinessGroupManagerImpl.getInstance(); BusinessGroup bg = bgm.loadBusinessGroup(g1.getKey(), false); @@ -248,14 +248,15 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testDeleteCourseGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testDeleteCourseGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); - String request = "/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey(); - DeleteMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - method.releaseConnection(); - assertEquals(200, code); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups/" + g1.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + + assertEquals(200, response.getStatusLine().getStatusCode()); BusinessGroupManager bgm = BusinessGroupManagerImpl.getInstance(); BusinessGroup bg = bgm.loadBusinessGroup(g1.getKey(), false); @@ -263,20 +264,21 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testBasicSecurityDeleteCall() throws IOException { - HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8"); + public void testBasicSecurityDeleteCall() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-c-g-3", "A6B7C8")); - String request = "/repo/courses/" + course.getResourceableId() + "/groups/" + g2.getKey(); - DeleteMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - method.releaseConnection(); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups/" + g2.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); - assertEquals(401, code); + assertEquals(401, response.getStatusLine().getStatusCode()); } @Test - public void testBasicSecurityPutCall() throws IOException { - HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8"); + public void testBasicSecurityPutCall() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-c-g-3", "A6B7C8")); GroupVO vo = new GroupVO(); vo.setName("hello dont put"); @@ -284,20 +286,15 @@ public class CourseGroupMgmtTest extends OlatJerseyTestCase { vo.setMinParticipants(new Integer(-1)); vo.setMaxParticipants(new Integer(-1)); - String stringuifiedAuth = stringuified(vo); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - String request = "/repo/courses/" + course.getResourceableId() + "/groups"; - PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - method.setRequestEntity(entity); - int code = c.executeMethod(method); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId() + "/groups").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); - assertEquals(401, code); + HttpResponse response = conn.execute(method); + assertEquals(401, response.getStatusLine().getStatusCode()); } - - - - protected List<GroupVO> parseGroupArray(String body) { + protected List<GroupVO> parseGroupArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<GroupVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/CourseSecurityTest.java b/src/test/java/org/olat/restapi/CourseSecurityTest.java index 3ecbd3b7d489e05e82130684b47a92dd89d86da5..fed4ba684a1990405ff04d98a0f8919856648752 100644 --- a/src/test/java/org/olat/restapi/CourseSecurityTest.java +++ b/src/test/java/org/olat/restapi/CourseSecurityTest.java @@ -27,17 +27,18 @@ package org.olat.restapi; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; import java.util.Collections; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPut; import org.junit.Before; import org.junit.Test; import org.olat.admin.securitygroup.gui.IdentitiesAddEvent; @@ -97,73 +98,69 @@ public class CourseSecurityTest extends OlatJerseyTestCase { } @Test - public void testAdminCanEditCourse() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testAdminCanEditCourse() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an structure node - URI newStructureUri = getElementsUri(course).path("structure").build(); - PutMethod method = createPut(newStructureUri, MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("position", "0"), - new NameValuePair("shortTitle", "Structure-admin-0"), - new NameValuePair("longTitle", "Structure-long-admin-0"), - new NameValuePair("objectives", "Structure-objectives-admin-0") - }); - int code = c.executeMethod(method); - assertEquals(200, code); + URI newStructureUri = getElementsUri(course).path("structure") + .queryParam("position", "0") + .queryParam("shortTitle", "Structure-admin-0") + .queryParam("longTitle", "Structure-long-admin-0") + .queryParam("objectives", "Structure-objectives-admin-0").build(); + HttpPut method = conn.createPut(newStructureUri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); } @Test - public void testIdCannotEditCourse() throws IOException { - HttpClient c = loginWithCookie("id-c-s-0", "A6B7C8"); + public void testIdCannotEditCourse() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("id-c-s-0", "A6B7C8")); //create an structure node - URI newStructureUri = getElementsUri(course).path("structure").build(); - PutMethod method = createPut(newStructureUri, MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("position", "0"), - new NameValuePair("shortTitle", "Structure-id-0"), - new NameValuePair("longTitle", "Structure-long-id-0"), - new NameValuePair("objectives", "Structure-objectives-id-0") - }); - int code = c.executeMethod(method); - assertEquals(401, code); + URI newStructureUri = getElementsUri(course).path("structure") + .queryParam("position", "0") + .queryParam("shortTitle", "Structure-id-0") + .queryParam("longTitle", "Structure-long-id-0") + .queryParam("objectives", "Structure-objectives-id-0").build(); + HttpPut method = conn.createPut(newStructureUri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(401, response.getStatusLine().getStatusCode()); } @Test - public void testAuthorCannotEditCourse() throws IOException { + public void testAuthorCannotEditCourse() throws IOException, URISyntaxException { //author but not owner - HttpClient c = loginWithCookie("id-c-s-1", "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("id-c-s-1", "A6B7C8")); //create an structure node - URI newStructureUri = getElementsUri(course).path("structure").build(); - PutMethod method = createPut(newStructureUri, MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("position", "0"), - new NameValuePair("shortTitle", "Structure-id-0"), - new NameValuePair("longTitle", "Structure-long-id-0"), - new NameValuePair("objectives", "Structure-objectives-id-0") - }); - int code = c.executeMethod(method); - assertEquals(401, code); + URI newStructureUri = getElementsUri(course).path("structure") + .queryParam("position", "0") + .queryParam("shortTitle", "Structure-id-0") + .queryParam("longTitle", "Structure-long-id-0") + .queryParam("objectives", "Structure-objectives-id-0").build(); + HttpPut method = conn.createPut(newStructureUri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(401, response.getStatusLine().getStatusCode()); } @Test - public void testAuthorCanEditCourse() throws IOException { + public void testAuthorCanEditCourse() throws IOException, URISyntaxException { //author and owner - HttpClient c = loginWithCookie("id-c-s-2", "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("id-c-s-2", "A6B7C8")); //create an structure node - URI newStructureUri = getElementsUri(course).path("structure").build(); - PutMethod method = createPut(newStructureUri, MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("position", "0"), - new NameValuePair("shortTitle", "Structure-id-0"), - new NameValuePair("longTitle", "Structure-long-id-0"), - new NameValuePair("objectives", "Structure-objectives-id-0") - }); - int code = c.executeMethod(method); - assertEquals(200, code); + URI newStructureUri = getElementsUri(course).path("structure") + .queryParam("position", "0") + .queryParam("shortTitle", "Structure-id-0") + .queryParam("longTitle", "Structure-long-id-0") + .queryParam("objectives", "Structure-objectives-id-0").build(); + HttpPut method = conn.createPut(newStructureUri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); } diff --git a/src/test/java/org/olat/restapi/CourseTest.java b/src/test/java/org/olat/restapi/CourseTest.java index 449982ccccf46660ac567f68ce481b0547ea1ece..21e6da032deee20cc521ad862dc7830ab276addf 100644 --- a/src/test/java/org/olat/restapi/CourseTest.java +++ b/src/test/java/org/olat/restapi/CourseTest.java @@ -34,19 +34,20 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PutMethod; import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Before; @@ -115,38 +116,47 @@ public class CourseTest extends OlatJerseyTestCase { } @Test - public void testGetCourseRunStructure() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - GetMethod method = createGet("/repo/courses/" + course1.getResourceableId() + "/runstructure", MediaType.APPLICATION_XML, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + public void testGetCourseRunStructure() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course1.getResourceableId() + "/runstructure").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_XML, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + String body = EntityUtils.toString(response.getEntity()); assertNotNull(body); assertTrue(body.length() > 100); assertTrue(body.indexOf("<org.olat.course.Structure>") >= 0); } @Test - public void testGetCourseEditorTreeModel() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - GetMethod method = createGet("/repo/courses/" + course1.getResourceableId() + "/editortreemodel", MediaType.APPLICATION_XML, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + public void testGetCourseEditorTreeModel() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course1.getResourceableId() + "/editortreemodel").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_XML, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + String body = EntityUtils.toString(response.getEntity()); assertNotNull(body); assertTrue(body.length() > 100); assertTrue(body.indexOf("<org.olat.course.tree.CourseEditorTreeModel>") >= 0); } @Test - public void testDeleteCourses() throws IOException { + public void testDeleteCourses() throws IOException, URISyntaxException { ICourse course = CoursesWebService.createEmptyCourse(admin, "courseToDel", "course to delete", null); DBFactory.getInstance().intermediateCommit(); - HttpClient c = loginWithCookie("administrator", "openolat"); - DeleteMethod method = createDelete("/repo/courses/" + course.getResourceableId(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course.getResourceableId()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); List<String> courseType = new ArrayList<String>(); courseType.add(CourseModule.getCourseTypeName()); @@ -161,12 +171,13 @@ public class CourseTest extends OlatJerseyTestCase { } @Test - public void testAddAuthor() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String uri = "/repo/courses/" + course1.getResourceableId() + "/authors/" + auth0.getKey(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + public void testAddAuthor() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course1.getResourceableId() + "/authors/" + auth0.getKey()).build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); //is auth0 author BaseSecurity securityManager = BaseSecurityManager.getInstance(); @@ -185,7 +196,7 @@ public class CourseTest extends OlatJerseyTestCase { } @Test - public void testGetAuthors() throws IOException { + public void testGetAuthors() throws IOException, URISyntaxException { //make auth1 and auth2 authors BaseSecurity securityManager = BaseSecurityManager.getInstance(); SecurityGroup authorGroup = securityManager.findSecurityGroupByName(Constants.GROUP_AUTHORS); @@ -208,12 +219,13 @@ public class CourseTest extends OlatJerseyTestCase { DBFactory.getInstance().intermediateCommit(); //get them - HttpClient c = loginWithCookie("administrator", "openolat"); - String uri = "/repo/courses/" + course1.getResourceableId() + "/authors"; - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI uri = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course1.getResourceableId() + "/authors").build(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); assertNotNull(body); List<UserVO> authorVOs = parseUserArray(body); @@ -221,7 +233,7 @@ public class CourseTest extends OlatJerseyTestCase { } @Test - public void testRemoveAuthor() throws IOException { + public void testRemoveAuthor() throws IOException, URISyntaxException { //make auth1 and auth2 authors BaseSecurity securityManager = BaseSecurityManager.getInstance(); SecurityGroup authorGroup = securityManager.findSecurityGroupByName(Constants.GROUP_AUTHORS); @@ -245,17 +257,19 @@ public class CourseTest extends OlatJerseyTestCase { //end setup //test - HttpClient c = loginWithCookie("administrator", "openolat"); - String uri = "/repo/courses/" + course1.getResourceableId() + "/authors/" + auth1.getKey(); - DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - - uri = "/repo/courses/" + course1.getResourceableId() + "/authors/" + auth2.getKey(); - method = createDelete(uri, MediaType.APPLICATION_JSON, true); - code = c.executeMethod(method); - assertEquals(code, 200); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course1.getResourceableId() + "/authors/" + auth1.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + EntityUtils.consume(response.getEntity()); + URI request2 = UriBuilder.fromUri(getContextURI()).path("/repo/courses/" + course1.getResourceableId() + "/authors/" + auth2.getKey()).build(); + HttpDelete method2 = conn.createDelete(request2, MediaType.APPLICATION_JSON, true); + HttpResponse response2 = conn.execute(method2); + assertEquals(200, response2.getStatusLine().getStatusCode()); + EntityUtils.consume(response2.getEntity()); //control repositoryEntry = rm.lookupRepositoryEntry(course1, true); @@ -265,7 +279,7 @@ public class CourseTest extends OlatJerseyTestCase { DBFactory.getInstance().intermediateCommit(); } - protected List<UserVO> parseUserArray(String body) { + protected List<UserVO> parseUserArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<UserVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/CoursesContactElementTest.java b/src/test/java/org/olat/restapi/CoursesContactElementTest.java index 288d023331d04a786d277ce0b597c38c1fa59379..b047fc77f5b422f0a4f7f9aeecb04de12467073f 100644 --- a/src/test/java/org/olat/restapi/CoursesContactElementTest.java +++ b/src/test/java/org/olat/restapi/CoursesContactElementTest.java @@ -28,6 +28,7 @@ package org.olat.restapi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_EMAILTOADRESSES; import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_EMAILTOCOACHES; import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_EMAILTOPARTICIPANTS; @@ -35,14 +36,16 @@ import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_MBODY_DEFAULT import static org.olat.course.nodes.co.COEditController.CONFIG_KEY_MSUBJECT_DEFAULT; import java.io.IOException; +import java.io.InputStream; import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpPut; import org.junit.Before; import org.junit.Test; import org.olat.basesecurity.BaseSecurityManager; @@ -85,8 +88,9 @@ public class CoursesContactElementTest extends OlatJerseyTestCase { } @Test - public void testBareBoneConfig() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testBareBoneConfig() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an contact node URI newContactUri = getElementsUri(course1).path("contact") @@ -94,12 +98,12 @@ public class CoursesContactElementTest extends OlatJerseyTestCase { .queryParam("position", "0").queryParam("shortTitle", "Contact-0") .queryParam("longTitle", "Contact-long-0") .queryParam("objectives", "Contact-objectives-0").build(); - PutMethod method = createPut(newContactUri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + HttpPut method = conn.createPut(newContactUri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + InputStream body = response.getEntity().getContent(); - assertEquals(200, code); + + assertEquals(200, response.getStatusLine().getStatusCode()); CourseNodeVO contactNode = parse(body, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); @@ -110,8 +114,9 @@ public class CoursesContactElementTest extends OlatJerseyTestCase { } @Test - public void testFullConfig() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testFullConfig() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an contact node URI newContactUri = getElementsUri(course1).path("contact") @@ -127,13 +132,13 @@ public class CoursesContactElementTest extends OlatJerseyTestCase { .queryParam("defaultSubject", "Hello by contact 1") .queryParam("defaultBody", "Hello by contact 1 body") .build(); - PutMethod method = createPut(newContactUri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + HttpPut method = conn.createPut(newContactUri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + InputStream body = response.getEntity().getContent(); + //check the return values - assertEquals(200, code); + assertEquals(200, response.getStatusLine().getStatusCode()); CourseNodeVO contactNode = parse(body, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); diff --git a/src/test/java/org/olat/restapi/CoursesElementsTest.java b/src/test/java/org/olat/restapi/CoursesElementsTest.java index 38341403be260cb486d5760144ff0d65e28c183a..bf76e81ec4e6711317fd144074a762caa212803f 100644 --- a/src/test/java/org/olat/restapi/CoursesElementsTest.java +++ b/src/test/java/org/olat/restapi/CoursesElementsTest.java @@ -32,6 +32,7 @@ import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -39,17 +40,16 @@ import java.net.URL; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.httpclient.methods.multipart.FilePart; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.commons.httpclient.methods.multipart.StringPart; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; import org.junit.Test; import org.olat.core.commons.modules.bc.vfs.OlatRootFolderImpl; import org.olat.core.gui.components.tree.TreeNode; @@ -86,16 +86,17 @@ public class CoursesElementsTest extends OlatJerseyTestCase { @Test public void testCreateCoursePost() throws IOException, URISyntaxException{ - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an empty course URI uri = getCoursesUri().queryParam("shortTitle", "course3").queryParam("title", "course3 long name").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + CourseVO course = parse(body, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); @@ -103,15 +104,16 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create an structure node URI newStructureUri = getElementsUri(course).path("structure").build(); - PostMethod newStructureMethod = createPost(newStructureUri, MediaType.APPLICATION_JSON, true); - newStructureMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newStructureMethod.addParameter("position", "0"); - newStructureMethod.addParameter("shortTitle", "Structure-0"); - newStructureMethod.addParameter("longTitle", "Structure-long-0"); - newStructureMethod.addParameter("objectives", "Structure-objectives-0"); - int newStructureCode = c.executeMethod(newStructureMethod); - assertTrue(newStructureCode == 200 || newStructureCode == 201); - String newStructureBody = newStructureMethod.getResponseBodyAsString(); + HttpPost newStructureMethod = conn.createPost(newStructureUri, MediaType.APPLICATION_JSON, true); + conn.addEntity(newStructureMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "0"), + new BasicNameValuePair("shortTitle", "Structure-0"), + new BasicNameValuePair("longTitle", "Structure-long-0"), + new BasicNameValuePair("objectives", "Structure-objectives-0")); + + HttpResponse newStructureCode = conn.execute(newStructureMethod); + assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); + String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); @@ -127,22 +129,22 @@ public class CoursesElementsTest extends OlatJerseyTestCase { File page = new File(pageUrl.toURI()); URI newPageUri = getElementsUri(course).path("singlepage").build(); - PostMethod newPageMethod = createPost(newPageUri, MediaType.APPLICATION_JSON, true); - newPageMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", page), - new StringPart("filename", page.getName()), - new StringPart("parentNodeId",course.getEditorRootNodeId()), - new StringPart("position","1"), - new StringPart("shortTitle", "Single-Page-0"), - new StringPart("longTitle", "Single-Page-long-0"), - new StringPart("objectives", "Single-Page-objectives-0") - }; - newPageMethod.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int newPageCode = c.executeMethod(newPageMethod); - assertTrue(newPageCode == 200 || newPageCode == 201); - String newPageBody = newPageMethod.getResponseBodyAsString(); + HttpPost newPageMethod = conn.createPost(newPageUri, MediaType.APPLICATION_JSON, true); + newPageMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(page)); + entity.addPart("filename", new StringBody(page.getName())); + entity.addPart("parentNodeId", new StringBody(course.getEditorRootNodeId())); + entity.addPart("position", new StringBody("1")); + entity.addPart("shortTitle", new StringBody("Single-Page-0")); + entity.addPart("longTitle", new StringBody("Single-Page-long-0")); + entity.addPart("objectives", new StringBody("Single-Page-objectives-0")); + newPageMethod.setEntity(entity); + + HttpResponse newPageCode = conn.execute(newPageMethod); + assertTrue(newPageCode.getStatusLine().getStatusCode() == 200 || newPageCode.getStatusLine().getStatusCode() == 201); + String newPageBody = EntityUtils.toString(newPageCode.getEntity()); CourseNodeVO pageNode = parse(newPageBody, CourseNodeVO.class); assertNotNull(pageNode); assertNotNull(pageNode.getId()); @@ -154,20 +156,21 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create a folder node URI newFolderUri = getElementsUri(course).path("folder").build(); - PostMethod newFolderMethod = createPost(newFolderUri, MediaType.APPLICATION_JSON, true); - newFolderMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newFolderMethod.addParameter("position", "2"); - newFolderMethod.addParameter("shortTitle", "Folder-0"); - newFolderMethod.addParameter("longTitle", "Folder-long-0"); - newFolderMethod.addParameter("objectives", "Folder-objectives-0"); + HttpPost newFolderMethod = conn.createPost(newFolderUri, MediaType.APPLICATION_JSON, true); + String rule = "hasLanguage(\"de\")"; - newFolderMethod.addParameter("visibilityExpertRules", rule); - newFolderMethod.addParameter("downloadExpertRules", rule); - newFolderMethod.addParameter("uploadExpertRules", rule); + conn.addEntity(newFolderMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "2"), + new BasicNameValuePair("shortTitle", "Folder-0"), + new BasicNameValuePair("longTitle", "Folder-long-0"), + new BasicNameValuePair("objectives", "Folder-objectives-0"), + new BasicNameValuePair("visibilityExpertRules", rule), + new BasicNameValuePair("downloadExpertRules", rule), + new BasicNameValuePair("uploadExpertRules", rule)); - int newFolderCode = c.executeMethod(newFolderMethod); - assertTrue(newFolderCode == 200 || newFolderCode == 201); - String newFolderBody = newFolderMethod.getResponseBodyAsString(); + HttpResponse newFolderCode = conn.execute(newFolderMethod); + assertTrue(newFolderCode.getStatusLine().getStatusCode() == 200 || newFolderCode.getStatusLine().getStatusCode() == 201); + String newFolderBody = EntityUtils.toString(newFolderCode.getEntity()); CourseNodeVO folderNode = parse(newFolderBody, CourseNodeVO.class); assertNotNull(folderNode); assertNotNull(folderNode.getId()); @@ -179,15 +182,15 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create a forum node URI newForumUri = getElementsUri(course).path("forum").build(); - PostMethod newForumMethod = createPost(newForumUri, MediaType.APPLICATION_JSON, true); - newForumMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newForumMethod.addParameter("position", "3"); - newForumMethod.addParameter("shortTitle", "Forum-0"); - newForumMethod.addParameter("longTitle", "Forum-long-0"); - newForumMethod.addParameter("objectives", "Forum-objectives-0"); - int newForumCode = c.executeMethod(newForumMethod); - assertTrue(newForumCode == 200 || newForumCode == 201); - String newForumBody = newForumMethod.getResponseBodyAsString(); + HttpPost newForumMethod = conn.createPost(newForumUri, MediaType.APPLICATION_JSON, true); + conn.addEntity(newForumMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "3"), + new BasicNameValuePair("shortTitle", "Forum-0"), + new BasicNameValuePair("longTitle", "Forum-long-0"), + new BasicNameValuePair("objectives", "Forum-objectives-0")); + HttpResponse newForumCode = conn.execute(newForumMethod); + assertTrue(newForumCode.getStatusLine().getStatusCode() == 200 || newForumCode.getStatusLine().getStatusCode() == 201); + String newForumBody = EntityUtils.toString(newForumCode.getEntity()); CourseNodeVO forumNode = parse(newForumBody, CourseNodeVO.class); assertNotNull(forumNode); assertNotNull(forumNode.getId()); @@ -199,17 +202,17 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create a task node URI newTaskUri = getElementsUri(course).path("task").build(); - PostMethod newTaskMethod = createPost(newTaskUri, MediaType.APPLICATION_JSON, true); - newTaskMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newTaskMethod.addParameter("position", "4"); - newTaskMethod.addParameter("shortTitle", "Task-0"); - newTaskMethod.addParameter("longTitle", "Task-long-0"); - newTaskMethod.addParameter("objectives", "Task-objectives-0"); - newTaskMethod.addParameter("points", "25"); - newTaskMethod.addParameter("text", "A very difficult test"); - int newTaskCode = c.executeMethod(newTaskMethod); - assertTrue(newTaskCode == 200 || newTaskCode == 201); - String newTaskBody = newTaskMethod.getResponseBodyAsString(); + HttpPost newTaskMethod = conn.createPost(newTaskUri, MediaType.APPLICATION_JSON, true); + conn.addEntity(newTaskMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "4"), + new BasicNameValuePair("shortTitle", "Task-0"), + new BasicNameValuePair("longTitle", "Task-long-0"), + new BasicNameValuePair("objectives", "Task-objectives-0"), + new BasicNameValuePair("points", "25"), + new BasicNameValuePair("text", "A very difficult test")); + HttpResponse newTaskCode = conn.execute(newTaskMethod); + assertTrue(newTaskCode.getStatusLine().getStatusCode() == 200 || newTaskCode.getStatusLine().getStatusCode() == 201); + String newTaskBody = EntityUtils.toString(newTaskCode.getEntity()); CourseNodeVO taskNode = parse(newTaskBody, CourseNodeVO.class); assertNotNull(taskNode); assertNotNull(taskNode.getId()); @@ -221,15 +224,17 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create a test node URI newTestUri = getElementsUri(course).path("test").build(); - PostMethod newTestMethod = createPost(newTestUri, MediaType.APPLICATION_JSON, true); - newTestMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newTestMethod.addParameter("testResourceableId", course.getEditorRootNodeId()); - newTestMethod.addParameter("position", "5"); - newTestMethod.addParameter("shortTitle", "Test-0"); - newTestMethod.addParameter("longTitle", "Test-long-0"); - newTestMethod.addParameter("objectives", "Test-objectives-0"); - int newTestCode = c.executeMethod(newTestMethod); - assertTrue(newTestCode == 404);//must bind a real test + HttpPost newTestMethod = conn.createPost(newTestUri, MediaType.APPLICATION_JSON, true); + conn.addEntity(newTestMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("testResourceableId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "5"), + new BasicNameValuePair("shortTitle", "Test-0"), + new BasicNameValuePair("longTitle", "Test-long-0"), + new BasicNameValuePair("objectives", "Test-objectives-0")); + HttpResponse newTestCode = conn.execute(newTestMethod); + assertTrue(newTestCode.getStatusLine().getStatusCode() == 404);//must bind a real test + EntityUtils.consume(newTestCode.getEntity()); + /* assertTrue(newTestCode == 200 || newTestCode == 201); String newTestBody = newTestMethod.getResponseBodyAsString(); @@ -242,15 +247,15 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create an assessment node URI newAssessmentUri = getElementsUri(course).path("assessment").build(); - PostMethod newAssessmentMethod = createPost(newAssessmentUri, MediaType.APPLICATION_JSON, true); - newAssessmentMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newAssessmentMethod.addParameter("position", "5"); - newAssessmentMethod.addParameter("shortTitle", "Assessment-0"); - newAssessmentMethod.addParameter("longTitle", "Assessment-long-0"); - newAssessmentMethod.addParameter("objectives", "Assessment-objectives-0"); - int newAssessmentCode = c.executeMethod(newAssessmentMethod); - assertTrue(newAssessmentCode == 200 || newAssessmentCode == 201); - String newAssessmentBody = newAssessmentMethod.getResponseBodyAsString(); + HttpPost newAssessmentMethod = conn.createPost(newAssessmentUri, MediaType.APPLICATION_JSON, true); + conn.addEntity(newAssessmentMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "5"), + new BasicNameValuePair("shortTitle", "Assessment-0"), + new BasicNameValuePair("longTitle", "Assessment-long-0"), + new BasicNameValuePair("objectives", "Assessment-objectives-0")); + HttpResponse newAssessmentCode = conn.execute(newAssessmentMethod); + assertTrue(newAssessmentCode.getStatusLine().getStatusCode() == 200 || newAssessmentCode.getStatusLine().getStatusCode() == 201); + String newAssessmentBody = EntityUtils.toString(newAssessmentCode.getEntity()); CourseNodeVO assessmentNode = parse(newAssessmentBody, CourseNodeVO.class); assertNotNull(assessmentNode); assertNotNull(assessmentNode.getId()); @@ -261,16 +266,16 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //create an contact node URI newContactUri = getElementsUri(course).path("contact").build(); - PostMethod newContactMethod = createPost(newContactUri, MediaType.APPLICATION_JSON, true); - newContactMethod.addParameter("parentNodeId", course.getEditorRootNodeId()); - newContactMethod.addParameter("position", "6"); - newContactMethod.addParameter("shortTitle", "Contact-0"); - newContactMethod.addParameter("longTitle", "Contact-long-0"); - newContactMethod.addParameter("objectives", "Contact-objectives-0"); + HttpPost newContactMethod = conn.createPost(newContactUri, MediaType.APPLICATION_JSON, true); + conn.addEntity(newContactMethod, new BasicNameValuePair("parentNodeId", course.getEditorRootNodeId()), + new BasicNameValuePair("position", "6"), + new BasicNameValuePair("shortTitle", "Contact-0"), + new BasicNameValuePair("longTitle", "Contact-long-0"), + new BasicNameValuePair("objectives", "Contact-objectives-0")); - int newContactCode = c.executeMethod(newContactMethod); - assertEquals(200, newContactCode); - String newContactBody = newContactMethod.getResponseBodyAsString(); + HttpResponse newContactCode = conn.execute(newContactMethod); + assertEquals(200, newContactCode.getStatusLine().getStatusCode()); + String newContactBody = EntityUtils.toString(newContactCode.getEntity()); CourseNodeVO contactNode = parse(newContactBody, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); @@ -282,16 +287,17 @@ public class CoursesElementsTest extends OlatJerseyTestCase { @Test public void testCreateCoursePut() throws IOException, URISyntaxException{ - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an empty course URI uri = getCoursesUri().queryParam("shortTitle", "course3").queryParam("title", "course3 long name").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + CourseVO course = parse(body, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); @@ -311,15 +317,14 @@ public class CoursesElementsTest extends OlatJerseyTestCase { groupVo.setMinParticipants(new Integer(-1)); groupVo.setMaxParticipants(new Integer(-1)); - String stringuifiedAuth = stringuified(groupVo); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); URI newGroupUri = getCoursesUri().path(course.getKey().toString()).path("groups").build(); - PutMethod newGrpMethod = createPut(newGroupUri, MediaType.APPLICATION_JSON, true); - newGrpMethod.setRequestEntity(entity); - int newGrpCode = c.executeMethod(newGrpMethod); - assertEquals(200, newGrpCode); - String newGrpBody = newGrpMethod.getResponseBodyAsString(); - newGrpMethod.releaseConnection(); + HttpPut newGrpMethod = conn.createPut(newGroupUri, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(newGrpMethod, groupVo); + + HttpResponse newGrpCode = conn.execute(newGrpMethod); + assertEquals(200, newGrpCode.getStatusLine().getStatusCode()); + InputStream newGrpBody = newGrpCode.getEntity().getContent(); + GroupVO group = parse(newGrpBody, GroupVO.class); assertNotNull(group); assertNotNull(group.getKey()); @@ -331,10 +336,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position", "0").queryParam("shortTitle", "Structure-0") .queryParam("longTitle", "Structure-long-0") .queryParam("objectives", "Structure-objectives-0").build(); - PutMethod newStructureMethod = createPut(newStructureUri, MediaType.APPLICATION_JSON, true); - int newStructureCode = c.executeMethod(newStructureMethod); - assertTrue(newStructureCode == 200 || newStructureCode == 201); - String newStructureBody = newStructureMethod.getResponseBodyAsString(); + HttpPut newStructureMethod = conn.createPut(newStructureUri, MediaType.APPLICATION_JSON, true); + HttpResponse newStructureCode = conn.execute(newStructureMethod); + assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); + String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); @@ -354,17 +359,13 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position","1").queryParam("shortTitle", "Single-Page-0") .queryParam("longTitle", "Single-Page-long-0") .queryParam("objectives", "Single-Page-objectives-0").build(); - PutMethod newPageMethod = createPut(newPageUri, MediaType.APPLICATION_JSON, true); - newPageMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", page), - new StringPart("filename", page.getName()) - }; - newPageMethod.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int newPageCode = c.executeMethod(newPageMethod); - assertTrue(newPageCode == 200 || newPageCode == 201); - String newPageBody = newPageMethod.getResponseBodyAsString(); + HttpPut newPageMethod = conn.createPut(newPageUri, MediaType.APPLICATION_JSON, true); + newPageMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(newPageMethod, page.getName(), page); + + HttpResponse newPageCode = conn.execute(newPageMethod); + assertTrue(newPageCode.getStatusLine().getStatusCode() == 200 || newPageCode.getStatusLine().getStatusCode() == 201); + String newPageBody = EntityUtils.toString(newPageCode.getEntity()); CourseNodeVO pageNode = parse(newPageBody, CourseNodeVO.class); assertNotNull(pageNode); assertNotNull(pageNode.getId()); @@ -380,10 +381,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position", "2").queryParam("shortTitle", "Folder-0") .queryParam("longTitle", "Folder-long-0") .queryParam("objectives", "Folder-objectives-0").build(); - PutMethod newFolderMethod = createPut(newFolderUri, MediaType.APPLICATION_JSON, true); - int newFolderCode = c.executeMethod(newFolderMethod); - assertTrue(newFolderCode == 200 || newFolderCode == 201); - String newFolderBody = newFolderMethod.getResponseBodyAsString(); + HttpPut newFolderMethod = conn.createPut(newFolderUri, MediaType.APPLICATION_JSON, true); + HttpResponse newFolderCode = conn.execute(newFolderMethod); + assertTrue(newFolderCode.getStatusLine().getStatusCode() == 200 || newFolderCode.getStatusLine().getStatusCode() == 201); + String newFolderBody = EntityUtils.toString(newFolderCode.getEntity()); CourseNodeVO folderNode = parse(newFolderBody, CourseNodeVO.class); assertNotNull(folderNode); assertNotNull(folderNode.getId()); @@ -399,10 +400,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position", "3").queryParam("shortTitle", "Forum-0") .queryParam("longTitle", "Forum-long-0") .queryParam("objectives", "Forum-objectives-0").build(); - PutMethod newForumMethod = createPut(newForumUri, MediaType.APPLICATION_JSON, true); - int newForumCode = c.executeMethod(newForumMethod); - assertTrue(newForumCode == 200 || newForumCode == 201); - String newForumBody = newForumMethod.getResponseBodyAsString(); + HttpPut newForumMethod = conn.createPut(newForumUri, MediaType.APPLICATION_JSON, true); + HttpResponse newForumCode = conn.execute(newForumMethod); + assertTrue(newForumCode.getStatusLine().getStatusCode() == 200 || newForumCode.getStatusLine().getStatusCode() == 201); + String newForumBody = EntityUtils.toString(newForumCode.getEntity()); CourseNodeVO forumNode = parse(newForumBody, CourseNodeVO.class); assertNotNull(forumNode); assertNotNull(forumNode.getId()); @@ -419,10 +420,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("longTitle", "Task-long-0") .queryParam("objectives", "Task-objectives-0") .queryParam("points", "25").queryParam("text", "A very difficult test").build(); - PutMethod newTaskMethod = createPut(newTaskUri, MediaType.APPLICATION_JSON, true); - int newTaskCode = c.executeMethod(newTaskMethod); - assertTrue(newTaskCode == 200 || newTaskCode == 201); - String newTaskBody = newTaskMethod.getResponseBodyAsString(); + HttpPut newTaskMethod = conn.createPut(newTaskUri, MediaType.APPLICATION_JSON, true); + HttpResponse newTaskCode = conn.execute(newTaskMethod); + assertTrue(newTaskCode.getStatusLine().getStatusCode() == 200 || newTaskCode.getStatusLine().getStatusCode() == 201); + String newTaskBody = EntityUtils.toString(newTaskCode.getEntity()); CourseNodeVO taskNode = parse(newTaskBody, CourseNodeVO.class); assertNotNull(taskNode); assertNotNull(taskNode.getId()); @@ -439,14 +440,15 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("scoreMin", new Float(1.5)) .queryParam("scoreMax", 10) .build(); - PutMethod taskConfigMethod = createPut(taskConfigUri, MediaType.APPLICATION_JSON, true); - int taskConfigCode = c.executeMethod(taskConfigMethod); - assertTrue(taskConfigCode == 200 || taskConfigCode == 201); + HttpPut taskConfigMethod = conn.createPut(taskConfigUri, MediaType.APPLICATION_JSON, true); + HttpResponse taskConfigCode = conn.execute(taskConfigMethod); + assertTrue(taskConfigCode.getStatusLine().getStatusCode() == 200 || taskConfigCode.getStatusLine().getStatusCode() == 201); + EntityUtils.consume(taskConfigCode.getEntity()); - GetMethod getTaskConfig = createGet(taskConfigUri, MediaType.APPLICATION_JSON, true); - taskConfigCode = c.executeMethod(getTaskConfig); - assertTrue(taskConfigCode == 200 || taskConfigCode == 201); - String taskConfigBody = getTaskConfig.getResponseBodyAsString(); + HttpGet getTaskConfig = conn.createGet(taskConfigUri, MediaType.APPLICATION_JSON, true); + taskConfigCode = conn.execute(getTaskConfig); + assertTrue(taskConfigCode.getStatusLine().getStatusCode() == 200 || taskConfigCode.getStatusLine().getStatusCode() == 201); + String taskConfigBody = EntityUtils.toString(taskConfigCode.getEntity()); TaskConfigVO taskConfig = parse(taskConfigBody, TaskConfigVO.class); assertNotNull(taskConfig); assertTrue(!taskConfig.getIsAssignmentEnabled());//default is true @@ -460,10 +462,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position", "5").queryParam("shortTitle", "Assessment-0") .queryParam("longTitle", "Assessment-long-0") .queryParam("objectives", "Assessment-objectives-0").build(); - PutMethod newAssessmentMethod = createPut(newAssessmentUri, MediaType.APPLICATION_JSON, true); - int newAssessmentCode = c.executeMethod(newAssessmentMethod); - assertTrue(newAssessmentCode == 200 || newAssessmentCode == 201); - String newAssessmentBody = newAssessmentMethod.getResponseBodyAsString(); + HttpPut newAssessmentMethod = conn.createPut(newAssessmentUri, MediaType.APPLICATION_JSON, true); + HttpResponse newAssessmentCode = conn.execute(newAssessmentMethod); + assertTrue(newAssessmentCode.getStatusLine().getStatusCode() == 200 || newAssessmentCode.getStatusLine().getStatusCode() == 201); + String newAssessmentBody = EntityUtils.toString(newAssessmentCode.getEntity()); CourseNodeVO assessmentNode = parse(newAssessmentBody, CourseNodeVO.class); assertNotNull(assessmentNode); assertNotNull(assessmentNode.getId()); @@ -478,10 +480,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position", "6").queryParam("shortTitle", "Contact-0") .queryParam("longTitle", "Contact-long-0") .queryParam("objectives", "Contact-objectives-0").build(); - PutMethod newContactMethod = createPut(newContactUri, MediaType.APPLICATION_JSON, true); - int newContactCode = c.executeMethod(newContactMethod); - assertEquals(200, newContactCode); - String newContactBody = newContactMethod.getResponseBodyAsString(); + HttpPut newContactMethod = conn.createPut(newContactUri, MediaType.APPLICATION_JSON, true); + HttpResponse newContactCode = conn.execute(newContactMethod); + assertEquals(200, newContactCode.getStatusLine().getStatusCode()); + String newContactBody = EntityUtils.toString(newContactCode.getEntity()); CourseNodeVO contactNode = parse(newContactBody, CourseNodeVO.class); assertNotNull(contactNode); assertNotNull(contactNode.getId()); @@ -496,27 +498,26 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("position", "7").queryParam("shortTitle", "Enrollment-0") .queryParam("longTitle", "Enrollment-long-0") .queryParam("objectives", "Enrollment-objectives-0").build(); - PutMethod newENMethod = createPut(newENUri, MediaType.APPLICATION_JSON, true); - int newENCode = c.executeMethod(newENMethod); - assertEquals(406, newENCode); + HttpPut newENMethod = conn.createPut(newENUri, MediaType.APPLICATION_JSON, true); + HttpResponse newENCode = conn.execute(newENMethod); + assertEquals(406, newENCode.getStatusLine().getStatusCode()); + EntityUtils.consume(newENCode.getEntity()); //create an enrollment node - newENUri = getElementsUri(course).path("enrollment").build(); - newENMethod = createPut(newENUri, MediaType.APPLICATION_JSON, true); - newENMethod.setQueryString(new NameValuePair[]{ - new NameValuePair("parentNodeId", course.getEditorRootNodeId()), - new NameValuePair("position", "7"), - new NameValuePair("shortTitle", "Enrollment-0"), - new NameValuePair("longTitle", "Enrollment-long-0"), - new NameValuePair("objectives", "Enrollment-objectives-0"), - new NameValuePair("groups",group.getKey().toString()), - new NameValuePair("cancelEnabled","true") - }); - - newENCode = c.executeMethod(newENMethod); - assertEquals(200, newENCode); - - String newENBody = newENMethod.getResponseBodyAsString(); + newENUri = getElementsUri(course).path("enrollment") + .queryParam("parentNodeId", course.getEditorRootNodeId()) + .queryParam("position", "7") + .queryParam("shortTitle", "Enrollment-0") + .queryParam("longTitle", "Enrollment-long-0") + .queryParam("objectives", "Enrollment-objectives-0") + .queryParam("groups",group.getKey().toString()) + .queryParam("cancelEnabled","true").build(); + newENMethod = conn.createPut(newENUri, MediaType.APPLICATION_JSON, true); + + newENCode = conn.execute(newENMethod); + assertEquals(200, newENCode.getStatusLine().getStatusCode()); + + String newENBody = EntityUtils.toString(newENCode.getEntity()); CourseNodeVO enNode = parse(newENBody, CourseNodeVO.class); assertNotNull(enNode); assertNotNull(enNode.getId()); @@ -530,21 +531,20 @@ public class CoursesElementsTest extends OlatJerseyTestCase { assertNotNull(cpUrl); File cp = new File(cpUrl.toURI()); - PutMethod qtiRepoMethod = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - qtiRepoMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] qtiRepoParts = { - new FilePart("file", cp), - new StringPart("filename","qti-demo.zip"), - new StringPart("resourcename","QTI demo"), - new StringPart("displayname","QTI demo") - }; - qtiRepoMethod.setRequestEntity(new MultipartRequestEntity(qtiRepoParts, qtiRepoMethod.getParams())); - - int qtiRepoCode = c.executeMethod(qtiRepoMethod); - assertTrue(qtiRepoCode == 200 || qtiRepoCode == 201); - - String qtiRepoBody = qtiRepoMethod.getResponseBodyAsString(); - qtiRepoMethod.releaseConnection(); + URI repoEntriesUri = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpPut qtiRepoMethod = conn.createPut(repoEntriesUri, MediaType.APPLICATION_JSON, true); + qtiRepoMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(cp)); + entity.addPart("filename", new StringBody("qti-demo.zip")); + entity.addPart("resourcename", new StringBody("QTI demo")); + entity.addPart("displayname", new StringBody("QTI demo")); + qtiRepoMethod.setEntity(entity); + + HttpResponse qtiRepoCode = conn.execute(qtiRepoMethod); + assertTrue(qtiRepoCode.getStatusLine().getStatusCode() == 200 || qtiRepoCode.getStatusLine().getStatusCode() == 201); + + String qtiRepoBody = EntityUtils.toString(qtiRepoCode.getEntity()); RepositoryEntryVO newTestVO = parse(qtiRepoBody, RepositoryEntryVO.class); assertNotNull(newTestVO); @@ -561,10 +561,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("longTitle", "Test-long-0") .queryParam("objectives", "Test-objectives-0") .queryParam("testResourceableId", key).build(); - PutMethod newTestMethod = createPut(newTestUri, MediaType.APPLICATION_JSON, true); - int newTestCode = c.executeMethod(newTestMethod); - assertTrue(newTestCode == 200 || newTestCode == 201); - String newTestBody = newTestMethod.getResponseBodyAsString(); + HttpPut newTestMethod = conn.createPut(newTestUri, MediaType.APPLICATION_JSON, true); + HttpResponse newTestCode = conn.execute(newTestMethod); + assertTrue(newTestCode.getStatusLine().getStatusCode() == 200 || newTestCode.getStatusLine().getStatusCode() == 201); + String newTestBody = EntityUtils.toString(newTestCode.getEntity()); CourseNodeVO testNode = parse(newTestBody, CourseNodeVO.class); assertNotNull(testNode); assertNotNull(testNode.getId()); @@ -573,31 +573,32 @@ public class CoursesElementsTest extends OlatJerseyTestCase { // configure test node URI testConfigUri = getElementsUri(course).path("test/"+testNode.getId()+"/configuration") - .queryParam("allowCancel", Boolean.TRUE) - .queryParam("allowNavigation", Boolean.TRUE) - .queryParam("allowSuspend", Boolean.TRUE) - .queryParam("numAttempts", 10) - .queryParam("sequencePresentation", AssessmentInstance.QMD_ENTRY_SEQUENCE_ITEM) - .queryParam("showNavigation", Boolean.TRUE) - .queryParam("showQuestionTitle", Boolean.TRUE) - .queryParam("showResultsAfterFinish", Boolean.TRUE) - .queryParam("showResultsDependendOnDate", Boolean.TRUE) - .queryParam("showResultsOnHomepage", key) - .queryParam("showScoreInfo", Boolean.TRUE) - .queryParam("showScoreProgress", Boolean.TRUE) - .queryParam("showSectionsOnly", Boolean.TRUE) - .queryParam("summaryPresentation", AssessmentInstance.QMD_ENTRY_SUMMARY_DETAILED) - .queryParam("startDate", new Long(1280444400))//new Date(1280444400)) - .queryParam("endDate", new Long(1293667200))//new Date(1293667200)) - .build(); - PutMethod testConfigMethod = createPut(testConfigUri, MediaType.APPLICATION_JSON, true); - int testConfigCode = c.executeMethod(testConfigMethod); - assertTrue(testConfigCode == 200 || testConfigCode == 201); - - GetMethod getTestConfig = createGet(testConfigUri, MediaType.APPLICATION_JSON, true); - testConfigCode = c.executeMethod(getTestConfig); - assertTrue(testConfigCode == 200 || testConfigCode == 201); - String testConfigBody = getTestConfig.getResponseBodyAsString(); + .queryParam("allowCancel", Boolean.TRUE) + .queryParam("allowNavigation", Boolean.TRUE) + .queryParam("allowSuspend", Boolean.TRUE) + .queryParam("numAttempts", 10) + .queryParam("sequencePresentation", AssessmentInstance.QMD_ENTRY_SEQUENCE_ITEM) + .queryParam("showNavigation", Boolean.TRUE) + .queryParam("showQuestionTitle", Boolean.TRUE) + .queryParam("showResultsAfterFinish", Boolean.TRUE) + .queryParam("showResultsDependendOnDate", Boolean.TRUE) + .queryParam("showResultsOnHomepage", key) + .queryParam("showScoreInfo", Boolean.TRUE) + .queryParam("showScoreProgress", Boolean.TRUE) + .queryParam("showSectionsOnly", Boolean.TRUE) + .queryParam("summaryPresentation", AssessmentInstance.QMD_ENTRY_SUMMARY_DETAILED) + .queryParam("startDate", new Long(1280444400))//new Date(1280444400)) + .queryParam("endDate", new Long(1293667200))//new Date(1293667200)) + .build(); + HttpPut testConfigMethod = conn.createPut(testConfigUri, MediaType.APPLICATION_JSON, true); + HttpResponse testConfigCode = conn.execute(testConfigMethod); + assertTrue(testConfigCode.getStatusLine().getStatusCode() == 200 || testConfigCode.getStatusLine().getStatusCode() == 201); + EntityUtils.consume(testConfigCode.getEntity()); + + HttpGet getTestConfig = conn.createGet(testConfigUri, MediaType.APPLICATION_JSON, true); + testConfigCode = conn.execute(getTestConfig); + assertTrue(testConfigCode.getStatusLine().getStatusCode() == 200 || testConfigCode.getStatusLine().getStatusCode() == 201); + String testConfigBody = EntityUtils.toString(testConfigCode.getEntity()); TestConfigVO testConfig = parse(testConfigBody, TestConfigVO.class); assertTrue(testConfig.getNumAttempts() == 10); assertTrue(testConfig.getAllowCancel()); @@ -608,19 +609,19 @@ public class CoursesElementsTest extends OlatJerseyTestCase { assertNotNull(newSurveyUrl); File surveyFile = new File(newSurveyUrl.toURI()); - PutMethod surveyRepoMethod = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - surveyRepoMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] newSurveyParts = { - new FilePart("file", surveyFile), - new StringPart("filename","questionnaire-demo.zip"), - new StringPart("resourcename","Questionnaire demo"), - new StringPart("displayname","Questionnaire demo") - }; - surveyRepoMethod.setRequestEntity(new MultipartRequestEntity(newSurveyParts, surveyRepoMethod.getParams())); - int surveyRepoCode = c.executeMethod(surveyRepoMethod); - assertTrue(surveyRepoCode == 200 || surveyRepoCode == 201); - - String surveyRepoBody = surveyRepoMethod.getResponseBodyAsString(); + URI repoEntriesUri2 = UriBuilder.fromUri(getContextURI()).path("repo").path("entries").build(); + HttpPut surveyRepoMethod = conn.createPut(repoEntriesUri2, MediaType.APPLICATION_JSON, true); + surveyRepoMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity surveyEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + surveyEntity.addPart("file", new FileBody(surveyFile)); + surveyEntity.addPart("filename", new StringBody("questionnaire-demo.zip")); + surveyEntity.addPart("resourcename", new StringBody("Questionnaire demo")); + surveyEntity.addPart("displayname", new StringBody("Questionnaire demo")); + surveyRepoMethod.setEntity(surveyEntity); + HttpResponse surveyRepoCode = conn.execute(surveyRepoMethod); + assertTrue(surveyRepoCode.getStatusLine().getStatusCode() == 200 || surveyRepoCode.getStatusLine().getStatusCode() == 201); + + String surveyRepoBody = EntityUtils.toString(surveyRepoCode.getEntity()); RepositoryEntryVO newSurveyVO = parse(surveyRepoBody, RepositoryEntryVO.class); assertNotNull(newSurveyVO); @@ -637,10 +638,10 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("longTitle", "Survey-long-0") .queryParam("objectives", "Survey-objectives-0") .queryParam("surveyResourceableId", surveyKey).build(); - PutMethod newSurveyMethod = createPut(newSurveyUri, MediaType.APPLICATION_JSON, true); - int newSurveyCode = c.executeMethod(newSurveyMethod); - assertTrue(newSurveyCode == 200 || newSurveyCode == 201); - String newSurveyBody = newSurveyMethod.getResponseBodyAsString(); + HttpPut newSurveyMethod = conn.createPut(newSurveyUri, MediaType.APPLICATION_JSON, true); + HttpResponse newSurveyCode = conn.execute(newSurveyMethod); + assertTrue(newSurveyCode.getStatusLine().getStatusCode() == 200 || newSurveyCode.getStatusLine().getStatusCode() == 201); + String newSurveyBody = EntityUtils.toString(newSurveyCode.getEntity()); CourseNodeVO surveyNode = parse(newSurveyBody, CourseNodeVO.class); assertNotNull(surveyNode); assertNotNull(surveyNode.getId()); @@ -657,34 +658,33 @@ public class CoursesElementsTest extends OlatJerseyTestCase { .queryParam("showQuestionTitle", Boolean.TRUE) .queryParam("showSectionsOnly", Boolean.TRUE) .build(); - PutMethod surveyConfigMethod = createPut(surveykConfigUri, MediaType.APPLICATION_JSON, true); - int surveyConfigCode = c.executeMethod(surveyConfigMethod); - assertTrue(surveyConfigCode == 200 || surveyConfigCode == 201); + HttpPut surveyConfigMethod = conn.createPut(surveykConfigUri, MediaType.APPLICATION_JSON, true); + HttpResponse surveyConfigCode = conn.execute(surveyConfigMethod); + assertTrue(surveyConfigCode.getStatusLine().getStatusCode() == 200 || surveyConfigCode.getStatusLine().getStatusCode() == 201); + EntityUtils.consume(surveyConfigCode.getEntity()); - GetMethod getSurveyConfig = createGet(surveykConfigUri, MediaType.APPLICATION_JSON, true); - surveyConfigCode = c.executeMethod(getSurveyConfig); - assertTrue(surveyConfigCode == 200 || surveyConfigCode == 201); - String surveyConfigBody = getSurveyConfig.getResponseBodyAsString(); + HttpGet getSurveyConfig = conn.createGet(surveykConfigUri, MediaType.APPLICATION_JSON, true); + surveyConfigCode = conn.execute(getSurveyConfig); + assertTrue(surveyConfigCode.getStatusLine().getStatusCode() == 200 || surveyConfigCode.getStatusLine().getStatusCode() == 201); + String surveyConfigBody =EntityUtils.toString(surveyConfigCode.getEntity()); SurveyConfigVO surveyConfig = parse(surveyConfigBody, SurveyConfigVO.class); assertNotNull(surveyConfig); assertTrue(surveyConfig.getAllowCancel()); //create an external page node - URI newTUUri = getElementsUri(course).path("externalpage").build(); - PutMethod newTUMethod = createPut(newTUUri, MediaType.APPLICATION_JSON, true); - newTUMethod.setQueryString(new NameValuePair[]{ - new NameValuePair("parentNodeId", course.getEditorRootNodeId()), - new NameValuePair("position", "10"), - new NameValuePair("shortTitle", "ExternalPage-0"), - new NameValuePair("longTitle", "ExternalPage-long-0"), - new NameValuePair("objectives", "ExternalPage-objectives-0"), - new NameValuePair("url","http://www.olat.org") - }); - - int newTUCode = c.executeMethod(newTUMethod); - assertEquals(200, newTUCode); - - String newTUBody = newTUMethod.getResponseBodyAsString(); + URI newTUUri = getElementsUri(course).path("externalpage") + .queryParam("parentNodeId", course.getEditorRootNodeId()) + .queryParam("position", "10") + .queryParam("shortTitle", "ExternalPage-0") + .queryParam("longTitle", "ExternalPage-long-0") + .queryParam("objectives", "ExternalPage-objectives-0") + .queryParam("url","http://www.olat.org").build(); + HttpPut newTUMethod = conn.createPut(newTUUri, MediaType.APPLICATION_JSON, true); + + HttpResponse newTUCode = conn.execute(newTUMethod); + assertEquals(200, newTUCode.getStatusLine().getStatusCode()); + + String newTUBody = EntityUtils.toString(newTUCode.getEntity()); CourseNodeVO tuNode = parse(newTUBody, CourseNodeVO.class); assertNotNull(tuNode); assertNotNull(tuNode.getId()); @@ -758,15 +758,12 @@ public class CoursesElementsTest extends OlatJerseyTestCase { childNode = child.getCourseNode(); URI attachTaskFileUri = getElementsUri(course).path("task").path(childNode.getIdent()).path("file") .queryParam("filename", "singlepage.html").build(); - PutMethod taskFileMethod = createPut(attachTaskFileUri, MediaType.APPLICATION_JSON, true); - taskFileMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] taskFileParts = { - new FilePart("file", page), - new StringPart("filename", page.getName()) - }; - taskFileMethod.setRequestEntity(new MultipartRequestEntity(taskFileParts, method.getParams())); - int taskFileCode = c.executeMethod(taskFileMethod); - assertEquals(200, taskFileCode); + HttpPut taskFileMethod = conn.createPut(attachTaskFileUri, MediaType.APPLICATION_JSON, true); + taskFileMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(taskFileMethod, page.getName(), page); + + HttpResponse taskFileCode = conn.execute(taskFileMethod); + assertEquals(200, taskFileCode.getStatusLine().getStatusCode()); String taskFolderPath = TACourseNode.getTaskFolderPathRelToFolderRoot(realCourse, childNode); OlatRootFolderImpl taskFolder = new OlatRootFolderImpl(taskFolderPath, null); VFSLeaf singleFile = (VFSLeaf) taskFolder.resolve("/" + "singlepage.html"); @@ -775,16 +772,17 @@ public class CoursesElementsTest extends OlatJerseyTestCase { @Test //fxdiff FXOLAT-122: course management - public void testUpdateRootNodeCoursePost() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testUpdateRootNodeCoursePost() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an empty course URI uri = getCoursesUri().queryParam("shortTitle", "course4").queryParam("title", "course4 long name").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + CourseVO course = parse(body, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); @@ -792,19 +790,18 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //update the root node URI rootUri = getElementsUri(course).path("structure").path(course.getEditorRootNodeId()).build(); - PostMethod updateMethod = createPost(rootUri, MediaType.APPLICATION_JSON, true); - updateMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new StringPart("shortTitle", "Structure-0b"), - new StringPart("longTitle", "Structure-long-0b"), - new StringPart("objectives", "Structure-objectives-0b") - }; - updateMethod.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int newStructureCode = c.executeMethod(updateMethod); - assertTrue(newStructureCode == 200 || newStructureCode == 201); + HttpPost updateMethod = conn.createPost(rootUri, MediaType.APPLICATION_JSON, true); + updateMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("shortTitle", new StringBody("Structure-0b")); + entity.addPart("longTitle", new StringBody("Structure-long-0b")); + entity.addPart("objectives", new StringBody("Structure-objectives-0b")); + updateMethod.setEntity(entity); + + HttpResponse newStructureCode = conn.execute(updateMethod); + assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); //check the response - String newStructureBody = updateMethod.getResponseBodyAsString(); + String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); @@ -828,15 +825,16 @@ public class CoursesElementsTest extends OlatJerseyTestCase { @Test //fxdiff FXOLAT-122: course management public void testUpdateRootNodeCoursePostWithFile() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an empty course URI uri = getCoursesUri().queryParam("shortTitle", "course5").queryParam("title", "course5 long name").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + CourseVO course = parse(body, CourseVO.class); assertNotNull(course); assertNotNull(course.getKey()); @@ -849,25 +847,24 @@ public class CoursesElementsTest extends OlatJerseyTestCase { //update the root node URI rootUri = getElementsUri(course).path("structure").path(course.getEditorRootNodeId()).build(); - PostMethod newStructureMethod = createPost(rootUri, MediaType.APPLICATION_JSON, true); - newStructureMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", page), - new StringPart("filename", page.getName()), - new StringPart("parentNodeId",course.getEditorRootNodeId()), - new StringPart("position","1"), - new StringPart("shortTitle", "Structure-0-with-file"), - new StringPart("longTitle", "Structure-long-0-with-file"), - new StringPart("objectives", "Structure-objectives-0-with-file"), - new StringPart("displayType", "file") - }; - newStructureMethod.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - - int newStructureCode = c.executeMethod(newStructureMethod); - assertTrue(newStructureCode == 200 || newStructureCode == 201); + HttpPost newStructureMethod = conn.createPost(rootUri, MediaType.APPLICATION_JSON, true); + newStructureMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(page)); + entity.addPart("filename", new StringBody(page.getName())); + entity.addPart("parentNodeId", new StringBody(course.getEditorRootNodeId())); + entity.addPart("position", new StringBody("1")); + entity.addPart("shortTitle", new StringBody("Structure-0-with-file")); + entity.addPart("longTitle", new StringBody("Structure-long-0-with-file")); + entity.addPart("objectives", new StringBody("Structure-objectives-0-with-file")); + entity.addPart("displayType", new StringBody("file")); + newStructureMethod.setEntity(entity); + + + HttpResponse newStructureCode = conn.execute(newStructureMethod); + assertTrue(newStructureCode.getStatusLine().getStatusCode() == 200 || newStructureCode.getStatusLine().getStatusCode() == 201); //check the response - String newStructureBody = newStructureMethod.getResponseBodyAsString(); + String newStructureBody = EntityUtils.toString(newStructureCode.getEntity()); CourseNodeVO structureNode = parse(newStructureBody, CourseNodeVO.class); assertNotNull(structureNode); assertNotNull(structureNode.getId()); diff --git a/src/test/java/org/olat/restapi/CoursesFoldersTest.java b/src/test/java/org/olat/restapi/CoursesFoldersTest.java index 486c96f06865243b6a4018dec96fb292f52f241a..ffed10d5768fd5e9274d2fb1993ed4bcfcbf8aec 100644 --- a/src/test/java/org/olat/restapi/CoursesFoldersTest.java +++ b/src/test/java/org/olat/restapi/CoursesFoldersTest.java @@ -42,15 +42,10 @@ import java.util.Locale; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.multipart.FilePart; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; import org.junit.Before; import org.junit.Test; import org.olat.basesecurity.BaseSecurityManager; @@ -151,7 +146,8 @@ public class CoursesFoldersTest extends OlatJerseyTestCase { @Test public void testUploadFile() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getNodeURI()).path("files").build(); @@ -160,15 +156,11 @@ public class CoursesFoldersTest extends OlatJerseyTestCase { assertNotNull(fileUrl); File file = new File(fileUrl.toURI()); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", file), - new StringPart("filename", file.getName()) - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(method, file.getName(), file); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode)bcNode, course1.getCourseEnvironment()); VFSItem item = folder.resolve(file.getName()); @@ -176,13 +168,14 @@ public class CoursesFoldersTest extends OlatJerseyTestCase { } @Test - public void testCreateFolder() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testCreateFolder() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getNodeURI()).path("files").path("RootFolder").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode)bcNode, course1.getCourseEnvironment()); VFSItem item = folder.resolve("RootFolder"); @@ -191,13 +184,14 @@ public class CoursesFoldersTest extends OlatJerseyTestCase { } @Test - public void testCreateFolders() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testCreateFolders() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getNodeURI()).path("files").path("NewFolder1").path("NewFolder2").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode)bcNode, course1.getCourseEnvironment()); VFSItem item = folder.resolve("NewFolder1"); @@ -211,7 +205,7 @@ public class CoursesFoldersTest extends OlatJerseyTestCase { } @Test - public void deleteFolder() throws IOException { + public void deleteFolder() throws IOException, URISyntaxException { //add some folders OlatNamedContainerImpl folder = BCCourseNode.getNodeFolderContainer((BCCourseNode)bcNode, course1.getCourseEnvironment()); VFSItem item = folder.resolve("FolderToDelete"); @@ -219,12 +213,13 @@ public class CoursesFoldersTest extends OlatJerseyTestCase { folder.createChildContainer("FolderToDelete"); } - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getNodeURI()).path("files").path("FolderToDelete").build(); - DeleteMethod method = createDelete(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpDelete method = conn.createDelete(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); VFSItem deletedItem = folder.resolve("FolderToDelete"); assertNull(deletedItem); diff --git a/src/test/java/org/olat/restapi/CoursesForumsTest.java b/src/test/java/org/olat/restapi/CoursesForumsTest.java index babc96672e642709381132ecfaade3e688a7208c..e95a49ed67e2b8c4aaabe4c9d578e3a3ac67461f 100644 --- a/src/test/java/org/olat/restapi/CoursesForumsTest.java +++ b/src/test/java/org/olat/restapi/CoursesForumsTest.java @@ -47,7 +47,6 @@ import org.olat.modules.fo.restapi.ForumVO; import org.olat.modules.fo.restapi.ForumVOes; import org.olat.modules.fo.restapi.MessageVOes; import org.olat.restapi.repository.course.CoursesWebService; -import org.olat.restapi.support.vo.CourseInfoVOes; import org.olat.test.OlatJerseyTestCase; /** diff --git a/src/test/java/org/olat/restapi/CoursesResourcesFoldersTest.java b/src/test/java/org/olat/restapi/CoursesResourcesFoldersTest.java index 679200d8b4c2ee6b2cab5f2ec6cd0f826889379b..767e01f36a9e95d7544e36b6a542bee5cf648c93 100644 --- a/src/test/java/org/olat/restapi/CoursesResourcesFoldersTest.java +++ b/src/test/java/org/olat/restapi/CoursesResourcesFoldersTest.java @@ -35,14 +35,16 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.util.EntityUtils; import org.junit.Before; import org.junit.Test; import org.olat.basesecurity.BaseSecurityManager; @@ -90,28 +92,30 @@ public class CoursesResourcesFoldersTest extends OlatJerseyTestCase { } @Test - public void testGetFiles() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetFiles() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getCourseFolderURI()).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); - String body = method.getResponseBodyAsString(); + InputStream body = response.getEntity().getContent(); List<LinkVO> links = parseLinkArray(body); assertNotNull(links); assertEquals(3, links.size()); } @Test - public void testGetFilesDeeper() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetFilesDeeper() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getCourseFolderURI()).path("SubDir").path("SubSubDir").path("SubSubSubDir").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); - String body = method.getResponseBodyAsString(); + InputStream body = response.getEntity().getContent(); List<LinkVO> links = parseLinkArray(body); assertNotNull(links); assertEquals(1, links.size()); @@ -119,20 +123,21 @@ public class CoursesResourcesFoldersTest extends OlatJerseyTestCase { } @Test - public void testGetFileDeep() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetFileDeep() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getCourseFolderURI()).path("SubDir").path("SubSubDir").path("SubSubSubDir") .path("3_singlepage.html").build(); - GetMethod method = createGet(uri, "*/*", true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpGet method = conn.createGet(uri, "*/*", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); - String body = method.getResponseBodyAsString(); + String body = EntityUtils.toString(response.getEntity()); assertNotNull(body); assertTrue(body.startsWith("<html>")); String contentType = null; - for(Header header:method.getResponseHeaders()){ + for(Header header:response.getAllHeaders()){ if("Content-Type".equals(header.getName())) { contentType = header.getValue(); break; diff --git a/src/test/java/org/olat/restapi/CoursesTest.java b/src/test/java/org/olat/restapi/CoursesTest.java index e7474766cfabf12e982057d9b8bfc111eb82b33d..c50e6138e0775105e78b4207cebaed11aa9d77d8 100644 --- a/src/test/java/org/olat/restapi/CoursesTest.java +++ b/src/test/java/org/olat/restapi/CoursesTest.java @@ -40,11 +40,9 @@ import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.PutMethod; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Before; @@ -89,13 +87,15 @@ public class CoursesTest extends OlatJerseyTestCase { } @Test - public void testGetCourses() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetCourses() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); - HttpMethod method = createGet("/repo/courses", MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + URI request = UriBuilder.fromUri(getContextURI()).path("/repo/courses").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<CourseVO> courses = parseCourseArray(body); assertNotNull(courses); assertTrue(courses.size() >= 2); @@ -116,16 +116,16 @@ public class CoursesTest extends OlatJerseyTestCase { } @Test - public void testGetCoursesWithPaging() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetCoursesWithPaging() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses") .queryParam("start", "0").queryParam("limit", "1").build(); - - HttpMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); CourseVOes courses = parse(body, CourseVOes.class); assertNotNull(courses); assertNotNull(courses.getCourses()); @@ -133,16 +133,17 @@ public class CoursesTest extends OlatJerseyTestCase { } @Test - public void testCreateEmptyCourse() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testCreateEmptyCourse() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("courses") .queryParam("shortTitle", "course3").queryParam("title", "course3 long name").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); CourseVO course = parse(body, CourseVO.class); assertNotNull(course); assertEquals("course3", course.getTitle()); @@ -168,7 +169,7 @@ public class CoursesTest extends OlatJerseyTestCase { assertNotNull(infos); } - protected List<CourseVO> parseCourseArray(String body) { + protected List<CourseVO> parseCourseArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<CourseVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/FolderTest.java b/src/test/java/org/olat/restapi/FolderTest.java index 72ad3c1af8d59a3742414ed406c0cd8da59c2cfc..41aaa25b0a24da130426e194001a44705cd91514 100644 --- a/src/test/java/org/olat/restapi/FolderTest.java +++ b/src/test/java/org/olat/restapi/FolderTest.java @@ -19,8 +19,8 @@ */ package org.olat.restapi; -import static org.olat.core.util.vfs.restapi.VFSWebservice.normalize; import static org.junit.Assert.assertEquals; +import static org.olat.core.util.vfs.restapi.VFSWebservice.normalize; import org.junit.Test; /** diff --git a/src/test/java/org/olat/restapi/ForumTest.java b/src/test/java/org/olat/restapi/ForumTest.java index 92822a0e96e8568a567d05b2b467de465b19cf6f..9c6121f21460e4ba270abac9e05e81293060d633 100644 --- a/src/test/java/org/olat/restapi/ForumTest.java +++ b/src/test/java/org/olat/restapi/ForumTest.java @@ -46,19 +46,13 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.httpclient.methods.multipart.FilePart; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Before; @@ -130,80 +124,86 @@ public class ForumTest extends OlatJerseyTestCase { } @Test - public void testGetThreads() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetThreads() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = getForumUriBuilder().path("threads").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<MessageVO> threads = parseMessageArray(body); - method.releaseConnection(); + assertNotNull(threads); assertFalse(threads.isEmpty()); } @Test - public void testGetThreadsWithPaging() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetThreadsWithPaging() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = getForumUriBuilder().path("threads") .queryParam("start", "0").queryParam("limit", "2").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVOes threads = parse(body, MessageVOes.class); - method.releaseConnection(); + assertNotNull(threads); assertNotNull(threads.getMessages()); assertTrue(threads.getTotalCount() >= 2); } @Test - public void testGetThread() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetThread() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<MessageVO> threads = parseMessageArray(body); - method.releaseConnection(); + assertNotNull(threads); assertFalse(threads.isEmpty()); } @Test - public void testGetThreadWithPaging() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetThreadWithPaging() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()) .queryParam("start", "0").queryParam("limit", "2").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVOes threads = parse(body, MessageVOes.class); - method.releaseConnection(); + assertNotNull(threads); assertNotNull(threads.getMessages()); assertTrue(threads.getTotalCount() >= 2); } @Test - public void testNewThread() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testNewThread() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = getForumUriBuilder().path("threads").queryParam("authorKey", id1.getKey()) .queryParam("title", "New thread") .queryParam("body", "A very interesting thread").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + HttpPut method = conn.createPut( +uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO thread = parse(body, MessageVO.class); assertNotNull(thread); assertNotNull(thread.getKey()); @@ -223,17 +223,19 @@ public class ForumTest extends OlatJerseyTestCase { } @Test - public void testNewMessage() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testNewMessage() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()) .queryParam("authorKey", id1.getKey()) .queryParam("title", "New message") .queryParam("body", "A very interesting response in Thread-1").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + HttpPut method = conn.createPut( +uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO message = parse(body, MessageVO.class); assertNotNull(message); assertNotNull(message.getKey()); @@ -292,16 +294,17 @@ public class ForumTest extends OlatJerseyTestCase { @Test public void testUploadAttachment() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()) .queryParam("authorKey", id1.getKey()) .queryParam("title", "New message with attachment ") .queryParam("body", "A very interesting response in Thread-1 with an attachment").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO message = parse(body, MessageVO.class); assertNotNull(message); @@ -312,16 +315,11 @@ public class ForumTest extends OlatJerseyTestCase { //upload portrait URI attachUri = getForumUriBuilder().path("posts").path(message.getKey().toString()).path("attachments").build(); - PostMethod attachMethod = createPost(attachUri, MediaType.APPLICATION_JSON, true); - attachMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", portrait), - new StringPart("filename","portrait.jpg") - }; - attachMethod.setRequestEntity(new MultipartRequestEntity(parts, attachMethod.getParams())); - int attachCode = c.executeMethod(attachMethod); - assertEquals(200, attachCode); - attachMethod.releaseConnection(); + HttpPost attachMethod = conn.createPost(attachUri, MediaType.APPLICATION_JSON, true); + attachMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(attachMethod, "portrait.jpg", portrait); + HttpResponse attachResponse = conn.execute(attachMethod); + assertEquals(200, attachResponse.getStatusLine().getStatusCode()); //check if the file exists @@ -341,16 +339,17 @@ public class ForumTest extends OlatJerseyTestCase { @Test public void testUpload64Attachment() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()) .queryParam("authorKey", id1.getKey()) .queryParam("title", "New message with attachment ") .queryParam("body", "A very interesting response in Thread-1 with an attachment").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO message = parse(body, MessageVO.class); assertNotNull(message); @@ -361,14 +360,14 @@ public class ForumTest extends OlatJerseyTestCase { URI attachUri = getForumUriBuilder().path("posts").path(message.getKey().toString()).path("attachments").build(); byte[] portraitBytes = IOUtils.toByteArray(portraitStream); byte[] portrait64 = Base64.encodeBase64(portraitBytes, true); - PostMethod attachMethod = createPost(attachUri, MediaType.APPLICATION_JSON, true); - attachMethod.addRequestHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); - attachMethod.addParameter("file", new String(portrait64)); - attachMethod.addParameter("filename", "portrait64.jpg"); + HttpPost attachMethod = conn.createPost(attachUri, MediaType.APPLICATION_JSON, true); + + attachMethod.addHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); + conn.addEntity(attachMethod, new BasicNameValuePair("file", new String(portrait64)), + new BasicNameValuePair("filename", "portrait64.jpg")); - int attachCode = c.executeMethod(attachMethod); - assertEquals(200, attachCode); - attachMethod.releaseConnection(); + HttpResponse attachCode = conn.execute(attachMethod); + assertEquals(200, attachCode.getStatusLine().getStatusCode()); //check if the file exists ForumManager fm = ForumManager.getInstance(); @@ -387,7 +386,8 @@ public class ForumTest extends OlatJerseyTestCase { @Test public void testReplyWithTwoAttachments() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); ReplyVO vo = new ReplyVO(); vo.setTitle("Reply with attachment"); @@ -408,19 +408,17 @@ public class ForumTest extends OlatJerseyTestCase { files[1] = new File64VO("singlepage64.html", new String(index64)); vo.setAttachments(files); - String stringuifiedAuth = stringuified(vo); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()).build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - method.setRequestEntity(entity); - method.addRequestHeader("Accept-Language", "en"); - - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + method.addHeader("Accept-Language", "en"); + + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO message = parse(body, MessageVO.class); assertNotNull(message); - method.releaseConnection(); + assertNotNull(message.getAttachments()); assertEquals(2, message.getAttachments().length); @@ -429,9 +427,10 @@ public class ForumTest extends OlatJerseyTestCase { assertNotNull(title); String href = attachment.getHref(); URI attachmentUri = new URI(href); - GetMethod getAttachment = createGet(attachmentUri, "*/*", true); - int attachmentCode = c.executeMethod(getAttachment); - assertEquals(200, attachmentCode); + HttpGet getAttachment = conn.createGet(attachmentUri, "*/*", true); + HttpResponse attachmentCode = conn.execute(getAttachment); + assertEquals(200, attachmentCode.getStatusLine().getStatusCode()); + EntityUtils.consume(attachmentCode.getEntity()); } @@ -457,16 +456,17 @@ public class ForumTest extends OlatJerseyTestCase { @Test public void testUploadAttachmentWithFile64VO() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()) .queryParam("authorKey", id1.getKey()) .queryParam("title", "New message with attachment ") .queryParam("body", "A very interesting response in Thread-1 with an attachment").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO message = parse(body, MessageVO.class); assertNotNull(message); @@ -475,20 +475,17 @@ public class ForumTest extends OlatJerseyTestCase { assertNotNull(portraitStream); //upload portrait URI attachUri = getForumUriBuilder().path("posts").path(message.getKey().toString()).path("attachments").build(); - PutMethod attachMethod = createPut(attachUri, MediaType.APPLICATION_JSON, true); - attachMethod.addRequestHeader("Content-Type", MediaType.APPLICATION_JSON); + HttpPut attachMethod = conn.createPut(attachUri, MediaType.APPLICATION_JSON, true); + attachMethod.addHeader("Content-Type", MediaType.APPLICATION_JSON); byte[] portraitBytes = IOUtils.toByteArray(portraitStream); byte[] portrait64 = Base64.encodeBase64(portraitBytes, true); File64VO fileVo = new File64VO(); fileVo.setFile(new String(portrait64)); fileVo.setFilename("portrait64vo.jpg"); - String stringuifiedFileVo = stringuified(fileVo); - RequestEntity entity = new StringRequestEntity(stringuifiedFileVo, MediaType.APPLICATION_JSON, "UTF-8"); - attachMethod.setRequestEntity(entity); - int attachCode = c.executeMethod(attachMethod); - assertEquals(200, attachCode); - attachMethod.releaseConnection(); + conn.addJsonEntity(attachMethod, fileVo); + HttpResponse attachCode = conn.execute(attachMethod); + assertEquals(200, attachCode.getStatusLine().getStatusCode()); //check if the file exists ForumManager fm = ForumManager.getInstance(); @@ -511,16 +508,17 @@ public class ForumTest extends OlatJerseyTestCase { @Test public void testUploadAttachmentAndRename() throws IOException, URISyntaxException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()) .queryParam("authorKey", id1.getKey()) .queryParam("title", "New message with attachment ") .queryParam("body", "A very interesting response in Thread-1 with an attachment").build(); - PutMethod method = createPut(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + HttpPut method = conn.createPut(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVO message = parse(body, MessageVO.class); assertNotNull(message); @@ -531,49 +529,39 @@ public class ForumTest extends OlatJerseyTestCase { //upload portrait URI attachUri = getForumUriBuilder().path("posts").path(m1.getKey().toString()).path("attachments").build(); - PostMethod attachMethod = createPost(attachUri, MediaType.APPLICATION_JSON, true); - attachMethod.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", portrait), - new StringPart("filename","portrait.jpg") - }; - attachMethod.setRequestEntity(new MultipartRequestEntity(parts, attachMethod.getParams())); - int attachCode = c.executeMethod(attachMethod); - assertEquals(200, attachCode); - attachMethod.releaseConnection(); + HttpPost attachMethod = conn.createPost(attachUri, MediaType.APPLICATION_JSON, true); + attachMethod.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(attachMethod, "portrait.jpg", portrait); + HttpResponse attachCode = conn.execute(attachMethod); + assertEquals(200, attachCode.getStatusLine().getStatusCode()); + EntityUtils.consume(attachCode.getEntity()); + //upload portrait a second time URI attach2Uri = getForumUriBuilder().path("posts").path(m1.getKey().toString()).path("attachments").build(); - PostMethod attach2Method = createPost(attach2Uri, MediaType.APPLICATION_JSON, true); - attach2Method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts2 = { - new FilePart("file", portrait), - new StringPart("filename","portrait.jpg") - }; - attach2Method.setRequestEntity(new MultipartRequestEntity(parts2, attach2Method.getParams())); - int attach2Code = c.executeMethod(attach2Method); - assertEquals(200, attach2Code); - attach2Method.releaseConnection(); + HttpPost attach2Method = conn.createPost(attach2Uri, MediaType.APPLICATION_JSON, true); + attach2Method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(attach2Method, "portrait.jpg", portrait); + HttpResponse attach2Code = conn.execute(attach2Method); + assertEquals(200, attach2Code.getStatusLine().getStatusCode()); + EntityUtils.consume(attach2Code.getEntity()); // load the attachments - URI loadUri = getForumUriBuilder().path("posts").path(m1.getKey().toString()).path("attachments").build(); - GetMethod loadMethod = createGet(loadUri, MediaType.APPLICATION_JSON, true); - int loadCode = c.executeMethod(loadMethod); - assertEquals(200, loadCode); - InputStream loadBody = loadMethod.getResponseBodyAsStream(); + HttpGet loadMethod = conn.createGet(loadUri, MediaType.APPLICATION_JSON, true); + HttpResponse loadResponse = conn.execute(loadMethod); + assertEquals(200, loadResponse.getStatusLine().getStatusCode()); + InputStream loadBody = loadResponse.getEntity().getContent(); List<FileVO> files = parseFileArray(loadBody); assertNotNull(files); assertEquals(2, files.size()); - loadMethod.releaseConnection(); - } private UriBuilder getForumUriBuilder() { return UriBuilder.fromUri(getContextURI()).path("repo").path("forums").path(forum.getKey().toString()); } - protected List<MessageVO> parseMessageArray(String body) { + protected List<MessageVO> parseMessageArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<MessageVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/GroupFoldersTest.java b/src/test/java/org/olat/restapi/GroupFoldersTest.java index d1edbbb2ef4796a8289f65492723d0ef0a1789a6..41dbb80540994db851989a3e03e2377fe4b8a0a2 100644 --- a/src/test/java/org/olat/restapi/GroupFoldersTest.java +++ b/src/test/java/org/olat/restapi/GroupFoldersTest.java @@ -33,17 +33,20 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.commons.httpclient.methods.multipart.StringPart; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.StringBody; +import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Before; @@ -73,7 +76,6 @@ import org.olat.repository.RepositoryEntry; import org.olat.repository.RepositoryManager; import org.olat.resource.OLATResource; import org.olat.resource.OLATResourceManager; -import org.olat.restapi.UserMgmtTest; import org.olat.restapi.support.vo.FileVO; import org.olat.test.JunitTestHelper; import org.olat.test.OlatJerseyTestCase; @@ -179,21 +181,22 @@ public class GroupFoldersTest extends OlatJerseyTestCase { } @Test - public void testGetFolder() throws IOException { - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); + public void testGetFolder() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); - String request = "/groups/" + g1.getKey() + "/folder"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); assertNotNull(body); - method.releaseConnection(); + } @Test - public void testGetSubFolder() throws IOException { + public void testGetSubFolder() throws IOException, URISyntaxException { //create some sub folders CollaborationTools collabTools1 = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(g1); String folderRelPath = collabTools1.getFolderRelPath(); @@ -210,65 +213,63 @@ public class GroupFoldersTest extends OlatJerseyTestCase { assertNotNull(newFolder11); - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); //get root folder - String request0 = "/groups/" + g1.getKey() + "/folder/"; - GetMethod method0 = createGet(request0, MediaType.APPLICATION_JSON, true); - int code0 = c.executeMethod(method0); - assertEquals(200, code0); - InputStream body0 = method0.getResponseBodyAsStream(); + URI request0 = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/").build(); + HttpGet method0 = conn.createGet(request0, MediaType.APPLICATION_JSON, true); + HttpResponse code0 = conn.execute(method0); + assertEquals(200, code0.getStatusLine().getStatusCode()); + InputStream body0 = code0.getEntity().getContent(); assertNotNull(body0); List<FileVO> fileVos0 = parseFileArray(body0); assertNotNull(fileVos0); assertEquals(1, fileVos0.size()); - method0.releaseConnection(); //get sub folder - String request1 = "/groups/" + g1.getKey() + "/folder/New_folder_1"; - GetMethod method1 = createGet(request1, MediaType.APPLICATION_JSON, true); - int code1 = c.executeMethod(method1); - assertEquals(200, code1); - InputStream body1 = method1.getResponseBodyAsStream(); + URI request1 = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/New_folder_1").build(); + HttpGet method1 = conn.createGet(request1, MediaType.APPLICATION_JSON, true); + HttpResponse code1 = conn.execute(method1); + assertEquals(200, code1.getStatusLine().getStatusCode()); + InputStream body1 = code1.getEntity().getContent(); assertNotNull(body1); List<FileVO> fileVos1 = parseFileArray(body1); assertNotNull(fileVos1); assertEquals(1, fileVos1.size()); - method1.releaseConnection(); //get sub folder by link FileVO fileVO = fileVos1.get(0); - GetMethod brutMethod = new GetMethod(fileVO.getHref()); - brutMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - brutMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON); - int codeBrut = c.executeMethod(brutMethod); - assertEquals(200, codeBrut); - + URI fileUri = new URI(fileVO.getHref()); + HttpGet brutMethod = conn.createGet(fileUri, "*/*", true); + brutMethod.addHeader("Accept", MediaType.APPLICATION_JSON); + HttpResponse codeBrut = conn.execute(brutMethod); + assertEquals(200, codeBrut.getStatusLine().getStatusCode()); + EntityUtils.consume(codeBrut.getEntity()); // get sub sub folder - String request2 = "/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1"; - GetMethod method2 = createGet(request2, MediaType.APPLICATION_JSON, true); - int code2 = c.executeMethod(method2); - assertEquals(200, code2); - InputStream body2 = method2.getResponseBodyAsStream(); + URI request2 = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1").build(); + HttpGet method2 = conn.createGet(request2, MediaType.APPLICATION_JSON, true); + HttpResponse code2 = conn.execute(method2); + assertEquals(200, code2.getStatusLine().getStatusCode()); + InputStream body2 = code2.getEntity().getContent(); assertNotNull(body2); - method2.releaseConnection(); + EntityUtils.consume(code2.getEntity()); //get sub folder with end / - String request3 = "/groups/" + g1.getKey() + "/folder/New_folder_1/"; - GetMethod method3 = createGet(request3, MediaType.APPLICATION_JSON, true); - int code3 = c.executeMethod(method3); - assertEquals(200, code3); - InputStream body3 = method3.getResponseBodyAsStream(); + URI request3 = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/New_folder_1/").build(); + HttpGet method3 = conn.createGet(request3, MediaType.APPLICATION_JSON, true); + HttpResponse code3 = conn.execute(method3); + assertEquals(200, code3.getStatusLine().getStatusCode()); + InputStream body3 = code3.getEntity().getContent(); assertNotNull(body3); List<FileVO> fileVos3 = parseFileArray(body3); assertNotNull(fileVos3); assertEquals(1, fileVos3.size()); - method3.releaseConnection(); } @Test - public void testGetFile() throws IOException { + public void testGetFile() throws IOException, URISyntaxException { //create some sub folders and copy file CollaborationTools collabTools2 = CollaborationToolsFactory.getInstance().getOrCreateCollaborationTools(g2); String folderRelPath = collabTools2.getFolderRelPath(); @@ -288,59 +289,58 @@ public class GroupFoldersTest extends OlatJerseyTestCase { } // get the file - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); - String request = "/groups/" + g2.getKey() + "/folder/New_folder_2/portrait.jpg"; - GetMethod method = createGet(request, "*/*", true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g2.getKey() + "/folder/New_folder_2/portrait.jpg").build(); + HttpGet method = conn.createGet(request, "*/*", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); assertNotNull(body); assertTrue(10 > body.available()); assertEquals(new Long(file.getSize()), new Long(body.available())); - - method.releaseConnection(); } @Test - public void testCreateFolder() throws IOException { - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); - String request = "/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/New_folder_1_1_1"; - - PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - InputStream body = method.getResponseBodyAsStream(); - assertEquals(200, code); + public void testCreateFolder() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/New_folder_1_1_1").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + InputStream body = response.getEntity().getContent(); + assertEquals(200, response.getStatusLine().getStatusCode()); assertNotNull(body); - - method.releaseConnection(); } //@Test not working -> Jersey ignore the request and return 200 (why?) - public void testCreateFoldersWithSpecialCharacter() throws IOException { - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); - String request = "/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/New_folder_1 1 2"; - PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); + public void testCreateFoldersWithSpecialCharacter() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/New_folder_1 1 2").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); FileVO file = parse(body, FileVO.class); assertNotNull(file); } @Test - public void testCreateFoldersWithSpecialCharacter2() throws IOException { - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); - String request = "/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/"; - PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new StringPart("foldername","New folder 1 2 3") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); + public void testCreateFoldersWithSpecialCharacter2() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/folder/New_folder_1/New_folder_1_1/").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("foldername", new StringBody("New folder 1 2 3")); + method.setEntity(entity); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); FileVO file = parse(body, FileVO.class); assertNotNull(file); assertNotNull(file.getHref()); diff --git a/src/test/java/org/olat/restapi/GroupMgmtTest.java b/src/test/java/org/olat/restapi/GroupMgmtTest.java index a4dc0b6ec8abda7ef3b5120e8b9b6ade6eb00ac8..2c55183244d22d3571aea6daf0a4b1c81e40cd0a 100644 --- a/src/test/java/org/olat/restapi/GroupMgmtTest.java +++ b/src/test/java/org/olat/restapi/GroupMgmtTest.java @@ -33,20 +33,21 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.After; @@ -248,9 +249,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @After - @Override public void tearDown() throws Exception { - super.tearDown(); try { DBFactory.getInstance().closeSession(); } catch (Exception e) { @@ -262,15 +261,16 @@ public class GroupMgmtTest extends OlatJerseyTestCase { @Test - public void testGetGroupsAdmin() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - String request = "/groups"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetGroupsAdmin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("groups").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + List<GroupVO> groups = parseGroupArray(body); assertNotNull(groups); assertTrue(groups.size() >= 4);//g1, g2, g3 and g4 + from olat @@ -287,15 +287,16 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetGroups() throws IOException { - HttpClient c = loginWithCookie("rest-four", "A6B7C8"); - - String request = "/groups"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetGroups() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-four", "A6B7C8")); + + URI request = UriBuilder.fromUri(getContextURI()).path("groups").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + List<GroupVO> groups = parseGroupArray(body); assertNotNull(groups); assertTrue(groups.size() >= 2);//g1, g2, g3 and g4 + from olat @@ -312,30 +313,32 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetGroupAdmin() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - String request = "/groups/" + g1.getKey(); - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetGroupAdmin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("groups").path(g1.getKey().toString()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + GroupVO vo = parse(body, GroupVO.class); assertNotNull(vo); assertEquals(vo.getKey(), g1.getKey()); } @Test - public void testGetGroupInfos() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - String request = "/groups/" + g1.getKey() + "/infos"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetGroupInfos() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/infos").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + GroupInfoVO vo = parse(body, GroupInfoVO.class); assertNotNull(vo); assertEquals(Boolean.TRUE, vo.getHasWiki()); @@ -345,15 +348,16 @@ public class GroupMgmtTest extends OlatJerseyTestCase { //the web service generate the forum key @Test - public void testGetGroupInfos2() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - String request = "/groups/" + g2.getKey() + "/infos"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetGroupInfos2() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g2.getKey() + "/infos").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + GroupInfoVO vo = parse(body, GroupInfoVO.class); assertNotNull(vo); assertEquals(Boolean.FALSE, vo.getHasWiki()); @@ -363,15 +367,16 @@ public class GroupMgmtTest extends OlatJerseyTestCase { @Test - public void testGetThreads() throws IOException { - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); - - String request = "/groups/" + g1.getKey() + "/forum/threads"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetThreads() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/forum/threads").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + List<MessageVO> messages = parseMessageArray(body); assertNotNull(messages); @@ -379,15 +384,16 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetMessages() throws IOException { - HttpClient c = loginWithCookie("rest-one", "A6B7C8"); - - String request = "/groups/" + g1.getKey() + "/forum/posts/" + m1.getKey(); - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetMessages() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-one", "A6B7C8")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/forum/posts/" + m1.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + List<MessageVO> messages = parseMessageArray(body); assertNotNull(messages); @@ -397,8 +403,9 @@ public class GroupMgmtTest extends OlatJerseyTestCase { @Test - public void testUpdateCourseGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testUpdateCourseGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); GroupVO vo = new GroupVO(); vo.setKey(g1.getKey()); @@ -408,13 +415,12 @@ public class GroupMgmtTest extends OlatJerseyTestCase { vo.setMaxParticipants(g1.getMaxParticipants()); vo.setType(g1.getType()); - String stringuifiedAuth = stringuified(vo); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - String request = "/groups/" + g1.getKey(); - PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true); - method.setRequestEntity(entity); - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey()).build(); + HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); BusinessGroupManager bgm = BusinessGroupManagerImpl.getInstance(); BusinessGroup bg = bgm.loadBusinessGroup(g1.getKey(), false); @@ -425,13 +431,14 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testDeleteCourseGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testDeleteCourseGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); - String request = "/groups/" + g1.getKey(); - DeleteMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); BusinessGroupManager bgm = BusinessGroupManagerImpl.getInstance(); BusinessGroup bg = bgm.loadBusinessGroup(g1.getKey(), false); @@ -439,14 +446,15 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetParticipantsAdmin() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - String request = "/groups/" + g1.getKey() + "/participants"; - HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + public void testGetParticipantsAdmin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/participants").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<UserVO> participants = parseUserArray(body); assertNotNull(participants); assertEquals(participants.size(), 2); @@ -465,25 +473,27 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetParticipants() throws HttpException, IOException { - HttpClient c = loginWithCookie("rest-four", "A6B7C8"); + public void testGetParticipants() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-four", "A6B7C8")); - String request = "/groups/" + g1.getKey() + "/participants"; - HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/participants").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); //g1 not authorized - assertEquals(code, 401); + assertEquals(401, response.getStatusLine().getStatusCode()); } @Test - public void testGetOwnersAdmin() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String request = "/groups/" + g1.getKey() + "/owners"; - HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + public void testGetOwnersAdmin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/owners").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<UserVO> owners = parseUserArray(body); assertNotNull(owners); assertEquals(owners.size(), 2); @@ -502,24 +512,26 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetOwners() throws HttpException, IOException { - HttpClient c = loginWithCookie("rest-four", "A6B7C8"); - String request = "/groups/" + g1.getKey() + "/owners"; - HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); + public void testGetOwners() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-four", "A6B7C8")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/owners").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); //not authorized - assertEquals(code, 401); + assertEquals(401, response.getStatusLine().getStatusCode()); } @Test - public void testAddParticipant() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey(); - HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - method.releaseConnection(); + public void testAddParticipant() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/participants/" + part3.getKey()).build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + - assertTrue(code == 200 || code == 201); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); BaseSecurity secm = BaseSecurityManager.getInstance(); List<Identity> participants = secm.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup()); @@ -534,14 +546,15 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testRemoveParticipant() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey(); - HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - method.releaseConnection(); + public void testRemoveParticipant() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/participants/" + part2.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + - assertTrue(code == 200); + assertEquals(200, response.getStatusLine().getStatusCode()); BaseSecurity secm = BaseSecurityManager.getInstance(); List<Identity> participants = secm.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup()); @@ -556,14 +569,15 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testAddTutor() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String request = "/groups/" + g1.getKey() + "/owners/" + owner3.getKey(); - HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - method.releaseConnection(); + public void testAddTutor() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/owners/" + owner3.getKey()).build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); - assertTrue(code == 200 || code == 201); + + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); BaseSecurity secm = BaseSecurityManager.getInstance(); List<Identity> owners = secm.getIdentitiesOfSecurityGroup(g1.getOwnerGroup()); @@ -578,14 +592,15 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } @Test - public void testRemoveTutor() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey(); - HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - method.releaseConnection(); + public void testRemoveTutor() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("/groups/" + g1.getKey() + "/owners/" + owner2.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + - assertTrue(code == 200); + assertEquals(200, response.getStatusLine().getStatusCode()); BaseSecurity secm = BaseSecurityManager.getInstance(); List<Identity> owners = secm.getIdentitiesOfSecurityGroup(g1.getOwnerGroup()); @@ -599,7 +614,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { assertFalse(found); } - protected List<UserVO> parseUserArray(String body) { + protected List<UserVO> parseUserArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<UserVO>>(){/* */}); @@ -609,7 +624,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } } - protected List<GroupVO> parseGroupArray(String body) { + protected List<GroupVO> parseGroupArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<GroupVO>>(){/* */}); @@ -619,7 +634,7 @@ public class GroupMgmtTest extends OlatJerseyTestCase { } } - protected List<MessageVO> parseMessageArray(String body) { + protected List<MessageVO> parseMessageArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<MessageVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/I18nTest.java b/src/test/java/org/olat/restapi/I18nTest.java index 66c00a5906a26ad73fb1e062ea59f3ae8909e92c..8b368f72013caad572c400b03bfe03f34f884cac 100644 --- a/src/test/java/org/olat/restapi/I18nTest.java +++ b/src/test/java/org/olat/restapi/I18nTest.java @@ -30,12 +30,14 @@ import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.util.EntityUtils; import org.junit.Test; import org.olat.test.OlatJerseyTestCase; @@ -54,12 +56,14 @@ public class I18nTest extends OlatJerseyTestCase { } @Test - public void testExecuteService() throws HttpException, IOException { + public void testExecuteService() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + URI uri = UriBuilder.fromUri(getContextURI()).path("i18n").path("org.olat.core").path("ok").build(); - GetMethod method = createGet(uri, MediaType.TEXT_PLAIN, false); - int code = getHttpClient().executeMethod(method); - assertEquals(200, code); - String response = method.getResponseBodyAsString(); - assertEquals("OK", response); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, false); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + String out = EntityUtils.toString(response.getEntity()); + assertEquals("OK", out); } } diff --git a/src/test/java/org/olat/restapi/NotificationsTest.java b/src/test/java/org/olat/restapi/NotificationsTest.java index 9c748b97c27e01e72bd9354071d1420a05bfcdc4..704674455f5897c13bde3c31eaa27dcb72a63864 100644 --- a/src/test/java/org/olat/restapi/NotificationsTest.java +++ b/src/test/java/org/olat/restapi/NotificationsTest.java @@ -44,9 +44,6 @@ import java.util.UUID; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.GetMethod; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.codehaus.jackson.map.ObjectMapper; @@ -125,16 +122,17 @@ public class NotificationsTest extends OlatJerseyTestCase { @Test - public void testGetNotifications() throws HttpException, IOException { - HttpClient c = loginWithCookie("rest-notifications-test-1", "A6B7C8"); - - String request = "/notifications"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + public void testGetNotifications() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-notifications-test-1", "A6B7C8")); + + URI request = UriBuilder.fromUri(getContextURI()).path("notifications").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<SubscriptionInfoVO> infos = parseUserArray(body); - method.releaseConnection(); + assertNotNull(infos); assertFalse(infos.isEmpty()); @@ -148,16 +146,17 @@ public class NotificationsTest extends OlatJerseyTestCase { } @Test - public void testGetUserNotifications() throws HttpException, IOException { - HttpClient c = loginWithCookie("rest-notifications-test-1", "A6B7C8"); + public void testGetUserNotifications() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-notifications-test-1", "A6B7C8")); UriBuilder request = UriBuilder.fromUri(getContextURI()).path("notifications").queryParam("type", "User"); - GetMethod method = createGet(request.build(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(request.build(), MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<SubscriptionInfoVO> infos = parseUserArray(body); - method.releaseConnection(); + assertNotNull(infos); assertFalse(infos.isEmpty()); @@ -171,7 +170,7 @@ public class NotificationsTest extends OlatJerseyTestCase { } @Test - public void testGetUserForumNotifications() throws HttpException, URISyntaxException, IOException { + public void testGetUserForumNotifications() throws URISyntaxException, IOException { RestConnection conn = new RestConnection(); assertTrue(conn.login(userAndForumSubscriberId.getName(), "A6B7C8")); @@ -190,16 +189,17 @@ public class NotificationsTest extends OlatJerseyTestCase { } @Test - public void testGetUserForumNotificationsByType() throws HttpException, IOException { - HttpClient c = loginWithCookie(userAndForumSubscriberId.getName(), "A6B7C8"); + public void testGetUserForumNotificationsByType() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(userAndForumSubscriberId.getName(), "A6B7C8")); UriBuilder request = UriBuilder.fromUri(getContextURI()).path("notifications").queryParam("type", "Forum"); - GetMethod method = createGet(request.build(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(request.build(), MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<SubscriptionInfoVO> infos = parseUserArray(body); - method.releaseConnection(); + assertNotNull(infos); assertTrue(1 <= infos.size()); @@ -213,21 +213,22 @@ public class NotificationsTest extends OlatJerseyTestCase { } @Test - public void testGetNoNotifications() throws HttpException, IOException { - HttpClient c = loginWithCookie("rest-notifications-test-3", "A6B7C8"); - - String request = "/notifications"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + public void testGetNoNotifications() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("rest-notifications-test-3", "A6B7C8")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/notifications").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<SubscriptionInfoVO> infos = parseUserArray(body); - method.releaseConnection(); + assertNotNull(infos); assertTrue(infos.isEmpty()); } - protected List<SubscriptionInfoVO> parseUserArray(HttpResponse response) throws IOException { + protected List<SubscriptionInfoVO> parseUserArray(HttpResponse response) throws IOException, URISyntaxException { InputStream body = response.getEntity().getContent(); return parseUserArray(body); } diff --git a/src/test/java/org/olat/restapi/RepositoryEntriesTest.java b/src/test/java/org/olat/restapi/RepositoryEntriesTest.java index f88f1aa4fd5fb0802359732f53f1e6c40efa2d93..a378f1664ab84fcb7c85b626af70113a7baa8b8e 100644 --- a/src/test/java/org/olat/restapi/RepositoryEntriesTest.java +++ b/src/test/java/org/olat/restapi/RepositoryEntriesTest.java @@ -41,14 +41,13 @@ import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.multipart.FilePart; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.commons.httpclient.methods.multipart.StringPart; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; @@ -56,8 +55,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.olat.core.commons.persistence.DBFactory; -import org.olat.core.id.OLATResourceable; -import org.olat.course.CourseModule; import org.olat.repository.RepositoryEntry; import org.olat.repository.RepositoryManager; import org.olat.resource.OLATResource; @@ -78,38 +75,40 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { DBFactory.getInstance().intermediateCommit(); } - @After @Override + @After public void tearDown() throws Exception { - super.tearDown(); DBFactory.getInstance().commitAndCloseSession(); } @Test - public void testGetEntries() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetEntries() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); - GetMethod method = createGet("repo/entries", MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); List<RepositoryEntryVO> entryVoes = parseRepoArray(body); assertNotNull(entryVoes); } @Test - public void testGetEntriesWithPaging() throws HttpException, IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetEntriesWithPaging() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); URI uri = UriBuilder.fromUri(getContextURI()).path("repo").path("entries") .queryParam("start", "0").queryParam("limit", "25").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(200, code); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); RepositoryEntryVOes entryVoes = parse(body, RepositoryEntryVOes.class); - method.releaseConnection(); + assertNotNull(entryVoes); assertNotNull(entryVoes.getRepositoryEntries()); @@ -118,43 +117,47 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { } @Test - public void testGetEntry() throws HttpException, IOException { + public void testGetEntry() throws IOException, URISyntaxException { RepositoryEntry re = createRepository("Test GET repo entry"); - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries/" + re.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); - GetMethod method = createGet("repo/entries/" + re.getKey(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(200, code); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); RepositoryEntryVO entryVo = parse(body, RepositoryEntryVO.class); assertNotNull(entryVo); } @Test - public void testImportCp() throws HttpException, IOException, URISyntaxException { + public void testImportCp() throws IOException, URISyntaxException { URL cpUrl = RepositoryEntriesTest.class.getResource("cp-demo.zip"); assertNotNull(cpUrl); File cp = new File(cpUrl.toURI()); - HttpClient c = loginWithCookie("administrator", "openolat"); - PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", cp), - new StringPart("filename","cp-demo.zip"), - new StringPart("resourcename","CP demo"), - new StringPart("displayname","CP demo") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(cp)); + entity.addPart("filename", new StringBody("cp-demo.zip")); + entity.addPart("resourcename", new StringBody("CP demo")); + entity.addPart("displayname", new StringBody("CP demo")); + method.setEntity(entity); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + + InputStream body = response.getEntity().getContent(); + RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); @@ -167,28 +170,30 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { } @Test - public void testImportTest() throws HttpException, IOException, URISyntaxException { + public void testImportTest() throws IOException, URISyntaxException { Logger log = Logger.getLogger(getClass().getName()); URL cpUrl = RepositoryEntriesTest.class.getResource("qti-demo.zip"); assertNotNull(cpUrl); File cp = new File(cpUrl.toURI()); - HttpClient c = loginWithCookie("administrator", "openolat"); - PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", cp), - new StringPart("filename","qti-demo.zip"), - new StringPart("resourcename","QTI demo"), - new StringPart("displayname","QTI demo") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(cp)); + entity.addPart("filename", new StringBody("qti-demo.zip")); + entity.addPart("resourcename", new StringBody("QTI demo")); + entity.addPart("displayname", new StringBody("QTI demo")); + method.setEntity(entity); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + + InputStream body = response.getEntity().getContent(); + RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); @@ -202,28 +207,30 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { } @Test - public void testImportQuestionnaire() throws HttpException, IOException, URISyntaxException { + public void testImportQuestionnaire() throws IOException, URISyntaxException { Logger log = Logger.getLogger(getClass().getName()); URL cpUrl = RepositoryEntriesTest.class.getResource("questionnaire-demo.zip"); assertNotNull(cpUrl); File cp = new File(cpUrl.toURI()); - HttpClient c = loginWithCookie("administrator", "openolat"); - PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", cp), - new StringPart("filename","questionnaire-demo.zip"), - new StringPart("resourcename","Questionnaire demo"), - new StringPart("displayname","Questionnaire demo") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(cp)); + entity.addPart("filename", new StringBody("questionnaire-demo.zip")); + entity.addPart("resourcename", new StringBody("Questionnaire demo")); + entity.addPart("displayname", new StringBody("Questionnaire demo")); + method.setEntity(entity); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + + InputStream body = response.getEntity().getContent(); + RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); @@ -237,28 +244,29 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { } @Test - public void testImportWiki() throws HttpException, IOException, URISyntaxException { + public void testImportWiki() throws IOException, URISyntaxException { Logger log = Logger.getLogger(getClass().getName()); URL cpUrl = RepositoryEntriesTest.class.getResource("wiki-demo.zip"); assertNotNull(cpUrl); File cp = new File(cpUrl.toURI()); - HttpClient c = loginWithCookie("administrator", "openolat"); - PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", cp), - new StringPart("filename","wiki-demo.zip"), - new StringPart("resourcename","Wiki demo"), - new StringPart("displayname","Wiki demo") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(cp)); + entity.addPart("filename", new StringBody("wiki-demo.zip")); + entity.addPart("resourcename", new StringBody("Wiki demo")); + entity.addPart("displayname", new StringBody("Wiki demo")); + method.setEntity(entity); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + + InputStream body = response.getEntity().getContent(); + RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); @@ -272,28 +280,30 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { } @Test - public void testImportBlog() throws HttpException, IOException, URISyntaxException { + public void testImportBlog() throws IOException, URISyntaxException { Logger log = Logger.getLogger(getClass().getName()); URL cpUrl = RepositoryEntriesTest.class.getResource("blog-demo.zip"); assertNotNull(cpUrl); File cp = new File(cpUrl.toURI()); - HttpClient c = loginWithCookie("administrator", "openolat"); - PutMethod method = createPut("repo/entries", MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", cp), - new StringPart("filename","blog-demo.zip"), - new StringPart("resourcename","Blog demo"), - new StringPart("displayname","Blog demo") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("repo/entries").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("file", new FileBody(cp)); + entity.addPart("filename", new StringBody("blog-demo.zip")); + entity.addPart("resourcename", new StringBody("Blog demo")); + entity.addPart("displayname", new StringBody("Blog demo")); + method.setEntity(entity); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + + InputStream body = response.getEntity().getContent(); + RepositoryEntryVO vo = parse(body, RepositoryEntryVO.class); assertNotNull(vo); @@ -306,7 +316,7 @@ public class RepositoryEntriesTest extends OlatJerseyTestCase { log.info(re.getOlatResource().getResourceableTypeName()); } - protected List<RepositoryEntryVO> parseRepoArray(String body) { + protected List<RepositoryEntryVO> parseRepoArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<RepositoryEntryVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/RestApiLoginFilterTest.java b/src/test/java/org/olat/restapi/RestApiLoginFilterTest.java index 66c392a1e0b2e70cf5b52c1fc6453a624aef40b7..8867854683e841b268573250c93f3a43e9d37b19 100644 --- a/src/test/java/org/olat/restapi/RestApiLoginFilterTest.java +++ b/src/test/java/org/olat/restapi/RestApiLoginFilterTest.java @@ -26,19 +26,22 @@ package org.olat.restapi; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.Cookie; -import org.apache.commons.httpclient.Credentials; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.UsernamePasswordCredentials; -import org.apache.commons.httpclient.auth.AuthScope; -import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.cookie.Cookie; import org.junit.Test; import org.olat.core.util.StringHelper; import org.olat.restapi.security.RestSecurityHelper; @@ -66,11 +69,12 @@ public class RestApiLoginFilterTest extends OlatJerseyTestCase { * @throws IOException */ @Test - public void testCookieAuthentication() throws HttpException, IOException { - HttpClient c = getAuthenticatedCookieBasedClient("administrator", "openolat"); - Cookie[] cookies = c.getState().getCookies(); + public void testCookieAuthentication() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + List<Cookie> cookies = conn.getCookieStore().getCookies(); assertNotNull(cookies); - assertTrue(cookies.length > 0); + assertFalse(cookies.isEmpty()); } /** @@ -79,8 +83,11 @@ public class RestApiLoginFilterTest extends OlatJerseyTestCase { * @throws IOException */ @Test - public void testTokenAuthentication() throws HttpException, IOException { - String securityToken = getAuthenticatedTokenBasedClient("administrator", "openolat"); + public void testTokenAuthentication() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + String securityToken = conn.getSecurityToken(); assertTrue(StringHelper.containsNonWhitespace(securityToken)); } @@ -91,70 +98,82 @@ public class RestApiLoginFilterTest extends OlatJerseyTestCase { * @throws IOException */ @Test - public void testFollowTokenBasedDiscussion() throws HttpException, IOException { - String securityToken = getAuthenticatedTokenBasedClient("administrator", "openolat"); + public void testFollowTokenBasedDiscussion() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + String securityToken = conn.getSecurityToken(); assertTrue(StringHelper.containsNonWhitespace(securityToken)); + conn.shutdown(); //path is protected - GetMethod method1 = createGet("/users/version", MediaType.TEXT_PLAIN, false); - method1.setRequestHeader(RestSecurityHelper.SEC_TOKEN, securityToken); - int code1 = getHttpClient().executeMethod(method1); - method1.releaseConnection(); - securityToken = getToken(method1); - assertEquals(code1, 200); + RestConnection c1 = new RestConnection(); + URI uri1 = UriBuilder.fromUri(getContextURI()).path("/users/version").build(); + HttpGet method1 = c1.createGet(uri1, MediaType.TEXT_PLAIN, false); + method1.setHeader(RestSecurityHelper.SEC_TOKEN, securityToken); + HttpResponse r1 = c1.execute(method1); + securityToken = c1.getSecurityToken(r1); + assertEquals(200, r1.getStatusLine().getStatusCode()); assertTrue(StringHelper.containsNonWhitespace(securityToken)); + c1.shutdown(); //path is protected - GetMethod method2 = createGet("/repo/entries", MediaType.TEXT_HTML, false); - method2.setRequestHeader(RestSecurityHelper.SEC_TOKEN, securityToken); - int code2 = getHttpClient().executeMethod(method2); - method2.releaseConnection(); - securityToken = getToken(method2); - assertEquals(code2, 200); + RestConnection c2 = new RestConnection(); + URI uri2 = UriBuilder.fromUri(getContextURI()).path("/repo/entries").build(); + HttpGet method2 = c2.createGet(uri2, MediaType.TEXT_HTML, false); + method2.setHeader(RestSecurityHelper.SEC_TOKEN, securityToken); + HttpResponse r2 = c2.execute(method2); + securityToken = c2.getSecurityToken(r2); + assertEquals(200, r2.getStatusLine().getStatusCode()); assertTrue(StringHelper.containsNonWhitespace(securityToken)); + c2.shutdown(); //path is not protected - GetMethod method3 = createGet("/api/copyright", MediaType.TEXT_PLAIN, false); - method3.setRequestHeader(RestSecurityHelper.SEC_TOKEN, securityToken); - int code3 = getHttpClient().executeMethod(method3); - method3.releaseConnection(); - securityToken = getToken(method3); - assertEquals(code3, 200); + RestConnection c3 = new RestConnection(); + URI uri3 = UriBuilder.fromUri(getContextURI()).path("/api/copyright").build(); + HttpGet method3 = c3.createGet(uri3, MediaType.TEXT_PLAIN, false); + method3.setHeader(RestSecurityHelper.SEC_TOKEN, securityToken); + HttpResponse r3 = c3.execute(method3); + securityToken = c3.getSecurityToken(r3); + assertEquals(200, r3.getStatusLine().getStatusCode()); assertTrue(StringHelper.containsNonWhitespace(securityToken)); + c3.shutdown(); //path is protected - GetMethod method4 = createGet("/repo/entries", MediaType.TEXT_HTML, false); - method4.setRequestHeader(RestSecurityHelper.SEC_TOKEN, securityToken); - int code4 = getHttpClient().executeMethod(method4); - method4.releaseConnection(); - securityToken = getToken(method4); - assertEquals(code4, 200); + RestConnection c4 = new RestConnection(); + URI uri4 = UriBuilder.fromUri(getContextURI()).path("/repo/entries").build(); + HttpGet method4 = c4.createGet(uri4, MediaType.TEXT_HTML, false); + method4.setHeader(RestSecurityHelper.SEC_TOKEN, securityToken); + HttpResponse r4 = c4.execute(method4); + securityToken = c4.getSecurityToken(r4); + assertEquals(200, r4.getStatusLine().getStatusCode()); assertTrue(StringHelper.containsNonWhitespace(securityToken)); + c4.shutdown(); } @Test - public void testBasicAuthentication() throws HttpException, IOException { + public void testBasicAuthentication() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); //path is protected - GetMethod method1 = createGet("/users/version", MediaType.TEXT_PLAIN, false); - method1.setRequestHeader("Authorization", "Basic " + Base64Encoder.encode("administrator:openolat")); - int code1 = getHttpClient().executeMethod(method1); - method1.releaseConnection(); - assertEquals(code1, 200); - String securityToken = getToken(method1); + URI uri = UriBuilder.fromUri(getContextURI()).path("/users/version").build(); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, false); + method.setHeader("Authorization", "Basic " + Base64Encoder.encode("administrator:openolat")); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + String securityToken = conn.getSecurityToken(response); assertTrue(StringHelper.containsNonWhitespace(securityToken)); } @Test - public void testWebStandardAuthentication() throws HttpException, IOException { - HttpClient c = getHttpClient(); - Credentials creds = new UsernamePasswordCredentials("administrator", "openolat"); - c.getState().setCredentials(AuthScope.ANY, creds); - - GetMethod method = createGet("/users/version", MediaType.TEXT_PLAIN, false); - int code = c.executeMethod(method); - method.releaseConnection(); - assertEquals(code, 200); - String securityToken = getToken(method); + public void testWebStandardAuthentication() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + conn.setCredentials("administrator", "openolat"); + + URI uri = UriBuilder.fromUri(getContextURI()).path("/users/version").build(); + HttpGet method = conn.createGet(uri, MediaType.TEXT_PLAIN, false); + HttpResponse response = conn.execute(method); + + assertEquals(200, response.getStatusLine().getStatusCode()); + String securityToken = conn.getSecurityToken(response); assertTrue(StringHelper.containsNonWhitespace(securityToken)); } } diff --git a/src/test/java/org/olat/restapi/RestConnection.java b/src/test/java/org/olat/restapi/RestConnection.java index b925b6bd2f325013e3c85e8afdebb30a1dc91551..6fb7f1028ce3618edcb25b5e6c3a0f92ad2c4640 100644 --- a/src/test/java/org/olat/restapi/RestConnection.java +++ b/src/test/java/org/olat/restapi/RestConnection.java @@ -19,6 +19,7 @@ */ package org.olat.restapi; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; @@ -31,7 +32,7 @@ import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.cookie.CookiePolicy; +import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpMessage; import org.apache.http.HttpResponse; @@ -46,8 +47,13 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.params.HttpClientParams; import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.JsonFactory; @@ -55,6 +61,7 @@ import org.codehaus.jackson.map.ObjectMapper; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.core.util.StringHelper; +import org.olat.restapi.security.RestSecurityHelper; /** * @@ -79,6 +86,8 @@ public class RestConnection { private final DefaultHttpClient httpclient; private static final JsonFactory jsonFactory = new JsonFactory(); + private String securityToken; + public RestConnection() { httpclient = new DefaultHttpClient(); HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.RFC_2109); @@ -91,25 +100,48 @@ public class RestConnection { return httpclient.getCookieStore(); } + public String getSecurityToken() { + return securityToken; + } + + public String getSecurityToken(HttpResponse response) { + if(response == null) return null; + + Header header = response.getFirstHeader(RestSecurityHelper.SEC_TOKEN); + return header == null ? null : header.getValue(); + } + public void shutdown() { httpclient.getConnectionManager().shutdown(); } + public void setCredentials(String username, String password) { + httpclient.getCredentialsProvider().setCredentials( + new AuthScope("localhost", PORT), + new UsernamePasswordCredentials(username, password)); + } + public boolean login(String username, String password) throws IOException, URISyntaxException { httpclient.getCredentialsProvider().setCredentials( - new AuthScope("localhost", 9998), + new AuthScope("localhost", PORT), new UsernamePasswordCredentials(username, password)); URI uri = getContextURI().path("auth").path(username).queryParam("password", password).build(); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpclient.execute(httpget); + + Header header = response.getFirstHeader(RestSecurityHelper.SEC_TOKEN); + if(header != null) { + securityToken = header.getValue(); + } + HttpEntity entity = response.getEntity(); int code = response.getStatusLine().getStatusCode(); EntityUtils.consume(entity); return code == 200; } - public <T> T get(URI uri, Class<T> cl) throws IOException { + public <T> T get(URI uri, Class<T> cl) throws IOException, URISyntaxException { HttpGet get = createGet(uri, MediaType.APPLICATION_JSON, true); HttpResponse response = execute(get); if(200 == response.getStatusLine().getStatusCode()) { @@ -147,6 +179,16 @@ public class RestConnection { put.setEntity(myEntity); } + public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file) + throws UnsupportedEncodingException { + + MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); + entity.addPart("filename", new StringBody(filename)); + FileBody fileBody = new FileBody(file, "application/octet-stream"); + entity.addPart("file", fileBody); + post.setEntity(entity); + } + public HttpPut createPut(URI uri, String accept, boolean cookie) { HttpPut put = new HttpPut(uri); decorateHttpMessage(put,accept, "en", cookie); @@ -164,7 +206,7 @@ public class RestConnection { decorateHttpMessage(get,accept, "en", cookie); return get; } - + public HttpPost createPost(URI uri, String accept, boolean cookie) { HttpPost get = new HttpPost(uri); decorateHttpMessage(get,accept, "en", cookie); @@ -190,7 +232,7 @@ public class RestConnection { } public HttpResponse execute(HttpUriRequest request) - throws IOException { + throws IOException, URISyntaxException { HttpResponse response = httpclient.execute(request); return response; } diff --git a/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java b/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java index 450ae668aa48a188b2fc5a029e7b31b6efd48630..da64dfcd8058989aeb00c8737388f6a771a34482 100644 --- a/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java +++ b/src/test/java/org/olat/restapi/UserAuthenticationMgmtTest.java @@ -26,19 +26,25 @@ package org.olat.restapi; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; import java.util.List; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Test; @@ -62,21 +68,23 @@ import org.olat.test.OlatJerseyTestCase; public class UserAuthenticationMgmtTest extends OlatJerseyTestCase { @Test - public void testGetAuthentications() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testGetAuthentications() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); - GetMethod method = createGet("/users/administrator/auth", MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); + URI request = UriBuilder.fromUri(getContextURI()).path("/users/administrator/auth").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<AuthenticationVO> vos = parseAuthenticationArray(body); assertNotNull(vos); assertFalse(vos.isEmpty()); - method.releaseConnection(); + } @Test - public void testCreateAuthentications() throws IOException { + public void testCreateAuthentications() throws IOException, URISyntaxException { BaseSecurity baseSecurity = BaseSecurityManager.getInstance(); Identity adminIdent = baseSecurity.findIdentityByName("administrator"); try { @@ -89,7 +97,8 @@ public class UserAuthenticationMgmtTest extends OlatJerseyTestCase { } DBFactory.getInstance().commitAndCloseSession(); - HttpClient c = loginWithCookie("administrator", "openolat"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); AuthenticationVO vo = new AuthenticationVO(); vo.setAuthUsername("administrator"); @@ -97,17 +106,16 @@ public class UserAuthenticationMgmtTest extends OlatJerseyTestCase { vo.setProvider("REST-API"); vo.setCredential("credentials"); - String stringuifiedAuth = stringuified(vo); - PutMethod method = createPut("/users/administrator/auth", MediaType.APPLICATION_JSON, true); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - method.setRequestEntity(entity); + URI request = UriBuilder.fromUri(getContextURI()).path("/users/administrator/auth").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - String body = method.getResponseBodyAsString(); + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + InputStream body = response.getEntity().getContent(); AuthenticationVO savedAuth = parse(body, AuthenticationVO.class); Authentication refAuth = baseSecurity.findAuthentication(adminIdent, "REST-API"); - method.releaseConnection(); + assertNotNull(refAuth); assertNotNull(refAuth.getKey()); @@ -123,8 +131,9 @@ public class UserAuthenticationMgmtTest extends OlatJerseyTestCase { } @Test - public void testDeleteAuthentications() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testDeleteAuthentications() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //create an authentication token BaseSecurity baseSecurity = BaseSecurityManager.getInstance(); @@ -134,17 +143,17 @@ public class UserAuthenticationMgmtTest extends OlatJerseyTestCase { DBFactory.getInstance().intermediateCommit(); //delete an authentication token - String request = "/users/administrator/auth/" + authentication.getKey().toString(); - DeleteMethod method = createDelete(request, MediaType.APPLICATION_XML, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - method.releaseConnection(); + URI request = UriBuilder.fromUri(getContextURI()).path("/users/administrator/auth/" + authentication.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_XML, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + Authentication refAuth = baseSecurity.findAuthentication(adminIdent, "REST-A-2"); assertNull(refAuth); } - private List<AuthenticationVO> parseAuthenticationArray(String body) { + private List<AuthenticationVO> parseAuthenticationArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<AuthenticationVO>>(){/* */}); diff --git a/src/test/java/org/olat/restapi/UserMgmtTest.java b/src/test/java/org/olat/restapi/UserMgmtTest.java index 0e7ca098d2bd6c6cef08c6ebef7874b832a557fe..427e73db7c35ff8dd2ff0a9c13be24e4d29dcfc7 100644 --- a/src/test/java/org/olat/restapi/UserMgmtTest.java +++ b/src/test/java/org/olat/restapi/UserMgmtTest.java @@ -48,21 +48,14 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.httpclient.methods.multipart.FilePart; -import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; -import org.apache.commons.httpclient.methods.multipart.Part; -import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.After; @@ -277,9 +270,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @After - @Override public void tearDown() throws Exception { - super.tearDown(); try { DBFactory.getInstance().closeSession(); } catch (Exception e) { @@ -290,15 +281,17 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetUsers() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + public void testGetUsers() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("users").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<UserVO> vos = parseUserArray(body); - method.releaseConnection(); + List<Identity> identities = BaseSecurityManager.getInstance().getIdentitiesByPowerSearch(null, null, true, null, null, null, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT); assertNotNull(vos); @@ -307,19 +300,19 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testFindUsersByLogin() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("login","administrator"), - new NameValuePair("authProvider","OLAT") - }); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + public void testFindUsersByLogin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("users") + .queryParam("login","administrator") + .queryParam("authProvider","OLAT").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<UserVO> vos = parseUserArray(body); - method.releaseConnection(); + String[] authProviders = new String[]{"OLAT"}; List<Identity> identities = BaseSecurityManager.getInstance().getIdentitiesByPowerSearch("administrator", null, true, null, null, authProviders, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT); @@ -336,39 +329,38 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testFindUsersByProperty() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("telMobile","39847592"), - new NameValuePair("gender","Female"), - new NameValuePair("birthDay", "12/12/2009") - }); - method.addRequestHeader("Accept-Language", "en"); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + public void testFindUsersByProperty() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("users") + .queryParam("telMobile","39847592") + .queryParam("gender","Female") + .queryParam("birthDay", "12/12/2009").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Accept-Language", "en"); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<UserVO> vos = parseUserArray(body); - method.releaseConnection(); assertNotNull(vos); assertFalse(vos.isEmpty()); } @Test - public void testFindAdminByAuth() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - GetMethod method = createGet("/users", MediaType.APPLICATION_JSON, true); - method.setQueryString(new NameValuePair[]{ - new NameValuePair("authUsername","administrator"), - new NameValuePair("authProvider","OLAT") - }); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testFindAdminByAuth() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("users") + .queryParam("authUsername","administrator") + .queryParam("authProvider","OLAT").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + List<UserVO> vos = parseUserArray(body); assertNotNull(vos); @@ -378,14 +370,16 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetUser() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetUser() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + UserVO vo = parse(body, UserVO.class); assertNotNull(vo); @@ -396,14 +390,16 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testGetUserNotAdmin() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); - - HttpMethod method = createGet("/users/" + id2.getKey(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); + public void testGetUserNotAdmin() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id2.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); + UserVO vo = parse(body, UserVO.class); assertNotNull(vo); @@ -418,13 +414,15 @@ public class UserMgmtTest extends OlatJerseyTestCase { * @throws IOException */ @Test - public void testGetRawJsonUser() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - - HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String bodyJson = method.getResponseBodyAsString(); + public void testGetRawJsonUser() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + String bodyJson = EntityUtils.toString(response.getEntity()); System.out.println("User"); System.out.println(bodyJson); System.out.println("User"); @@ -435,20 +433,24 @@ public class UserMgmtTest extends OlatJerseyTestCase { * @throws IOException */ @Test - public void testGetRawXmlUser() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); - HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_XML, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - String bodyXml = method.getResponseBodyAsString(); + public void testGetRawXmlUser() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); + + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey()).build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_XML, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + String bodyXml = EntityUtils.toString(response.getEntity()); System.out.println("User"); System.out.println(bodyXml); System.out.println("User"); } @Test - public void testCreateUser() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testCreateUser() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); UserVO vo = new UserVO(); String username = UUID.randomUUID().toString(); @@ -462,16 +464,15 @@ public class UserMgmtTest extends OlatJerseyTestCase { vo.putProperty("gender", "Female");//male or female vo.putProperty("birthDay", "12/12/2009"); - String stringuifiedAuth = stringuified(vo); - PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - method.setRequestEntity(entity); - method.addRequestHeader("Accept-Language", "en"); + URI request = UriBuilder.fromUri(getContextURI()).path("users").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + method.addHeader("Accept-Language", "en"); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + InputStream body = response.getEntity().getContent(); - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); UserVO savedVo = parse(body, UserVO.class); Identity savedIdent = BaseSecurityManager.getInstance().findIdentityByName(username); @@ -489,8 +490,9 @@ public class UserMgmtTest extends OlatJerseyTestCase { * Test machine format for gender and date */ @Test - public void testCreateUser2() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testCreateUser2() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); UserVO vo = new UserVO(); String username = UUID.randomUUID().toString(); @@ -504,16 +506,15 @@ public class UserMgmtTest extends OlatJerseyTestCase { vo.putProperty("gender", "female");//male or female vo.putProperty("birthDay", "20091212"); - String stringuifiedAuth = stringuified(vo); - PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - method.setRequestEntity(entity); - method.addRequestHeader("Accept-Language", "en"); + URI request = UriBuilder.fromUri(getContextURI()).path("users").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + method.addHeader("Accept-Language", "en"); + + HttpResponse response = conn.execute(method); + assertTrue(response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201); + InputStream body = response.getEntity().getContent(); - int code = c.executeMethod(method); - assertTrue(code == 200 || code == 201); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); UserVO savedVo = parse(body, UserVO.class); Identity savedIdent = BaseSecurityManager.getInstance().findIdentityByName(username); @@ -528,8 +529,9 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testCreateUserWithValidationError() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testCreateUserWithValidationError() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); UserVO vo = new UserVO(); vo.setLogin("rest-809"); @@ -538,15 +540,14 @@ public class UserMgmtTest extends OlatJerseyTestCase { vo.setEmail(""); vo.putProperty("gender", "lu"); - String stringuifiedAuth = stringuified(vo); - PutMethod method = createPut("/users", MediaType.APPLICATION_JSON, true); - RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8"); - method.setRequestEntity(entity); + URI request = UriBuilder.fromUri(getContextURI()).path("users").build(); + HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true); + conn.addJsonEntity(method, vo); + + HttpResponse response = conn.execute(method); + assertEquals(406, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); - int code = c.executeMethod(method); - assertTrue(code == 406); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); List<ErrorVO> errors = parseErrorArray(body); assertNotNull(errors); assertFalse(errors.isEmpty()); @@ -561,15 +562,16 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testDeleteUser() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testDeleteUser() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //delete an authentication token - String request = "/users/" + id2.getKey(); - DeleteMethod method = createDelete(request, MediaType.APPLICATION_XML, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - method.releaseConnection(); + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id2.getKey()).build(); + HttpDelete method = conn.createDelete(request, MediaType.APPLICATION_XML, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + Identity deletedIdent = BaseSecurityManager.getInstance().loadIdentityByKey(id2.getKey()); assertNotNull(deletedIdent);//Identity aren't deleted anymore @@ -577,16 +579,17 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserForums() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + public void testUserForums() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("forums") .queryParam("start", 0).queryParam("limit", 20).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); ForumVOes forums = parse(body, ForumVOes.class); assertNotNull(forums); @@ -613,17 +616,18 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserGroupForum() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + public void testUserGroupForum() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("forums") .path("group").path(g1.getKey().toString()) .path("threads").queryParam("start", "0").queryParam("limit", "25").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVOes threads = parse(body, MessageVOes.class); assertNotNull(threads); @@ -632,17 +636,18 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserCourseForum() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + public void testUserCourseForum() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("forums") .path("course").path(demoCourse.getResourceableId().toString()).path(demoForumNode.getIdent()) .path("threads").queryParam("start", "0").queryParam("limit", 25).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); MessageVOes threads = parse(body, MessageVOes.class); assertNotNull(threads); @@ -651,15 +656,16 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserFolders() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + public void testUserFolders() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); FolderVOes folders = parse(body, FolderVOes.class); assertNotNull(folders); @@ -693,16 +699,17 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserGroupFolder() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + public void testUserGroupFolder() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders") .path("group").path(g2.getKey().toString()).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<FileVO> folders = parseFileArray(body); assertNotNull(folders); @@ -714,16 +721,17 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserBCCourseNodeFolder() throws IOException { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + public void testUserBCCourseNodeFolder() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders") .path("course").path(demoCourse.getResourceableId().toString()).path(demoBCCourseNode.getIdent()).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<FileVO> folders = parseFileArray(body); assertNotNull(folders); @@ -736,14 +744,15 @@ public class UserMgmtTest extends OlatJerseyTestCase { @Test public void testUserPersonalFolder() throws Exception { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("folders").path("personal").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<FileVO> files = parseFileArray(body); assertNotNull(files); @@ -753,14 +762,15 @@ public class UserMgmtTest extends OlatJerseyTestCase { @Test public void testOtherUserPersonalFolder() throws Exception { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id2.getKey().toString()).path("folders").path("personal").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<FileVO> files = parseFileArray(body); assertNotNull(files); @@ -770,14 +780,15 @@ public class UserMgmtTest extends OlatJerseyTestCase { @Test public void testOtherUserPersonalFolderOfId3() throws Exception { - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); URI uri = UriBuilder.fromUri(getContextURI()).path("users").path(id3.getKey().toString()).path("folders").path("personal").build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); - InputStream body = method.getResponseBodyAsStream(); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + InputStream body = response.getEntity().getContent(); List<FileVO> files = parseFileArray(body); assertNotNull(files); @@ -789,36 +800,38 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserGroup() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testUserGroup() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //retrieve all groups - String request = "/users/" + id1.getKey() + "/groups"; - GetMethod method = createGet(request, MediaType.APPLICATION_JSON, true); - int code = c.executeMethod(method); - assertEquals(code, 200); + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey() + "/groups").build(); + HttpGet method = conn.createGet(request, MediaType.APPLICATION_JSON, true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); - String body = method.getResponseBodyAsString(); + InputStream body = response.getEntity().getContent(); List<GroupVO> groups = parseGroupArray(body); assertNotNull(groups); assertEquals(2, groups.size());//g1 and g2 as g3 and g4 are right groups which are not returned } @Test - public void testUserGroupWithPaging() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testUserGroupWithPaging() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //retrieve all groups URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups") .queryParam("start", 0).queryParam("limit", 1).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = method.getResponseBodyAsStream(); + InputStream body = response.getEntity().getContent(); GroupVOes groups = parse(body, GroupVOes.class); - method.releaseConnection(); + assertNotNull(groups); assertNotNull(groups.getGroups()); assertEquals(1, groups.getGroups().length); @@ -826,20 +839,21 @@ public class UserMgmtTest extends OlatJerseyTestCase { } @Test - public void testUserGroupInfosWithPaging() throws IOException { - HttpClient c = loginWithCookie("administrator", "openolat"); + public void testUserGroupInfosWithPaging() throws IOException, URISyntaxException { + RestConnection conn = new RestConnection(); + assertTrue(conn.login("administrator", "openolat")); //retrieve all groups URI uri =UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).path("groups").path("infos") .queryParam("start", 0).queryParam("limit", 1).build(); - GetMethod method = createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); - int code = c.executeMethod(method); - assertEquals(code, 200); + HttpGet method = conn.createGet(uri, MediaType.APPLICATION_JSON + ";pagingspec=1.0", true); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); - InputStream body = method.getResponseBodyAsStream(); + InputStream body = response.getEntity().getContent(); GroupInfoVOes groups = parse(body, GroupInfoVOes.class); - method.releaseConnection(); + assertNotNull(groups); assertNotNull(groups.getGroups()); assertEquals(1, groups.getGroups().length); @@ -851,21 +865,19 @@ public class UserMgmtTest extends OlatJerseyTestCase { URL portraitUrl = CoursesElementsTest.class.getResource("portrait.jpg"); assertNotNull(portraitUrl); File portrait = new File(portraitUrl.toURI()); - - HttpClient c = loginWithCookie(id1.getName(), "A6B7C8"); + + RestConnection conn = new RestConnection(); + assertTrue(conn.login(id1.getName(), "A6B7C8")); //upload portrait - String request = "/users/" + id1.getKey() + "/portrait"; - PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true); - method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); - Part[] parts = { - new FilePart("file", portrait), - new StringPart("filename","portrait.jpg") - }; - method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); - int code = c.executeMethod(method); - assertEquals(code, 200); - method.releaseConnection(); + URI request = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey() + "/portrait").build(); + HttpPost method = conn.createPost(request, MediaType.APPLICATION_JSON, true); + method.addHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); + conn.addMultipart(method, "portrait.jpg", portrait); + HttpResponse response = conn.execute(method); + assertEquals(200, response.getStatusLine().getStatusCode()); + EntityUtils.consume(response.getEntity()); + //check if big and small portraits exist DisplayPortraitManager dps = DisplayPortraitManager.getInstance(); @@ -875,17 +887,16 @@ public class UserMgmtTest extends OlatJerseyTestCase { assertTrue(bigPortrait.exists()); //check get portrait - String getRequest = "/users/" + id1.getKey() + "/portrait"; - GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true); - int getCode = c.executeMethod(getMethod); - assertEquals(getCode, 200); - InputStream in = getMethod.getResponseBodyAsStream(); + URI getRequest = UriBuilder.fromUri(getContextURI()).path("/users/" + id1.getKey() + "/portrait").build(); + HttpGet getMethod = conn.createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true); + HttpResponse getResponse = conn.execute(getMethod); + assertEquals(200, getResponse.getStatusLine().getStatusCode()); + InputStream in = getResponse.getEntity().getContent(); int b = 0; int count = 0; while((b = in.read()) > -1) { count++; } - getMethod.releaseConnection(); assertEquals(-1, b);//up to end of file assertTrue(count > 1000);//enough bytes @@ -895,12 +906,11 @@ public class UserMgmtTest extends OlatJerseyTestCase { //check get portrait as Base64 UriBuilder getRequest2 = UriBuilder.fromUri(getContextURI()).path("users").path(id1.getKey().toString()).queryParam("withPortrait", "true"); - GetMethod getMethod2 = createGet(getRequest2.build(), MediaType.APPLICATION_JSON, true); - int getCode2 = c.executeMethod(getMethod2); - assertEquals(getCode2, 200); - InputStream in2 = getMethod2.getResponseBodyAsStream(); + HttpGet getMethod2 = conn.createGet(getRequest2.build(), MediaType.APPLICATION_JSON, true); + HttpResponse getCode2 = conn.execute(getMethod2); + assertEquals(200, getCode2.getStatusLine().getStatusCode()); + InputStream in2 = getCode2.getEntity().getContent(); UserVO userVo = parse(in2, UserVO.class); - getMethod2.releaseConnection(); assertNotNull(userVo); assertNotNull(userVo.getPortrait()); byte[] datas = Base64.decodeBase64(userVo.getPortrait().getBytes()); @@ -918,16 +928,6 @@ public class UserMgmtTest extends OlatJerseyTestCase { } } - protected List<UserVO> parseUserArray(String body) { - try { - ObjectMapper mapper = new ObjectMapper(jsonFactory); - return mapper.readValue(body, new TypeReference<List<UserVO>>(){/* */}); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - protected List<UserVO> parseUserArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); @@ -938,7 +938,7 @@ public class UserMgmtTest extends OlatJerseyTestCase { } } - protected List<GroupVO> parseGroupArray(String body) { + protected List<GroupVO> parseGroupArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<GroupVO>>(){/* */}); diff --git a/src/test/java/org/olat/test/OlatJerseyTestCase.java b/src/test/java/org/olat/test/OlatJerseyTestCase.java index 5257c3321e2411cf3eb5462b2d98f983bb03622a..0afe19bb903e167bfbf786ea03e16fe5a8e180ff 100644 --- a/src/test/java/org/olat/test/OlatJerseyTestCase.java +++ b/src/test/java/org/olat/test/OlatJerseyTestCase.java @@ -26,8 +26,6 @@ package org.olat.test; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; @@ -38,15 +36,8 @@ import javax.servlet.Servlet; import javax.servlet.http.HttpServlet; import javax.ws.rs.core.UriBuilder; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.http.Header; +import org.apache.http.HttpResponse; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; @@ -54,7 +45,6 @@ import org.junit.After; import org.junit.Before; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; -import org.olat.core.util.StringHelper; import org.olat.restapi.RestModule; import org.olat.restapi.security.RestApiLoginFilter; import org.olat.restapi.security.RestSecurityHelper; @@ -138,9 +128,9 @@ public abstract class OlatJerseyTestCase extends OlatTestCase { //always enabled the REST API for testing restModule.setEnabled(true); - log.info("Starting the Grizzly Web Container..."); try { if(!webServerStarted) { + log.info("Starting the Grizzly Web Container..."); webServer.start(); } } catch (IOException ex) { @@ -148,201 +138,6 @@ public abstract class OlatJerseyTestCase extends OlatTestCase { } } - /** - * Tear down the test by invoking {@link TestContainer#stop() } on - * the test container obtained from the test container factory. - * - * @throws Exception - */ - @After - public void tearDown() throws Exception { - log.info("Stopping the Grizzly Web Container..."); - //webServer.stop(); - //webServer.getSelectorThread().stopEndpoint(); - } - - /** - * @return bare bone HttpClient - */ - public HttpClient getHttpClient() { - HttpClient c = new HttpClient(); - c.getHostConfiguration().setHost(HOST, PORT, PROTOCOL); - return c; - } - - /** - * Return an authenticated HttpClient based on session cookie - * @param username - * @param password - * @return - * @throws HttpException - * @throws IOException - */ - public HttpClient getAuthenticatedCookieBasedClient(String username, String password) throws HttpException, IOException { - HttpClient c = getHttpClient(); - loginWithCookie(username, password, c); - return c; - } - - /** - * Return an authenticated HttpClient based on session cookie - * @param username - * @param password - * @return - * @throws HttpException - * @throws IOException - */ - public String getAuthenticatedTokenBasedClient(String username, String password) throws HttpException, IOException { - HttpClient c = getHttpClient(); - return loginWithToken(username, password, c); - } - - /** - * Login the HttpClient based on the session cookie - * @param username - * @param password - * @param c - * @throws HttpException - * @throws IOException - */ - public HttpClient loginWithCookie(String username, String password) throws HttpException, IOException { - HttpClient c = getHttpClient(); - URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build(); - GetMethod method = new GetMethod(uri.toString()); - method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - int response = c.executeMethod(method); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); - assertTrue(response == 200); - assertTrue(body != null && body.length() > "<hello></hello>".length()); - return c; - } - - /** - * Login the HttpClient based on the session cookie - * @param username - * @param password - * @param c - * @throws HttpException - * @throws IOException - */ - public void loginWithCookie(String username, String password, HttpClient c) throws HttpException, IOException { - URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build(); - GetMethod method = new GetMethod(uri.toString()); - method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - int response = c.executeMethod(method); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); - assertTrue(response == 200); - assertTrue(body != null && body.length() > "<hello></hello>".length()); - } - - /** - * Login the HttpClient based on the session cookie - * @param username - * @param password - * @param c - * @throws HttpException - * @throws IOException - */ - public String loginWithToken(String username, String password, HttpClient c) throws HttpException, IOException { - URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build(); - GetMethod method = new GetMethod(uri.toString()); - int response = c.executeMethod(method); - String body = method.getResponseBodyAsString(); - method.releaseConnection(); - assertTrue(response == 200); - assertTrue(body != null && body.length() > "<hello></hello>".length()); - Header securityToken = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN); - assertTrue(securityToken != null && StringHelper.containsNonWhitespace(securityToken.getValue())); - return securityToken == null ? null : securityToken.getValue(); - } - - public String getToken(HttpMethod method) { - Header header = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN); - return header == null ? null : header.getValue(); - } - - public GetMethod createGet(String requestStr, String accept, boolean cookie) { - URI requestURI = UriBuilder.fromUri(getContextURI()).path(requestStr).build(); - return createGet(requestURI, accept, cookie); - } - - /** - * Return a GetMethod - * @param requestURI - * @param accept accepted mime-type - * @param cookie allow cookie or not - * @return - */ - public GetMethod createGet(URI requestURI, String accept, boolean cookie) { - GetMethod method = new GetMethod(requestURI.toString()); - if(cookie) { - method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - } - method.addRequestHeader("Accept", accept); - return method; - } - - - public PutMethod createPut(String requestStr, String accept, boolean cookie) { - URI requestURI = UriBuilder.fromUri(getContextURI()).path(requestStr).build(); - return createPut(requestURI, accept, cookie); - } - - public PutMethod createPut(String requestStr, String accept, String langage, boolean cookie) { - URI requestURI = UriBuilder.fromUri(getContextURI()).path(requestStr).build(); - return createPut(requestURI, accept, langage, cookie); - } - - public PutMethod createPut(URI requestURI, String accept, boolean cookie) { - return createPut(requestURI, accept, "en", cookie); - } - - public PutMethod createPut(URI requestURI, String accept, String langage, boolean cookie) { - PutMethod method = new PutMethod(requestURI.toString()); - if(cookie) { - method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - } - if(StringHelper.containsNonWhitespace(accept)) { - method.addRequestHeader("Accept", accept); - } - method.addRequestHeader("Accept-Language", langage); - return method; - } - - public PostMethod createPost(String requestStr, String accept, boolean cookie) { - URI requestURI = UriBuilder.fromUri(getContextURI()).path(requestStr).build(); - return createPost(requestURI, accept, cookie); - } - - public PostMethod createPost(URI requestURI, String accept, boolean cookie) { - PostMethod method = new PostMethod(requestURI.toString()); - if(cookie) { - method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - } - if(StringHelper.containsNonWhitespace(accept)) { - method.addRequestHeader("Accept", accept); - } - return method; - } - - public DeleteMethod createDelete(String requestStr, String accept, boolean cookie) { - URI requestURI = UriBuilder.fromUri(getContextURI()).path(requestStr).build(); - return createDelete(requestURI, accept, cookie); - } - - public DeleteMethod createDelete(URI requestURI, String accept, boolean cookie) { - DeleteMethod method = new DeleteMethod(requestURI.toString()); - if(cookie) { - method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); - } - if(StringHelper.containsNonWhitespace(accept)) { - method.addRequestHeader("Accept", accept); - } - return method; - } - protected <T> T parse(String body, Class<T> cl) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); @@ -365,19 +160,7 @@ public abstract class OlatJerseyTestCase extends OlatTestCase { } } - protected String stringuified(Object obj) { - try { - ObjectMapper mapper = new ObjectMapper(jsonFactory); - StringWriter w = new StringWriter(); - mapper.writeValue(w, obj); - return w.toString(); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - protected List<ErrorVO> parseErrorArray(String body) { + protected List<ErrorVO> parseErrorArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory); return mapper.readValue(body, new TypeReference<List<ErrorVO>>(){/* */}); @@ -387,16 +170,6 @@ public abstract class OlatJerseyTestCase extends OlatTestCase { } } - protected List<LinkVO> parseLinkArray(String body) { - try { - ObjectMapper mapper = new ObjectMapper(jsonFactory); - return mapper.readValue(body, new TypeReference<List<LinkVO>>(){/* */}); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - protected List<LinkVO> parseLinkArray(InputStream body) { try { ObjectMapper mapper = new ObjectMapper(jsonFactory);