diff --git a/src/main/java/de/thm/arsnova/aop/UserSessionAspect.java b/src/main/java/de/thm/arsnova/aop/UserSessionAspect.java index bfe0dad441bf1bc57c68f54585aafba56e701feb..690fdd241bf238dfcb89f3009e9af7d4976f1c11 100644 --- a/src/main/java/de/thm/arsnova/aop/UserSessionAspect.java +++ b/src/main/java/de/thm/arsnova/aop/UserSessionAspect.java @@ -14,35 +14,17 @@ public class UserSessionAspect { @Autowired private UserSessionService userSessionService; - /** Sets current user and ARSnova session in session scoped UserSessionService - * + /** Sets current user and ARSnova session in session scoped UserSessionService + * * @param jp * @param keyword * @param session */ @AfterReturning( - pointcut="execution(public * de.thm.arsnova.services.SessionService.joinSession(..)) && args(keyword)", - returning="session" - ) + pointcut="execution(public * de.thm.arsnova.services.SessionService.joinSession(..)) && args(keyword)", + returning="session" + ) public final void joinSessionAdvice(final JoinPoint jp, final String keyword, final Session session) { userSessionService.setSession(session); } - - /** Sets current user, ARSnova session and websocket session ID in session scoped UserSessionService - * - * @param jp - * @param keyword - * @param socketId - * @param session - */ - /* FIXME This is not working because of scoping problems - @AfterReturning( - pointcut="execution(public * de.thm.arsnova.services.SessionService.joinSession(..)) && args(keyword, socketId)", - returning="session" - ) - public final void joinSessionAdviceWithWebsocket(final JoinPoint jp, final String keyword, final UUID socketId, final Session session) { - userSessionService.setSession(session); - userSessionService.setSocketId(socketId); - } - */ } diff --git a/src/main/java/de/thm/arsnova/controller/SessionController.java b/src/main/java/de/thm/arsnova/controller/SessionController.java index b8443784bf35398a46b3845e246b7f97b5ae019e..27e5c8e1f38dabdbb88147978284ad532e10451b 100644 --- a/src/main/java/de/thm/arsnova/controller/SessionController.java +++ b/src/main/java/de/thm/arsnova/controller/SessionController.java @@ -61,8 +61,7 @@ public class SessionController extends AbstractController { @RequestMapping(value = "/{sessionkey}", method = RequestMethod.GET) @ResponseBody public final Session joinSession(@PathVariable final String sessionkey) { - Session session = sessionService.joinSession(sessionkey); - return session; + return sessionService.joinSession(sessionkey); } @RequestMapping(value = "/{sessionkey}", method = RequestMethod.DELETE) @@ -78,7 +77,7 @@ public class SessionController extends AbstractController { public final LoggedIn registerAsOnlineUser( @PathVariable final String sessionkey, final HttpServletResponse response - ) { + ) { response.addHeader("X-Deprecated-API", "1"); User user = userService.getCurrentUser(); @@ -95,7 +94,7 @@ public class SessionController extends AbstractController { public final int countActiveUsers( @PathVariable final String sessionkey, final HttpServletResponse response - ) { + ) { response.addHeader("X-Deprecated-API", "1"); return userService.getUsersInSessionCount(sessionkey); @@ -132,7 +131,7 @@ public class SessionController extends AbstractController { public final Session updateSession( @PathVariable final String sessionkey, @RequestBody final Session session - ) { + ) { return sessionService.updateSession(sessionkey, session); } @@ -143,7 +142,7 @@ public class SessionController extends AbstractController { @RequestParam(value = "visitedonly", defaultValue = "false") final boolean visitedOnly, @RequestParam(value = "sortby", defaultValue = "name") final String sortby, final HttpServletResponse response - ) { + ) { User user = userService.getCurrentUser(); List<Session> sessions = null; @@ -183,7 +182,7 @@ public class SessionController extends AbstractController { @PathVariable final String sessionkey, @RequestParam(required = false) final Boolean lock, final HttpServletResponse response - ) { + ) { if (lock != null) { return this.sessionService.setActive(sessionkey, lock); } @@ -196,7 +195,7 @@ public class SessionController extends AbstractController { public final int learningProgress( @PathVariable final String sessionkey, final HttpServletResponse response - ) { + ) { return sessionService.getLearningProgress(sessionkey); } @@ -205,7 +204,7 @@ public class SessionController extends AbstractController { public final int myLearningProgress( @PathVariable final String sessionkey, final HttpServletResponse response - ) { + ) { return sessionService.getMyLearningProgress(sessionkey); } @@ -215,7 +214,7 @@ public class SessionController extends AbstractController { public final String redirectLecturerQuestion( @PathVariable final String sessionKey, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/lecturerquestion/?sessionkey=%s", sessionKey); @@ -226,7 +225,7 @@ public class SessionController extends AbstractController { @PathVariable final String sessionKey, @PathVariable final String arg1, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/lecturerquestion/%s/?sessionkey=%s", arg1, sessionKey); @@ -238,7 +237,7 @@ public class SessionController extends AbstractController { @PathVariable final String arg1, @PathVariable final String arg2, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/lecturerquestion/%s/%s/?sessionkey=%s", arg1, arg2, sessionKey); @@ -251,7 +250,7 @@ public class SessionController extends AbstractController { @PathVariable final String arg2, @PathVariable final String arg3, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/lecturerquestion/%s/%s/%s/?sessionkey=%s", arg1, arg2, arg3, sessionKey); @@ -261,7 +260,7 @@ public class SessionController extends AbstractController { public final String redirectAudienceQuestion( @PathVariable final String sessionKey, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/audiencequestion/?sessionkey=%s", sessionKey); @@ -272,7 +271,7 @@ public class SessionController extends AbstractController { @PathVariable final String sessionKey, @PathVariable final String arg1, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/audiencequestion/%s/?sessionkey=%s", arg1, sessionKey); @@ -284,7 +283,7 @@ public class SessionController extends AbstractController { @PathVariable final String arg1, @PathVariable final String arg2, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/audiencequestion/%s/%s/?sessionkey=%s", arg1, arg2, sessionKey); @@ -297,7 +296,7 @@ public class SessionController extends AbstractController { @PathVariable final String arg2, @PathVariable final String arg3, final HttpServletResponse response - ) { + ) { response.addHeader("X-Forwarded", "1"); return String.format("forward:/audiencequestion/%s/%s/%s/?sessionkey=%s", arg1, arg2, arg3, sessionKey); diff --git a/src/main/java/de/thm/arsnova/dao/CouchDBDao.java b/src/main/java/de/thm/arsnova/dao/CouchDBDao.java index 28ff837d321414e12a645f32e0f3bcfa83b3b640..8b85944aced1d92c302e9f1dc3f89152fbec3c48 100644 --- a/src/main/java/de/thm/arsnova/dao/CouchDBDao.java +++ b/src/main/java/de/thm/arsnova/dao/CouchDBDao.java @@ -63,7 +63,6 @@ import de.thm.arsnova.entities.VisitedSession; import de.thm.arsnova.exceptions.ForbiddenException; import de.thm.arsnova.exceptions.NotFoundException; import de.thm.arsnova.exceptions.UnauthorizedException; -import de.thm.arsnova.services.IFeedbackService; import de.thm.arsnova.services.ISessionService; import de.thm.arsnova.services.IUserService; @@ -72,9 +71,6 @@ public class CouchDBDao implements IDatabaseDao { @Autowired private IUserService userService; - @Autowired - private IFeedbackService feedbackService; - @Autowired private ISessionService sessionService; @@ -134,7 +130,7 @@ public class CouchDBDao implements IDatabaseDao { Session session = (Session) JSONObject.toBean( d.getJSONObject().getJSONObject("value"), Session.class - ); + ); session.setCreator(d.getJSONObject().getJSONArray("key").getString(0)); session.setName(d.getJSONObject().getJSONArray("key").getString(1)); session.set_id(d.getId()); @@ -175,7 +171,7 @@ public class CouchDBDao implements IDatabaseDao { return (Session) JSONObject.toBean( results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"), Session.class - ); + ); } @Override @@ -190,7 +186,7 @@ public class CouchDBDao implements IDatabaseDao { return (Session) JSONObject.toBean( results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"), Session.class - ); + ); } @Override @@ -244,14 +240,14 @@ public class CouchDBDao implements IDatabaseDao { com.fourspaces.couchdb.Session session = new com.fourspaces.couchdb.Session( databaseHost, databasePort - ); + ); database = session.getDatabase(databaseName); } catch (Exception e) { LOGGER.error( "Cannot connect to CouchDB database '" + databaseName + "' on host '" + databaseHost + "' using port " + databasePort - ); + ); } } @@ -364,14 +360,14 @@ public class CouchDBDao implements IDatabaseDao { Question q = (Question) JSONObject.toBean( results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"), Question.class - ); + ); JSONArray possibleAnswers = new JSONArray(); possibleAnswers = results.getJSONArray("rows").optJSONObject(0).optJSONObject("value") .getJSONArray("possibleAnswers"); Collection<PossibleAnswer> answers = JSONArray.toCollection( possibleAnswers, PossibleAnswer.class - ); + ); q.setPossibleAnswers(new ArrayList<PossibleAnswer>(answers)); q.setSessionKeyword(this.getSessionKeyword(q.getSessionId())); return q; @@ -472,7 +468,7 @@ public class CouchDBDao implements IDatabaseDao { LOGGER.error("IOException: Could not delete question {}", question.get_id()); } } - + @Override public final void deleteAllQuestionsWithAnswers(Session session) { NovaView view = new NovaView("skill_question/by_session"); @@ -483,7 +479,7 @@ public class CouchDBDao implements IDatabaseDao { view.setStartKeyArray(session.get_id()); view.setEndKey(session.get_id(), "{}"); ViewResults results = this.getDatabase().view(view); - + for (Document d : results.getResults()) { Question q = new Question(); q.set_id(d.getId()); @@ -540,7 +536,7 @@ public class CouchDBDao implements IDatabaseDao { return (Answer) JSONObject.toBean( results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"), Answer.class - ); + ); } @Override @@ -565,7 +561,7 @@ public class CouchDBDao implements IDatabaseDao { a.setQuestionId(d.getJSONObject().getJSONArray("key").getString(0)); a.setPiRound(piRound); String answerText = d.getJSONObject().getJSONArray("key").getString(2); - a.setAnswerText(answerText == "null" ? null : answerText); + a.setAnswerText("null".equals(answerText) ? null : answerText); answers.add(a); } return answers; @@ -732,7 +728,7 @@ public class CouchDBDao implements IDatabaseDao { InterposedQuestion question = (InterposedQuestion) JSONObject.toBean( document.getJSONObject().getJSONObject("value"), InterposedQuestion.class - ); + ); question.setSessionId(sessionKey); question.set_id(document.getId()); result.add(question); @@ -861,8 +857,8 @@ public class CouchDBDao implements IDatabaseDao { for (int i = 0; i < rows.size(); i++) { JSONObject row = rows.getJSONObject(i); if ( - row.getString("key").equals(key) - ) { + row.getString("key").equals(key) + ) { result += row.getInt("value"); } } @@ -910,9 +906,9 @@ public class CouchDBDao implements IDatabaseDao { if (d.getJSONObject().optJSONArray("value") != null) { @SuppressWarnings("unchecked") Collection<Session> visitedSessions = JSONArray.toCollection( - d.getJSONObject().getJSONArray("value"), - Session.class - ); + d.getJSONObject().getJSONArray("value"), + Session.class + ); allSessions.addAll(visitedSessions); } } @@ -1000,7 +996,7 @@ public class CouchDBDao implements IDatabaseDao { Session session = (Session) JSONObject.toBean( d.getJSONObject().getJSONObject("value"), Session.class - ); + ); result.add(session); } return result; @@ -1053,6 +1049,7 @@ public class CouchDBDao implements IDatabaseDao { } } + @Override public String getQueryString() { StringBuilder query = new StringBuilder(); if (super.getQueryString() != null) { @@ -1066,7 +1063,9 @@ public class CouchDBDao implements IDatabaseDao { query.append("keys=" + this.keys); } - if (query.toString().isEmpty()) return null; + if (query.toString().isEmpty()) { + return null; + } return query.toString(); } } @@ -1155,9 +1154,9 @@ public class CouchDBDao implements IDatabaseDao { } } return getQuestions(new NovaView(viewName), session); - + } - + private List<Question> getQuestions(NovaView view, Session session) { view.setStartKeyArray(session.get_id()); view.setEndKeyArray(session.get_id(), "{}"); @@ -1174,12 +1173,12 @@ public class CouchDBDao implements IDatabaseDao { Question question = (Question) JSONObject.toBean( document.getJSONObject().getJSONObject("value"), Question.class - ); + ); @SuppressWarnings("unchecked") Collection<PossibleAnswer> answers = JSONArray.toCollection( document.getJSONObject().getJSONObject("value").getJSONArray("possibleAnswers"), PossibleAnswer.class - ); + ); question.setPossibleAnswers(new ArrayList<PossibleAnswer>(answers)); question.setSessionKeyword(session.getKeyword()); if (!"freetext".equals(question.getQuestionType()) && 0 == question.getPiRound()) { @@ -1205,7 +1204,7 @@ public class CouchDBDao implements IDatabaseDao { public int getPreparationQuestionCount(Session session) { return getQuestionCount(new NovaView("skill_question/preparation_question_count_by_session"), session); } - + private int getQuestionCount(NovaView view, Session session) { view.setKey(session.get_id()); ViewResults results = this.getDatabase().view(view); @@ -1224,7 +1223,7 @@ public class CouchDBDao implements IDatabaseDao { public int countPreparationQuestionAnswers(Session session) { return countQuestionVariantAnswers(session, "preparation"); } - + private int countQuestionVariantAnswers(Session session, String variant) { NovaView view = new NovaView("skill_question/count_answers_by_session_and_question_variant"); view.setKey(session.get_id(), variant); @@ -1319,7 +1318,8 @@ public class CouchDBDao implements IDatabaseDao { } return ids; } - + + @Override public void deleteAllInterposedQuestions(Session session) { NovaView view = new NovaView("interposed_question/by_session"); view.setKey(session.get_id()); diff --git a/src/main/java/de/thm/arsnova/dao/NovaView.java b/src/main/java/de/thm/arsnova/dao/NovaView.java index b9325b598ea5208be3412643ed0c31999ef2dc04..e525f06c32ff9c6dbb6d84a304f1e2f2c3e1d733 100644 --- a/src/main/java/de/thm/arsnova/dao/NovaView.java +++ b/src/main/java/de/thm/arsnova/dao/NovaView.java @@ -100,7 +100,7 @@ public class NovaView extends View { private String quote(String string) { return encode("\"" + string + "\""); } - + private boolean isNumber(String string) { return string.matches("^[0-9]+$"); } diff --git a/src/main/java/de/thm/arsnova/services/SessionService.java b/src/main/java/de/thm/arsnova/services/SessionService.java index 205ee49b743cfafe17347bbed23d3c8deca2323e..0d63d14a80ef35230a96756db568389880948199 100644 --- a/src/main/java/de/thm/arsnova/services/SessionService.java +++ b/src/main/java/de/thm/arsnova/services/SessionService.java @@ -128,8 +128,8 @@ public class SessionService implements ISessionService { } List<Session> courseSessions = databaseDao.getCourseSessions( - connectorClient.getCourses(user.getUsername()).getCourse() - ); + connectorClient.getCourses(user.getUsername()).getCourse() + ); Map<String, Session> allAvailableSessions = new HashMap<String, Session>(); @@ -152,8 +152,8 @@ public class SessionService implements ISessionService { public final Session saveSession(final Session session) { if (connectorClient != null && session.getCourseId() != null) { if (!connectorClient.getMembership( - userService.getCurrentUser().getUsername(), session.getCourseId()).isMember() - ) { + userService.getCurrentUser().getUsername(), session.getCourseId()).isMember() + ) { throw new ForbiddenException(); } } diff --git a/src/main/java/de/thm/arsnova/services/UserService.java b/src/main/java/de/thm/arsnova/services/UserService.java index ea8d922bc2a469c6d8c8b9997373fc1ebf74ba7a..8215be82d9241c5a3dd11e3244ef56e916a37ad1 100644 --- a/src/main/java/de/thm/arsnova/services/UserService.java +++ b/src/main/java/de/thm/arsnova/services/UserService.java @@ -170,17 +170,7 @@ public class UserService implements IUserService { User user = null; if (authentication instanceof OAuthAuthenticationToken) { - OAuthAuthenticationToken token = (OAuthAuthenticationToken) authentication; - if (token.getUserProfile() instanceof Google2Profile) { - Google2Profile profile = (Google2Profile) token.getUserProfile(); - user = new User(profile); - } else if (token.getUserProfile() instanceof TwitterProfile) { - TwitterProfile profile = (TwitterProfile) token.getUserProfile(); - user = new User(profile); - } else if (token.getUserProfile() instanceof FacebookProfile) { - FacebookProfile profile = (FacebookProfile) token.getUserProfile(); - user = new User(profile); - } + user = getOAuthUser(authentication, user); } else if (authentication instanceof CasAuthenticationToken) { CasAuthenticationToken token = (CasAuthenticationToken) authentication; user = new User(token.getAssertion().getPrincipal()); @@ -204,6 +194,21 @@ public class UserService implements IUserService { return user; } + private User getOAuthUser(Authentication authentication, User user) { + OAuthAuthenticationToken token = (OAuthAuthenticationToken) authentication; + if (token.getUserProfile() instanceof Google2Profile) { + Google2Profile profile = (Google2Profile) token.getUserProfile(); + user = new User(profile); + } else if (token.getUserProfile() instanceof TwitterProfile) { + TwitterProfile profile = (TwitterProfile) token.getUserProfile(); + user = new User(profile); + } else if (token.getUserProfile() instanceof FacebookProfile) { + FacebookProfile profile = (FacebookProfile) token.getUserProfile(); + user = new User(profile); + } + return user; + } + public boolean isBannedFromLogin(String addr) { return loginBans.contains(addr); } diff --git a/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java b/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java index d63372fa8b4155a7a0f24d16e70b3f2422db5c24..7fbb17ae61e3f4ec1a63cd14f63cbfb53d866bed 100644 --- a/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java +++ b/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java @@ -30,7 +30,6 @@ import de.thm.arsnova.entities.User; import de.thm.arsnova.events.ARSnovaEvent; import de.thm.arsnova.exceptions.NoContentException; import de.thm.arsnova.services.IFeedbackService; -import de.thm.arsnova.services.IQuestionService; import de.thm.arsnova.services.ISessionService; import de.thm.arsnova.services.IUserService; import de.thm.arsnova.socket.message.Feedback; @@ -41,9 +40,6 @@ public class ARSnovaSocketIOServer { @Autowired private IFeedbackService feedbackService; - @Autowired - private IQuestionService questionService; - @Autowired private IUserService userService; @@ -65,14 +61,14 @@ public class ARSnovaSocketIOServer { public ARSnovaSocketIOServer() { config = new Configuration(); } - + @PreDestroy public void closeAllSessions() { LOGGER.info("Close all websockets due to @PreDestroy"); for (SocketIOClient c : server.getAllClients()) { c.disconnect(); } - + int clientCount = 0; for (SocketIOClient c : server.getAllClients()) { c.send(new Packet(PacketType.DISCONNECT)); @@ -135,7 +131,11 @@ public class ARSnovaSocketIOServer { server.addDisconnectListener(new DisconnectListener() { @Override public void onDisconnect(SocketIOClient client) { - if (userService == null || client.getSessionId() == null || userService.getUser2SocketId(client.getSessionId()) == null) { + if ( + userService == null + || client.getSessionId() == null + || userService.getUser2SocketId(client.getSessionId()) == null + ) { LOGGER.warn("NullPointer in ARSnovaSocketIOServer DisconnectListener"); return; } @@ -306,8 +306,8 @@ public class ARSnovaSocketIOServer { broadcastInSession(sessionKey, "lecQuestionAvail", lecturerQuestionId); } - /** Sends event to a websocket connection identified by UUID - * + /** Sends event to a websocket connection identified by UUID + * * @param sessionId The UUID of the websocket ID * @param event The event to be send to client * TODO This method is unimplemented! diff --git a/src/test/java/de/thm/arsnova/ARSnovaChromeDriver.java b/src/test/java/de/thm/arsnova/ARSnovaChromeDriver.java deleted file mode 100644 index 97905e6acc4a7a63f94180b896f1c3020092ca4d..0000000000000000000000000000000000000000 --- a/src/test/java/de/thm/arsnova/ARSnovaChromeDriver.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2012 THM webMedia - * - * This file is part of ARSnova. - * - * ARSnova is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ARSnova is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ -package de.thm.arsnova; - -import org.openqa.selenium.chrome.ChromeDriver; -import org.openqa.selenium.html5.*; -import org.openqa.selenium.remote.html5.*; - -public class ARSnovaChromeDriver extends ChromeDriver implements WebStorage { - - public LocalStorage getLocalStorage() { - return new RemoteLocalStorage(this.getExecuteMethod()); - } - - @Override - public SessionStorage getSessionStorage() { - return new RemoteSessionStorage(this.getExecuteMethod()); - } -} diff --git a/src/test/java/de/thm/arsnova/HttpRestApiTest.java b/src/test/java/de/thm/arsnova/HttpRestApiTest.java deleted file mode 100644 index 31c8994a2dc4352f21ae51d3eba59bf414ca0c79..0000000000000000000000000000000000000000 --- a/src/test/java/de/thm/arsnova/HttpRestApiTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2012 THM webMedia - * - * This file is part of ARSnova. - * - * ARSnova is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ARSnova is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ -package de.thm.arsnova; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Unit test to verify the public RESTlike API. - * - * These tests only check the API communication and structure of responses. They do not verify data. - */ -public class HttpRestApiTest { - public final String host = "localhost"; - public final int port = 8080; - public final String pathPrefix = "/"; - - private HttpURLConnection sendRequest(String path, String method, String accept, HashMap<String, String> parameters, String contentType, String body) throws IOException { - HttpURLConnection conn; - - try { - conn = (HttpURLConnection) (new URL("http", host, port, pathPrefix + path)).openConnection(); - System.out.println(conn.getURL().toExternalForm()); - - conn.setRequestMethod(method); - conn.setRequestProperty("Accept", accept); - conn.setRequestProperty("Host", host + ":" + Integer.valueOf(port)); - - if (null != body) { - conn.setRequestProperty("Content-Type", contentType); - conn.setRequestProperty("Content-Length", Integer.toString(body.getBytes().length)); - conn.setDoOutput(true); - DataOutputStream out = new DataOutputStream(conn.getOutputStream()); - out.writeBytes(body); - out.flush(); - out.close(); - } - } catch (MalformedURLException e) { - conn = null; - e.printStackTrace(); - } - - return conn; - } - - private HttpURLConnection sendRequest(String path, String method, String accept, HashMap<String, String> parameters) throws IOException { - return sendRequest(path, method, accept, parameters, null, null); - } - - private String transformInputToString(InputStream input) throws IOException { - BufferedReader reader = new BufferedReader(new InputStreamReader(input)); - StringBuilder str = new StringBuilder(); - String line; - while (null != (line = reader.readLine())) { - str.append(line); - } - System.out.println(str); - - return str.toString(); - } - - private JSONObject transformInputToJsonObject(InputStream input) throws IOException, JSONException { - return new JSONObject(transformInputToString(input)); - } - - private JSONArray transformInputToJsonArray(InputStream input) throws IOException, JSONException { - return new JSONArray(transformInputToString(input)); - } - - @Ignore("Test not implemented") - @Test - public void testSession() throws Exception { - - } - - @Ignore("Test not implemented") - @Test - public void testQuestionByLecturer() throws Exception { - - } - - @Ignore("Test not implemented") - @Test - public void testQuestionByAudience() throws Exception { - - } - - @Ignore("Test not implemented") - @Test - public void testSocket() throws Exception { - - } - - @Test - public void testCanteen() throws Exception { - HttpURLConnection conn; - JSONArray jsonArr; - String responseBody; - - /* TODO: make test case more specific */ - conn = sendRequest("canteen/menu/vote", "GET", "application/json", null); - assertEquals(200, conn.getResponseCode()); - jsonArr = transformInputToJsonArray(conn.getInputStream()); - assertNotNull(jsonArr); - - conn = sendRequest("canteen/menu/vote/count", "GET", "text/plain", null); - assertEquals(200, conn.getResponseCode()); - responseBody = transformInputToString(conn.getInputStream()); - Integer.valueOf(responseBody); - - /* TODO: implement test for POST /canteen/menu/vote */ - } - - @Test - public void testStatistics() throws Exception { - HttpURLConnection conn; - JSONObject jsonObj; - String responseBody; - - conn = sendRequest("statistics", "GET", "application/json", null); - assertEquals(200, conn.getResponseCode()); - jsonObj = transformInputToJsonObject(conn.getInputStream()); - assertTrue(jsonObj.has("answers")); - assertTrue(jsonObj.has("questions")); - assertTrue(jsonObj.has("openSessions")); - assertTrue(jsonObj.has("closedSessions")); - assertTrue(jsonObj.has("activeUsers")); - - conn = sendRequest("statistics/activeusercount", "GET", "text/plain", null); - assertEquals(200, conn.getResponseCode()); - responseBody = transformInputToString(conn.getInputStream()); - Integer.parseInt(responseBody); - - conn = sendRequest("statistics/sessioncount", "GET", "text/plain", null); - assertEquals(200, conn.getResponseCode()); - responseBody = transformInputToString(conn.getInputStream()); - Integer.parseInt(responseBody); - } -} \ No newline at end of file diff --git a/src/test/java/de/thm/arsnova/Selenium2Test.java b/src/test/java/de/thm/arsnova/Selenium2Test.java deleted file mode 100644 index 98a5211c11e13cbcbb125d0e70bd5412015a949e..0000000000000000000000000000000000000000 --- a/src/test/java/de/thm/arsnova/Selenium2Test.java +++ /dev/null @@ -1,150 +0,0 @@ -package de.thm.arsnova; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Properties; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.html5.LocalStorage; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.ExpectedConditions; -import org.openqa.selenium.support.ui.WebDriverWait; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PropertiesLoaderUtils; - -import de.thm.arsnova.dao.CouchDBDao; -import de.thm.arsnova.entities.Feedback; -import de.thm.arsnova.entities.Session; -import de.thm.arsnova.services.FeedbackService; -import de.thm.arsnova.services.SessionService; -import de.thm.arsnova.services.StubUserService; - -public class Selenium2Test { - - private ARSnovaChromeDriver driver; - private Properties properties; - - private CouchDBDao couchdbDao; - private SessionService sessionService; - private StubUserService userService; - private FeedbackService feedbackService; - - @Before - public final void setUp() throws IOException { - Resource resource = new FileSystemResource("/etc/arsnova/arsnova.properties"); - properties = PropertiesLoaderUtils.loadProperties(resource); - - userService = new StubUserService(); - userService.setUserAuthenticated(true); - - couchdbDao = new CouchDBDao(); - couchdbDao.setDatabaseHost(properties.getProperty("couchdb.host", "localhost")); - couchdbDao.setDatabasePort(properties.getProperty("couchdb.port", "5984")); - couchdbDao.setDatabaseName(properties.getProperty("couchdb.name", "arsnova")); - sessionService = new SessionService(); - couchdbDao.setSessionService(sessionService); - couchdbDao.setUserService(userService); - sessionService.setDatabaseDao(couchdbDao); - feedbackService = new FeedbackService(); - feedbackService.setDatabaseDao(couchdbDao); - - this.driver = new ARSnovaChromeDriver(); - driver.get(properties.getProperty("security.arsnova-url", "http://localhost:8080/arsnova-war/")); - LocalStorage localStorage = this.driver.getLocalStorage(); - localStorage.setItem("html5 info read", ""); - } - - @After - public final void tearDown() { - driver.close(); - driver.quit(); - } - - @Test - public final void studentGuestShouldPostFeedback() { - Session session = couchdbDao.saveSession(createSession()); - Feedback initialFeedback = feedbackService.getFeedback(session.getKeyword()); - - selectStudentRole(); - loginAsGuest(); - joinSession(session); - - WebElement feedbackBadButton = waitForElement(By.className("feedbackBad")); - // Before clicking, ensure that no loading mask is displayed - By loadingSpinner = By.className("x-mask"); - waitWhileVisible(loadingSpinner); - feedbackBadButton.click(); - - // Wait for the feedback to arrive back at the client - By feedbackResultToolbar = By.id("ext-comp-1125"); - waitForElementWithContent(feedbackResultToolbar, "1/"); - - Feedback feedback = feedbackService.getFeedback(session.getKeyword()); - assertEquals(new Feedback(0, 0, 0, 0), initialFeedback); - assertEquals(new Feedback(0, 0, 1, 0), feedback); - } - - private void waitForElementWithContent(final By by, final String content) { - final long timeoutInSecs = 10; - (new WebDriverWait(driver, timeoutInSecs)).until(new ExpectedCondition<Boolean>() { - public Boolean apply(final WebDriver d) { - WebElement element = d.findElement(by); - return element != null && element.getText().contains(content); - } - }); - } - - private void assertEquals(Feedback feedback, Feedback feedback2) { - assertTrue(feedback.equals(feedback2)); - } - - private WebElement waitForElement(final By by) { - final long timeoutInSecs = 10; - (new WebDriverWait(driver, timeoutInSecs)).until(new ExpectedCondition<Boolean>() { - public Boolean apply(final WebDriver d) { - return d.findElement(by) != null; - } - }); - return driver.findElement(by); - } - - private void waitWhileVisible(final By by) { - final long timeoutInSecs = 10; - (new WebDriverWait(driver, timeoutInSecs)).until(ExpectedConditions.invisibilityOfElementLocated(by)); - } - - private Session createSession() { - return createNamedSession(null, null); - } - - private Session createNamedSession(final String name, final String shortName) { - Session session = new Session(); - session.setName(name != null ? name : "selenium test session"); - session.setShortName(shortName != null ? shortName : "selenium"); - return session; - } - - private void joinSession(Session session) { - WebElement sessionKeywordField = waitForElement(By.name("keyword")); - sessionKeywordField.sendKeys(session.getKeyword()); - WebElement joinSessionButton = waitForElement(By.id("ext-gen1138")); - joinSessionButton.click(); - } - - private void loginAsGuest() { - WebElement guestLoginButton = waitForElement(By.id("ext-gen1016")); - guestLoginButton.click(); - } - - private void selectStudentRole() { - WebElement studentRoleButton = waitForElement(By.id("ext-gen1047")); - studentRoleButton.click(); - } -} diff --git a/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java b/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java index 2cf9ff61f7e5e1648aac2f3515ece81861628885..0c9ae13d77bc7dee889f5aff3c8891f9406befbc 100644 --- a/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java +++ b/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java @@ -1,109 +1,72 @@ package de.thm.arsnova.controller; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import javax.inject.Inject; - -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; -import de.thm.arsnova.dao.StubDatabaseDao; -import de.thm.arsnova.exceptions.NoContentException; -import de.thm.arsnova.exceptions.NotFoundException; import de.thm.arsnova.services.StubUserService; @RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml", "file:src/main/webapp/WEB-INF/spring/spring-main.xml", - "file:src/test/resources/test-config.xml" + "file:src/test/resources/test-config.xml", + "file:src/test/resources/test-socketioconfig.xml" }) public class FeedbackControllerTest { - @Inject - private ApplicationContext applicationContext; - private MockHttpServletRequest request; - private MockHttpServletResponse response; - private HandlerAdapter handlerAdapter; - - @Autowired - private FeedbackController feedbackController; - @Autowired private StubUserService userService; - + + private MockMvc mockMvc; + @Autowired - private StubDatabaseDao databaseDao; - - @After - public final void cleanup() { - databaseDao.cleanupTestData(); - } + private WebApplicationContext webApplicationContext; @Before - public void setUp() { - this.request = new MockHttpServletRequest(); - this.response = new MockHttpServletResponse(); - handlerAdapter = applicationContext.getBean(AnnotationMethodHandlerAdapter.class); + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } - @Test(expected = NotFoundException.class) + @Test public void testShouldNotGetFeedbackForUnknownSession() throws Exception { userService.setUserAuthenticated(true); - - request.setMethod("GET"); - request.setRequestURI("/session/00000000/feedback"); - final ModelAndView mav = handlerAdapter.handle(request, response, feedbackController); - - assertNull(mav); - assertTrue(response.getStatus() == 404); + mockMvc.perform(get("/session/00000000/feedback").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); } - @Test(expected = NoContentException.class) + @Test public void testShouldNotGetAverageFeedbackContentForSessionWithoutFeedback() throws Exception { userService.setUserAuthenticated(true); - - request.setMethod("GET"); - request.setRequestURI("/session/12345678/averagefeedback"); - final ModelAndView mav = handlerAdapter.handle(request, response, feedbackController); - - assertNull(mav); - assertTrue(response.getStatus() == 204); + mockMvc.perform(get("/session/12345678/averagefeedback").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); } @Test public void testShouldNotGetCorrectFeedbackCountForSessionWithoutFeedback() throws Exception { userService.setUserAuthenticated(true); - - request.setMethod("GET"); - request.setRequestURI("/session/12345678/feedbackcount"); - handlerAdapter.handle(request, response, feedbackController); - - assertTrue(response.getStatus() == 200); - assertEquals("0", response.getContentAsString()); + mockMvc.perform(get("/session/12345678/feedbackcount").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("0")); } - + @Test public void testShouldReturnFeedback() throws Exception { userService.setUserAuthenticated(true); - - request.setMethod("GET"); - request.setRequestURI("/session/87654321/feedback"); - handlerAdapter.handle(request, response, feedbackController); - - assertTrue(response.getStatus() == 200); + mockMvc.perform(get("/session/87654321/feedback").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); } } diff --git a/src/test/java/de/thm/arsnova/controller/LecturerQuestionControllerTest.java b/src/test/java/de/thm/arsnova/controller/LecturerQuestionControllerTest.java deleted file mode 100644 index 3ea9fb83d1eab66be3813cda4a7eec8933b43e8f..0000000000000000000000000000000000000000 --- a/src/test/java/de/thm/arsnova/controller/LecturerQuestionControllerTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package de.thm.arsnova.controller; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import javax.inject.Inject; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; - -import de.thm.arsnova.dao.StubDatabaseDao; -import de.thm.arsnova.exceptions.NotFoundException; -import de.thm.arsnova.exceptions.UnauthorizedException; -import de.thm.arsnova.services.StubUserService; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml", - "file:src/main/webapp/WEB-INF/spring/spring-main.xml", - "file:src/test/resources/test-config.xml" }) -public class LecturerQuestionControllerTest { - - @Inject - private ApplicationContext applicationContext; - private MockHttpServletRequest request; - private MockHttpServletResponse response; - private HandlerAdapter handlerAdapter; - - @Autowired - private LecturerQuestionController lecturerQuestionController; - - @Autowired - private StubUserService userService; - - @Autowired - private StubDatabaseDao databaseDao; - - @After - public final void cleanup() { - databaseDao.cleanupTestData(); - } - - @Before - public void setUp() { - this.request = new MockHttpServletRequest(); - this.response = new MockHttpServletResponse(); - handlerAdapter = applicationContext - .getBean(AnnotationMethodHandlerAdapter.class); - } - - /* TODO: update test case for API changes or remove it if it is not necessary anymore */ - @Ignore - @Test(expected=NotFoundException.class) - public void testShouldNotGetQestionIdsForUnknownSession() throws Exception { - userService.setUserAuthenticated(true); - - request.setMethod("GET"); - request.setRequestURI("/session/00000000/questionids"); - final ModelAndView mav = handlerAdapter.handle(request, response, lecturerQuestionController); - - assertNull(mav); - assertTrue(response.getStatus() == 404); - } - - /* TODO: update test case for API changes or remove it if it is not necessary anymore */ - @Ignore - @Test(expected=UnauthorizedException.class) - public void testShouldNotGetQuestionIdsIfUnauthorized() throws Exception { - userService.setUserAuthenticated(false); - - request.setMethod("GET"); - request.setRequestURI("/session/00000000/questionids"); - final ModelAndView mav = handlerAdapter.handle(request, response, lecturerQuestionController); - - assertNull(mav); - assertTrue(response.getStatus() == 401); - } - -} diff --git a/src/test/java/de/thm/arsnova/controller/StatisticsControllerTest.java b/src/test/java/de/thm/arsnova/controller/StatisticsControllerTest.java index 63fcbcd0bc271b89c926688f3bbc8fc09b7a0fb9..788c22d376d5b2486b7bb7641d32dfed27fb7f16 100644 --- a/src/test/java/de/thm/arsnova/controller/StatisticsControllerTest.java +++ b/src/test/java/de/thm/arsnova/controller/StatisticsControllerTest.java @@ -1,70 +1,61 @@ package de.thm.arsnova.controller; -import static org.junit.Assert.assertEquals; - -import javax.inject.Inject; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/arsnova-servlet.xml", "file:src/main/webapp/WEB-INF/spring/spring-main.xml", - "file:src/test/resources/test-config.xml" + "file:src/test/resources/test-config.xml", + "file:src/test/resources/test-socketioconfig.xml" }) public class StatisticsControllerTest { - @Inject - private ApplicationContext applicationContext; - private MockHttpServletRequest request; - private MockHttpServletResponse response; - private HandlerAdapter handlerAdapter; - @Autowired private StatisticsController statisticsController; + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + @Before - public final void setUp() { - this.request = new MockHttpServletRequest(); - this.response = new MockHttpServletResponse(); - handlerAdapter = applicationContext.getBean(AnnotationMethodHandlerAdapter.class); + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public final void testShouldGetCurrentOnlineUsers() throws Exception { - request.setMethod("GET"); - request.setRequestURI("/statistics/activeusercount"); - handlerAdapter.handle(request, response, statisticsController); - - assertEquals("0", response.getContentAsString()); + mockMvc.perform(get("/statistics/activeusercount")) + .andExpect(status().isOk()) + .andExpect(content().string("0")); } - + @Test public final void testShouldGetSessionCount() throws Exception { - request.setMethod("GET"); - request.setRequestURI("/statistics/sessioncount"); - handlerAdapter.handle(request, response, statisticsController); - - assertEquals("3", response.getContentAsString()); + mockMvc.perform(get("/statistics/sessioncount")) + .andExpect(status().isOk()) + .andExpect(content().string("3")); } - + @Test public final void testShouldGetStatistics() throws Exception { - request.setMethod("GET"); - request.setRequestURI("/statistics/"); - handlerAdapter.handle(request, response, statisticsController); - - String expected = "{\"answers\":0,\"questions\":0,\"openSessions\":3,\"closedSessions\":0,\"activeUsers\":0}"; - assertEquals(expected, response.getContentAsString()); + mockMvc.perform(get("/statistics")) + .andExpect(status().isOk()) + .andExpect(content().string("{\"answers\":0,\"questions\":0,\"openSessions\":3,\"closedSessions\":0,\"activeUsers\":0}")); } } diff --git a/src/test/resources/test-socketioconfig.xml b/src/test/resources/test-socketioconfig.xml new file mode 100644 index 0000000000000000000000000000000000000000..844695c967c031e2b3900ce737c2ea0a5811944c --- /dev/null +++ b/src/test/resources/test-socketioconfig.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:p="http://www.springframework.org/schema/p" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> + + <bean id="socketServer" class="de.thm.arsnova.socket.ARSnovaSocketIOServer" + init-method="startServer" destroy-method="stopServer" scope="singleton" + p:portNumber="11443" p:hostIp="${socketio.ip}" p:useSSL="${security.ssl}" p:keystore="${security.keystore}" + p:storepass="${security.storepass}" /> +</beans>