diff --git a/ARSnova-checkstyle-checker.xml b/ARSnova-checkstyle-checker.xml new file mode 100644 index 0000000000000000000000000000000000000000..59405d3facc5f97433f051dc7b68cbdd0e8a667d --- /dev/null +++ b/ARSnova-checkstyle-checker.xml @@ -0,0 +1,191 @@ +<?xml version="1.0"?> +<!DOCTYPE module PUBLIC + "-//Puppy Crawl//DTD Check Configuration 1.2//EN" + "http://www.puppycrawl.com/dtds/configuration_1_2.dtd"> + +<!-- + + Checkstyle configuration that checks the sun coding conventions from: + + - the Java Language Specification at + http://java.sun.com/docs/books/jls/second_edition/html/index.html + + - the Sun Code Conventions at http://java.sun.com/docs/codeconv/ + + - the Javadoc guidelines at + http://java.sun.com/j2se/javadoc/writingdoccomments/index.html + + - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html + + - some best practices + + Checkstyle is very configurable. Be sure to read the documentation at + http://checkstyle.sf.net (or in your downloaded distribution). + + Most Checks are configurable, be sure to consult the documentation. + + To completely disable a check, just comment it out or delete it from the file. + + Finally, it is worth reading the documentation. + +--> + +<module name="Checker"> + <!-- + If you set the basedir property below, then all reported file + names will be relative to the specified directory. See + http://checkstyle.sourceforge.net/5.x/config.html#Checker + + <property name="basedir" value="${basedir}"/> + --> + + <!-- Checks that each Java package has a Javadoc file used for commenting. --> + <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage --> + <module name="JavadocPackage"> + <property name="allowLegacy" value="true"/> + </module> + + <!-- Checks whether files end with a new line. --> + <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile --> + <module name="NewlineAtEndOfFile"/> + + <!-- Checks that property files contain the same keys. --> + <!-- See http://checkstyle.sf.net/config_misc.html#Translation --> + <module name="Translation"/> + + <module name="FileLength"/> + + <!-- Following interprets the header file as regular expressions. --> + <!-- <module name="RegexpHeader"/> --> + + <!--module name="FileTabCharacter"> + <property name="eachLine" value="true"/> + </module--> + + <module name="RegexpSingleline"> + <!-- \s matches whitespace character, $ matches end of line. --> + <property name="format" value="\s+$"/> + <property name="message" value="Line has trailing spaces."/> + </module> + + <module name="TreeWalker"> + + <property name="cacheFile" value="${checkstyle.cache.file}"/> + + <!-- Checks for Javadoc comments. --> + <!-- See http://checkstyle.sf.net/config_javadoc.html --> + <!-- module name="JavadocMethod"> + <property name="allowMissingJavadoc" value="true"/> + </module> + <module name="JavadocType"/> + <module name="JavadocVariable"/> + <module name="JavadocStyle"/--> + + + <!-- Checks for Naming Conventions. --> + <!-- See http://checkstyle.sf.net/config_naming.html --> + <module name="ConstantName"/> + <module name="LocalFinalVariableName"/> + <module name="LocalVariableName"/> + <module name="MemberName"/> + <module name="MethodName"/> + <module name="PackageName"/> + <module name="ParameterName"/> + <module name="StaticVariableName"/> + <module name="TypeName"/> + + + <!-- Checks for Headers --> + <!-- See http://checkstyle.sf.net/config_header.html --> + <!-- <module name="Header"> --> + <!-- The follow property value demonstrates the ability --> + <!-- to have access to ANT properties. In this case it uses --> + <!-- the ${basedir} property to allow Checkstyle to be run --> + <!-- from any directory within a project. See property --> + <!-- expansion, --> + <!-- http://checkstyle.sf.net/config.html#properties --> + <!-- <property --> + <!-- name="headerFile" --> + <!-- value="${basedir}/java.header"/> --> + <!-- </module> --> + + + <!-- Checks for imports --> + <!-- See http://checkstyle.sf.net/config_import.html --> + <module name="AvoidStarImport"/> + <module name="IllegalImport"/> <!-- defaults to sun.* packages --> + <module name="RedundantImport"/> + <module name="UnusedImports"/> + + + <!-- Checks for Size Violations. --> + <!-- See http://checkstyle.sf.net/config_sizes.html --> + <module name="LineLength"> + <property name="max" value="120" /> + </module> + <module name="MethodLength"/> + <module name="ParameterNumber"/> + + + <!-- Checks for whitespace --> + <!-- See http://checkstyle.sf.net/config_whitespace.html --> + <module name="EmptyForIteratorPad"/> + <module name="MethodParamPad"/> + <module name="NoWhitespaceAfter"/> + <module name="NoWhitespaceBefore"/> + <module name="OperatorWrap"/> + <module name="ParenPad"/> + <module name="TypecastParenPad"/> + <module name="WhitespaceAfter"/> + <module name="WhitespaceAround"/> + + + <!-- Modifier Checks --> + <!-- See http://checkstyle.sf.net/config_modifiers.html --> + <module name="ModifierOrder"/> + <module name="RedundantModifier"/> + + + <!-- Checks for blocks. You know, those {}'s --> + <!-- See http://checkstyle.sf.net/config_blocks.html --> + <module name="AvoidNestedBlocks"/> + <module name="EmptyBlock"/> + <module name="LeftCurly"/> + <module name="NeedBraces"/> + <module name="RightCurly"/> + + + <!-- Checks for common coding problems --> + <!-- See http://checkstyle.sf.net/config_coding.html --> + <module name="AvoidInlineConditionals"/> + <module name="DoubleCheckedLocking"/> <!-- MY FAVOURITE --> + <module name="EmptyStatement"/> + <module name="EqualsHashCode"/> + <module name="HiddenField"/> + <module name="IllegalInstantiation"/> + <module name="InnerAssignment"/> + <module name="MagicNumber"/> + <module name="MissingSwitchDefault"/> + <module name="RedundantThrows"/> + <module name="SimplifyBooleanExpression"/> + <module name="SimplifyBooleanReturn"/> + + <!-- Checks for class design --> + <!-- See http://checkstyle.sf.net/config_design.html --> + <module name="DesignForExtension"/> + <module name="FinalClass"/> + <module name="HideUtilityClassConstructor"/> + <module name="InterfaceIsType"/> + <module name="VisibilityModifier"/> + + + <!-- Miscellaneous other checks. --> + <!-- See http://checkstyle.sf.net/config_misc.html --> + <module name="ArrayTypeStyle"/> + <module name="FinalParameters"/> + <module name="TodoComment"/> + <module name="UpperEll"/> + + </module> + +</module> diff --git a/pom.xml b/pom.xml index eaa346f266287c043e0b45d5952ab599a1031d75..b44ab394b548ad9a6878511838986166fa32ebca 100644 --- a/pom.xml +++ b/pom.xml @@ -92,6 +92,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> + <version>2.9</version> <configuration></configuration> </plugin> <plugin> @@ -100,6 +101,14 @@ <version>2.5.2</version> <configuration></configuration> </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-checkstyle-plugin</artifactId> + <version>2.9.1</version> + <configuration> + <configLocation>ARSnova-checkstyle-checker.xml</configLocation> + </configuration> + </plugin> </plugins> </reporting> @@ -339,6 +348,14 @@ <artifactId>aspectj-maven-plugin</artifactId> <version>1.4</version> </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-checkstyle-plugin</artifactId> + <version>2.9.1</version> + <configuration> + <configLocation>ARSnova-checkstyle-checker.xml</configLocation> + </configuration> + </plugin> </plugins> </build> diff --git a/src/main/java/de/thm/arsnova/CASLogoutSuccessHandler.java b/src/main/java/de/thm/arsnova/CASLogoutSuccessHandler.java index e173c8ea4127cf5a11caeac94b15cb9683d9ca1e..013ddc1d8e956f51fe00dd3c0d754c900b6f1021 100644 --- a/src/main/java/de/thm/arsnova/CASLogoutSuccessHandler.java +++ b/src/main/java/de/thm/arsnova/CASLogoutSuccessHandler.java @@ -15,33 +15,36 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl public class CASLogoutSuccessHandler implements LogoutSuccessHandler { - public static final Logger logger = LoggerFactory.getLogger(CASLogoutSuccessHandler.class); - + public static final Logger LOGGER = LoggerFactory.getLogger(CASLogoutSuccessHandler.class); + private String casUrl; private String defaultTarget; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override - public void onLogoutSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws IOException, ServletException { - + public final void onLogoutSuccess( + final HttpServletRequest request, + final HttpServletResponse response, + final Authentication authentication + ) throws IOException, ServletException { String referer = request.getHeader("referer"); - if (response.isCommitted()) { - logger.info("Response has already been committed. Unable to redirect to target"); - return; - } - redirectStrategy.sendRedirect(request, response, - (casUrl + "/logout?url=") + (referer != null ? referer : defaultTarget)); - + if (response.isCommitted()) { + LOGGER.info("Response has already been committed. Unable to redirect to target"); + return; + } + redirectStrategy.sendRedirect( + request, + response, + (casUrl + "/logout?url=") + (referer != null ? referer : defaultTarget) + ); } - public void setCasUrl(String casUrl) { - this.casUrl = casUrl; + public final void setCasUrl(final String newCasUrl) { + casUrl = newCasUrl; } - public void setDefaultTarget(String defaultTarget) { - this.defaultTarget = defaultTarget; + public final void setDefaultTarget(final String newDefaultTarget) { + defaultTarget = newDefaultTarget; } } diff --git a/src/main/java/de/thm/arsnova/CasUserDetailsService.java b/src/main/java/de/thm/arsnova/CasUserDetailsService.java index 1f3fb4a7f24471eaa7fff8678d75ebe7e4eaaa75..7ad909d2b26ad439cc9590d224cb441151216484 100644 --- a/src/main/java/de/thm/arsnova/CasUserDetailsService.java +++ b/src/main/java/de/thm/arsnova/CasUserDetailsService.java @@ -1,6 +1,6 @@ /* * Copyright (C) 2012 THM webMedia - * + * * This file is part of ARSnova. * * ARSnova is free software: you can redistribute it and/or modify @@ -30,13 +30,22 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; @Service -public class CasUserDetailsService extends AbstractCasAssertionUserDetailsService { - +public class CasUserDetailsService extends + AbstractCasAssertionUserDetailsService { + @Override - protected UserDetails loadUserDetails(Assertion assertion) { + protected final UserDetails loadUserDetails(final Assertion assertion) { final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER")); - - return new User(assertion.getPrincipal().getName(), "", true, true, true, true, grantedAuthorities); + + return new User( + assertion.getPrincipal().getName(), + "", + true, + true, + true, + true, + grantedAuthorities + ); } } diff --git a/src/main/java/de/thm/arsnova/LoginAuthenticationFailureHandler.java b/src/main/java/de/thm/arsnova/LoginAuthenticationFailureHandler.java index 0864cc5b3d105f152a2079668899038533f70b94..72770e629f66001ac003966e73070d3a0702a018 100644 --- a/src/main/java/de/thm/arsnova/LoginAuthenticationFailureHandler.java +++ b/src/main/java/de/thm/arsnova/LoginAuthenticationFailureHandler.java @@ -1,6 +1,6 @@ /* * Copyright (C) 2012 THM webMedia - * + * * This file is part of ARSnova. * * ARSnova is free software: you can redistribute it and/or modify @@ -30,25 +30,27 @@ import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; -public class LoginAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { - +public class LoginAuthenticationFailureHandler extends + SimpleUrlAuthenticationFailureHandler { + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private String defaultFailureUrl; - + @Override - public void onAuthenticationFailure(HttpServletRequest request, - HttpServletResponse response, AuthenticationException exception) - throws IOException, ServletException { - + public final void onAuthenticationFailure( + final HttpServletRequest request, + final HttpServletResponse response, + final AuthenticationException exception + ) throws IOException, ServletException { HttpSession session = request.getSession(); if (session != null && session.getAttribute("ars-referer") != null) { defaultFailureUrl = (String) session.getAttribute("ars-referer"); } - + redirectStrategy.sendRedirect(request, response, defaultFailureUrl); } - - public void setDefaultFailureUrl(String defaultFailureUrl) { + + public final void setDefaultFailureUrl(final String defaultFailureUrl) { this.defaultFailureUrl = defaultFailureUrl; } diff --git a/src/main/java/de/thm/arsnova/LoginAuthenticationSucessHandler.java b/src/main/java/de/thm/arsnova/LoginAuthenticationSucessHandler.java index 9975409349163c3d6b8f9c4084a178d488dbb1b3..11ea77fb60fc474103b837f125b5aad948350e3f 100644 --- a/src/main/java/de/thm/arsnova/LoginAuthenticationSucessHandler.java +++ b/src/main/java/de/thm/arsnova/LoginAuthenticationSucessHandler.java @@ -24,13 +24,16 @@ import javax.servlet.http.HttpSession; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; -public class LoginAuthenticationSucessHandler extends SimpleUrlAuthenticationSuccessHandler { +public class LoginAuthenticationSucessHandler extends + SimpleUrlAuthenticationSuccessHandler { private String targetUrl; - + @Override - protected String determineTargetUrl(HttpServletRequest request, - HttpServletResponse response) { + protected final String determineTargetUrl( + final HttpServletRequest request, + final HttpServletResponse response + ) { HttpSession session = request.getSession(); if (session == null || session.getAttribute("ars-referer") == null) { return targetUrl; @@ -38,8 +41,8 @@ public class LoginAuthenticationSucessHandler extends SimpleUrlAuthenticationSuc String referer = (String) session.getAttribute("ars-referer"); return referer + targetUrl; } - - public void setTargetUrl(String targetUrl) { + + public final void setTargetUrl(final String targetUrl) { this.targetUrl = targetUrl; } } diff --git a/src/main/java/de/thm/arsnova/OpenidUserDetailsService.java b/src/main/java/de/thm/arsnova/OpenidUserDetailsService.java index a1545487cf92fb3a7ab13e63e287967cf74e0fa1..aca25f32ebe71d4064069e8bffa0b1e3cea549c9 100644 --- a/src/main/java/de/thm/arsnova/OpenidUserDetailsService.java +++ b/src/main/java/de/thm/arsnova/OpenidUserDetailsService.java @@ -1,6 +1,6 @@ /* * Copyright (C) 2012 THM webMedia - * + * * This file is part of ARSnova. * * ARSnova is free software: you can redistribute it and/or modify @@ -30,11 +30,19 @@ import org.springframework.stereotype.Service; @Service public class OpenidUserDetailsService implements UserDetailsService { - - public UserDetails loadUserByUsername(String openIdIdentifier) { + + public final UserDetails loadUserByUsername(final String openIdIdentifier) { final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER")); - - return new User(openIdIdentifier, "", true, true, true, true, grantedAuthorities); - } -} \ No newline at end of file + + return new User( + openIdIdentifier, + "", + true, + true, + true, + true, + grantedAuthorities + ); + } +} diff --git a/src/main/java/de/thm/arsnova/annotation/package-info.java b/src/main/java/de/thm/arsnova/annotation/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..f833d035049886c096cc6709ad0f32a90e0e6e74 --- /dev/null +++ b/src/main/java/de/thm/arsnova/annotation/package-info.java @@ -0,0 +1,2 @@ +package de.thm.arsnova.annotation; + diff --git a/src/main/java/de/thm/arsnova/aop/AuthorizationAdviser.java b/src/main/java/de/thm/arsnova/aop/AuthorizationAdviser.java index 9a24f3176de9d3fd65e2eff2e2e971975b73e95b..bc41e869095949c159e69deb49253ee608e89e7e 100644 --- a/src/main/java/de/thm/arsnova/aop/AuthorizationAdviser.java +++ b/src/main/java/de/thm/arsnova/aop/AuthorizationAdviser.java @@ -11,32 +11,38 @@ import de.thm.arsnova.services.IUserService; @Aspect public class AuthorizationAdviser { - static IUserService userService; - - public void setUserService(IUserService uService) { + private static IUserService userService; + + public final void setUserService(final IUserService uService) { userService = uService; } - - /** This method checks if the user has a valid authorization from security context - * + + /** + * This method checks if the user has a valid authorization from security + * context + * * @param authenticated * @param object */ @Before("execution(public * de.thm.arsnova.services.*.*(..)) && @annotation(authenticated) && this(object)") - public void checkAuthorization(Authenticated authenticated, Object object) { + public final void checkAuthorization(final Authenticated authenticated, final Object object) { User u = userService.getCurrentUser(); - if (u == null) throw new UnauthorizedException(); - // TODO: For unauthorized users e.g. after logout there is still a user object with username 'anonymous' - if (u.getUsername().equals("anonymous")) throw new UnauthorizedException(); + if (u == null) { + throw new UnauthorizedException(); + } + if (u.getUsername().equals("anonymous")) { + throw new UnauthorizedException(); + } } - - /** This method checks if the user is enlisted in current ARSnova session + + /** + * This method checks if the user is enlisted in current ARSnova session * * @param authenticated * @param object */ @Before("execution(public * de.thm.arsnova.services.*.*(..)) && @annotation(authenticated) && this(object)") - public void checkSessionMembership(Authenticated authenticated, Object object) { - //TODO: Implement check based on session membership lists + public final void checkSessionMembership(final Authenticated authenticated, final Object object) { + /// TODO: Implement check based on session membership lists } } diff --git a/src/main/java/de/thm/arsnova/aop/package-info.java b/src/main/java/de/thm/arsnova/aop/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..698958d605d106ac1d216f37c3ff7a05d85a4445 --- /dev/null +++ b/src/main/java/de/thm/arsnova/aop/package-info.java @@ -0,0 +1,2 @@ +package de.thm.arsnova.aop; + diff --git a/src/main/java/de/thm/arsnova/controller/AbstractController.java b/src/main/java/de/thm/arsnova/controller/AbstractController.java index 251dafbea2c19f66deb39fc9e63b86f184ac7571..0e6d2b5268546d6ea59aad49b36425c331ecc30e 100644 --- a/src/main/java/de/thm/arsnova/controller/AbstractController.java +++ b/src/main/java/de/thm/arsnova/controller/AbstractController.java @@ -13,19 +13,21 @@ import de.thm.arsnova.exceptions.UnauthorizedException; public class AbstractController { @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(NotFoundException.class) - public void handleNotFoundException(Exception e, HttpServletRequest request) { - + public void handleNotFoundException(final Exception e, HttpServletRequest request) { } - + @ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(ForbiddenException.class) - public void handleForbiddenException(Exception e, HttpServletRequest request) { - + public void handleForbiddenException(final Exception e, HttpServletRequest request) { } - + @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(UnauthorizedException.class) - public void handleUnauthorizedException(Exception e, HttpServletRequest request) { - + public void handleUnauthorizedException(final Exception e, HttpServletRequest request) { + } + + @ResponseStatus(HttpStatus.NO_CONTENT) + @ExceptionHandler(UnauthorizedException.class) + public void handleNoContentException(final Exception e, HttpServletRequest request) { } } diff --git a/src/main/java/de/thm/arsnova/controller/FeedbackController.java b/src/main/java/de/thm/arsnova/controller/FeedbackController.java index b91cec4859999a684c3411ef6d106c1238de47b1..f79d4e05241d0fe92780f71ea1ba8dea5ecf8dcf 100644 --- a/src/main/java/de/thm/arsnova/controller/FeedbackController.java +++ b/src/main/java/de/thm/arsnova/controller/FeedbackController.java @@ -39,37 +39,58 @@ import de.thm.arsnova.socket.ARSnovaSocketIOServer; @Controller public class FeedbackController extends AbstractController { - + public static final Logger logger = LoggerFactory.getLogger(FeedbackController.class); - + @Autowired IFeedbackService feedbackService; - + @Autowired IUserService userService; - + @Autowired ARSnovaSocketIOServer server; - - @RequestMapping(value="/session/{sessionkey}/feedback", method=RequestMethod.GET) + + @RequestMapping(value = "/session/{sessionkey}/feedback", method = RequestMethod.GET) @ResponseBody public Feedback getFeedback(@PathVariable String sessionkey) { return feedbackService.getFeedback(sessionkey); } - - @RequestMapping(value="/session/{sessionkey}/feedbackcount", method=RequestMethod.GET) + + @RequestMapping(value = "/session/{sessionkey}/myfeedback", method = RequestMethod.GET) + @ResponseBody + public Integer getMyFeedback(@PathVariable String sessionkey, HttpServletResponse response) { + Integer value = feedbackService.getMyFeedback(sessionkey, userService.getCurrentUser()); + if (value != null && value >= 0 && value <= 3) { + return value; + } + response.setStatus(HttpStatus.NOT_FOUND.value()); + return null; + } + + @RequestMapping(value = "/session/{sessionkey}/feedbackcount", method = RequestMethod.GET) @ResponseBody public int getFeedbackCount(@PathVariable String sessionkey) { return feedbackService.getFeedbackCount(sessionkey); } + + @RequestMapping(value = "/session/{sessionkey}/roundedaveragefeedback", method = RequestMethod.GET) + @ResponseBody + public long getAverageFeedbackRounded( + @PathVariable String sessionkey + ) { + return feedbackService.getAverageFeedbackRounded(sessionkey); + } - @RequestMapping(value="/session/{sessionkey}/averagefeedback", method=RequestMethod.GET) + @RequestMapping(value = "/session/{sessionkey}/averagefeedback", method = RequestMethod.GET) @ResponseBody - public long getAverageFeedback(@PathVariable String sessionkey) { + public double getAverageFeedback( + @PathVariable String sessionkey + ) { return feedbackService.getAverageFeedback(sessionkey); } - - @RequestMapping(value="/session/{sessionkey}/feedback", method=RequestMethod.POST) + + @RequestMapping(value = "/session/{sessionkey}/feedback", method = RequestMethod.POST) @ResponseBody public Feedback postFeedback(@PathVariable String sessionkey, @RequestBody int value, HttpServletResponse response) { User user = userService.getCurrentUser(); @@ -80,11 +101,11 @@ public class FeedbackController extends AbstractController { response.setStatus(HttpStatus.CREATED.value()); return feedback; } - + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); return null; } - + response.setStatus(HttpStatus.BAD_REQUEST.value()); return null; } diff --git a/src/main/java/de/thm/arsnova/controller/LoginController.java b/src/main/java/de/thm/arsnova/controller/LoginController.java index e55c8386ce30e7d81f225b5a98237ff17683f230..f1f6f2f49858aac2e7a816e9bd5e3430b98cc9df 100644 --- a/src/main/java/de/thm/arsnova/controller/LoginController.java +++ b/src/main/java/de/thm/arsnova/controller/LoginController.java @@ -58,53 +58,68 @@ public class LoginController extends AbstractController { @Autowired TwitterProvider twitterProvider; - + @Autowired Google2Provider googleProvider; - + @Autowired FacebookProvider facebookProvider; - + @Autowired CasAuthenticationEntryPoint casEntryPoint; - + @Autowired IUserService userService; - - public static final Logger logger = LoggerFactory.getLogger(LoginController.class); + + public static final Logger logger = LoggerFactory + .getLogger(LoginController.class); @RequestMapping(method = RequestMethod.GET, value = "/doLogin") - public View doLogin(@RequestParam("type") String type, @RequestParam(value="user", required=false) String guestName, HttpServletRequest request, HttpServletResponse response) + public View doLogin(@RequestParam("type") String type, + @RequestParam(value = "user", required = false) String guestName, + HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String referer = request.getHeader("referer"); request.getSession().setAttribute("ars-referer", referer); - if("cas".equals(type)) { + if ("cas".equals(type)) { casEntryPoint.commence(request, response, null); - } else if("twitter".equals(type)) { - String authUrl = twitterProvider.getAuthorizationUrl(new HttpUserSession(request)); + } else if ("twitter".equals(type)) { + String authUrl = twitterProvider + .getAuthorizationUrl(new HttpUserSession(request)); return new RedirectView(authUrl); - } else if("facebook".equals(type)) { - String authUrl = facebookProvider.getAuthorizationUrl(new HttpUserSession(request)); + } else if ("facebook".equals(type)) { + String authUrl = facebookProvider + .getAuthorizationUrl(new HttpUserSession(request)); return new RedirectView(authUrl); - } else if("google".equals(type)) { - String authUrl = googleProvider.getAuthorizationUrl(new HttpUserSession(request)); + } else if ("google".equals(type)) { + String authUrl = googleProvider + .getAuthorizationUrl(new HttpUserSession(request)); return new RedirectView(authUrl); - } else if("guest".equals(type)) { + } else if ("guest".equals(type)) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority("ROLE_GUEST")); String username = ""; - if(guestName != null && guestName.startsWith("Guest") && guestName.length() == 15) { + if (guestName != null && guestName.startsWith("Guest") + && guestName.length() == 15) { username = guestName; } else { - username = "Guest" + Sha512DigestUtils.shaHex(request.getSession().getId()).substring(0, 10); - } - org.springframework.security.core.userdetails.User user = - new org.springframework.security.core.userdetails.User(username, "", true, true, true, true, authorities); - Authentication token = new UsernamePasswordAuthenticationToken(user, null, authorities); + username = "Guest" + + Sha512DigestUtils + .shaHex(request.getSession().getId()) + .substring(0, 10); + } + org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User( + username, "", true, true, true, true, authorities); + Authentication token = new UsernamePasswordAuthenticationToken( + user, null, authorities); SecurityContextHolder.getContext().setAuthentication(token); - request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); - return new RedirectView((referer != null ? referer : "/") + "#auth/checkLogin"); + request.getSession(true) + .setAttribute( + HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + SecurityContextHolder.getContext()); + return new RedirectView((referer != null ? referer : "/") + + "#auth/checkLogin"); } return null; } @@ -117,12 +132,15 @@ public class LoginController extends AbstractController { @RequestMapping(method = RequestMethod.GET, value = "/logout") public View doLogout(final HttpServletRequest request) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); request.getSession().invalidate(); SecurityContextHolder.clearContext(); if (auth instanceof CasAuthenticationToken) { return new RedirectView("/j_spring_cas_security_logout"); } - return new RedirectView(request.getHeader("referer") != null ? request.getHeader("referer") : "/" ); + return new RedirectView( + request.getHeader("referer") != null ? request + .getHeader("referer") : "/"); } } diff --git a/src/main/java/de/thm/arsnova/controller/QuestionController.java b/src/main/java/de/thm/arsnova/controller/QuestionController.java index 7b38deb01bd0454cf7a397db19266237d4b0863c..a2ba464527b59dcc5a3b4c0c9348146b60236f19 100644 --- a/src/main/java/de/thm/arsnova/controller/QuestionController.java +++ b/src/main/java/de/thm/arsnova/controller/QuestionController.java @@ -31,6 +31,7 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import de.thm.arsnova.entities.Question; @@ -39,60 +40,60 @@ import de.thm.arsnova.services.IQuestionService; import de.thm.arsnova.services.IUserService; import de.thm.arsnova.socket.ARSnovaSocketIOServer; - @Controller public class QuestionController extends AbstractController { - - public static final Logger logger = LoggerFactory.getLogger(QuestionController.class); - + + public static final Logger logger = LoggerFactory + .getLogger(QuestionController.class); + @Autowired IQuestionService questionService; - + @Autowired IUserService userService; - + @Autowired ARSnovaSocketIOServer server; - @RequestMapping(value="/session/{sessionkey}/question/{questionId}", method=RequestMethod.GET) + @RequestMapping(value = "/session/{sessionkey}/question/{questionId}", method = RequestMethod.GET) @ResponseBody - public Question getQuestion(@PathVariable String sessionkey, @PathVariable String questionId, HttpServletResponse response) { + public Question getQuestion(@PathVariable String sessionkey, + @PathVariable String questionId, HttpServletResponse response) { Question question = questionService.getQuestion(questionId, sessionkey); if (question != null) { return question; - } + } + response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } - - @RequestMapping(value="/session/{sessionkey}/question", method=RequestMethod.POST) + + @RequestMapping(value = "/session/{sessionkey}/question", method = RequestMethod.POST) @ResponseBody - public void postQuestion(@PathVariable String sessionkey, @RequestBody Question question, HttpServletResponse response) { - if (! sessionkey.equals(question.getSession())) { + public void postQuestion(@PathVariable String sessionkey, + @RequestBody Question question, HttpServletResponse response) { + if (!sessionkey.equals(question.getSession())) { response.setStatus(HttpStatus.PRECONDITION_FAILED.value()); return; } - + if (questionService.saveQuestion(question)) { response.setStatus(HttpStatus.CREATED.value()); return; } - + response.setStatus(HttpStatus.BAD_REQUEST.value()); return; } - - @RequestMapping( - value={ - "/getSkillQuestions/{sessionkey}", - "/session/{sessionkey}/skillquestions" - }, - method=RequestMethod.GET - ) + + @RequestMapping(value = { "/getSkillQuestions/{sessionkey}", + "/session/{sessionkey}/skillquestions" }, method = RequestMethod.GET) @ResponseBody - public List<Question> getSkillQuestions(@PathVariable String sessionkey, HttpServletResponse response) { - List<Question> questions = questionService.getSkillQuestions(sessionkey); - if(questions == null || questions.isEmpty()) { + public List<Question> getSkillQuestions(@PathVariable String sessionkey, + HttpServletResponse response) { + List<Question> questions = questionService + .getSkillQuestions(sessionkey); + if (questions == null || questions.isEmpty()) { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } diff --git a/src/main/java/de/thm/arsnova/controller/SessionController.java b/src/main/java/de/thm/arsnova/controller/SessionController.java index 3d45cb90fc291c79bf841c145f9c9c8dd6f8de17..e8bd7801273d1484b1987de26b023ae0ee88ea00 100644 --- a/src/main/java/de/thm/arsnova/controller/SessionController.java +++ b/src/main/java/de/thm/arsnova/controller/SessionController.java @@ -47,53 +47,60 @@ import de.thm.arsnova.socket.ARSnovaSocketIOServer; @Controller public class SessionController extends AbstractController { - - public static final Logger logger = LoggerFactory.getLogger(SessionController.class); - + + public static final Logger logger = LoggerFactory + .getLogger(SessionController.class); + @Autowired ISessionService sessionService; - + @Autowired IUserService userService; - + @Autowired ARSnovaSocketIOServer server; - + @RequestMapping(method = RequestMethod.POST, value = "/authorize") - public void authorize(@RequestBody Object sessionObject, HttpServletResponse response) { - String socketid = (String) JSONObject.fromObject(sessionObject).get("session"); - if(socketid == null) { + public void authorize(@RequestBody Object sessionObject, + HttpServletResponse response) { + String socketid = (String) JSONObject.fromObject(sessionObject).get( + "session"); + if (socketid == null) { return; - } + } User u = userService.getCurrentUser(); logger.info("authorize session: " + socketid + ", user is: " + u); - response.setStatus(u != null ? HttpStatus.CREATED.value() : HttpStatus.UNAUTHORIZED.value()); + response.setStatus(u != null ? HttpStatus.CREATED.value() + : HttpStatus.UNAUTHORIZED.value()); userService.putUser2SessionID(UUID.fromString(socketid), u); } - - @RequestMapping(value="/session/{sessionkey}", method=RequestMethod.GET) + + @RequestMapping(value = "/session/{sessionkey}", method = RequestMethod.GET) @ResponseBody public Session joinSession(@PathVariable String sessionkey) { return sessionService.joinSession(sessionkey); } - - @RequestMapping(value="/session/{sessionkey}/online", method=RequestMethod.POST) + + @RequestMapping(value = "/session/{sessionkey}/online", method = RequestMethod.POST) @ResponseBody - public LoggedIn registerAsOnlineUser(@PathVariable String sessionkey, HttpServletResponse response) { + public LoggedIn registerAsOnlineUser(@PathVariable String sessionkey, + HttpServletResponse response) { User user = userService.getCurrentUser(); - LoggedIn loggedIn = sessionService.registerAsOnlineUser(user, sessionkey); + LoggedIn loggedIn = sessionService.registerAsOnlineUser(user, + sessionkey); if (loggedIn != null) { response.setStatus(HttpStatus.CREATED.value()); return loggedIn; } - + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); return null; } - - @RequestMapping(value="/session", method=RequestMethod.POST) + + @RequestMapping(value = "/session", method = RequestMethod.POST) @ResponseBody - public Session postNewSession(@RequestBody Session session, HttpServletResponse response) { + public Session postNewSession(@RequestBody Session session, + HttpServletResponse response) { Session newSession = sessionService.saveSession(session); if (session != null) { response.setStatus(HttpStatus.CREATED.value()); @@ -104,22 +111,22 @@ public class SessionController extends AbstractController { return null; } - @RequestMapping(value="/socketurl", method=RequestMethod.GET) + @RequestMapping(value = "/socketurl", method = RequestMethod.GET) @ResponseBody public String getSocketUrl() { StringBuilder url = new StringBuilder(); - + url.append(server.isUseSSL() ? "https://" : "http://"); url.append(server.getHostIp() + ":" + server.getPortNumber()); - + return url.toString(); } - - @RequestMapping(value={"/mySessions","/session/mysessions"}, method=RequestMethod.GET) + + @RequestMapping(value = { "/mySessions", "/session/mysessions" }, method = RequestMethod.GET) @ResponseBody public List<Session> getMySession(HttpServletResponse response) { String username = userService.getCurrentUser().getUsername(); - if(username == null) { + if (username == null) { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } diff --git a/src/main/java/de/thm/arsnova/controller/package-info.java b/src/main/java/de/thm/arsnova/controller/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..ab9a862ae0e0599f236cf9d7d1914a8180be16cd --- /dev/null +++ b/src/main/java/de/thm/arsnova/controller/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.controller; diff --git a/src/main/java/de/thm/arsnova/dao/CouchDBDao.java b/src/main/java/de/thm/arsnova/dao/CouchDBDao.java index 13bf4c74b00376fd89d54e277ab413137f11ddc5..5bbcc0979fc8ba7d94767a364d85a45c3a85ce30 100644 --- a/src/main/java/de/thm/arsnova/dao/CouchDBDao.java +++ b/src/main/java/de/thm/arsnova/dao/CouchDBDao.java @@ -70,21 +70,21 @@ import de.thm.arsnova.services.IUserService; public class CouchDBDao implements IDatabaseDao { @Autowired IUserService userService; - + @Autowired IFeedbackService feedbackService; - + @Autowired ISessionService sessionService; - + private String databaseHost; private int databasePort; private String databaseName; - + private Database database; - + // - + public static final Logger logger = LoggerFactory.getLogger(CouchDBDao.class); @Value("${couchdb.host}") @@ -92,19 +92,19 @@ public class CouchDBDao implements IDatabaseDao { logger.info(databaseHost); this.databaseHost = databaseHost; } - + @Value("${couchdb.port}") public final void setDatabasePort(String databasePort) { logger.info(databasePort); this.databasePort = Integer.parseInt(databasePort); } - + @Value("${couchdb.name}") public final void setDatabaseName(String databaseName) { logger.info(databaseName); this.databaseName = databaseName; } - + /** * This method cleans up old feedback votes at the scheduled interval. */ @@ -112,10 +112,10 @@ public class CouchDBDao implements IDatabaseDao { public void cleanFeedbackVotes(int cleanupFeedbackDelay) { final long timelimitInMillis = 60000 * (long) cleanupFeedbackDelay; final long maxAllowedTimeInMillis = System.currentTimeMillis() - timelimitInMillis; - + Map<String, Set<String>> affectedUsers = new HashMap<String, Set<String>>(); Set<String> allAffectedSessions = new HashSet<String>(); - + List<Document> results = findFeedbackForDeletion(maxAllowedTimeInMillis); for (Document d : results) { try { @@ -123,8 +123,9 @@ public class CouchDBDao implements IDatabaseDao { Document feedback = this.getDatabase().getDocument(d.getId()); String arsInternalSessionId = feedback.getString("sessionId"); String user = feedback.getString("user"); - - // Store user and session data for later. We need this to communicate the changes back to the users. + + // Store user and session data for later. We need this to + // communicate the changes back to the users. Set<String> affectedArsSessions = affectedUsers.get(user); if (affectedArsSessions == null) { affectedArsSessions = new HashSet<String>(); @@ -132,21 +133,19 @@ public class CouchDBDao implements IDatabaseDao { affectedArsSessions.add(getSessionKeyword(arsInternalSessionId)); affectedUsers.put(user, affectedArsSessions); allAffectedSessions.addAll(affectedArsSessions); - + this.database.deleteDocument(feedback); logger.debug("Cleaning up Feedback document " + d.getId()); } catch (IOException e) { logger.error("Could not delete Feedback document " + d.getId()); } catch (JSONException e) { - logger.error("Could not delete Feedback document {}, error is: {} ", new Object[] {d.getId(), e}); + logger.error("Could not delete Feedback document {}, error is: {} ", new Object[] { d.getId(), e }); } } if (!results.isEmpty()) { feedbackService.broadcastFeedbackChanges(affectedUsers, allAffectedSessions); } } - - private List<Document> findFeedbackForDeletion(final long maxAllowedTimeInMillis) { View cleanupFeedbackView = new View("understanding/cleanup"); @@ -155,26 +154,20 @@ public class CouchDBDao implements IDatabaseDao { ViewResults feedbackForCleanup = this.getDatabase().view(cleanupFeedbackView); return feedbackForCleanup.getResults(); } - - @Override public Session getSession(String keyword) { Session result = this.getSessionFromKeyword(keyword); - - if(result == null) { + if (result == null) { throw new NotFoundException(); } - if ( - result.isActive() - || result.getCreator().equals(userService.getCurrentUser().getUsername()) - ) { + if (result.isActive() || result.getCreator().equals(userService.getCurrentUser().getUsername())) { return result; } - + throw new ForbiddenException(); } - + @Override public List<Session> getMySessions(String username) { try { @@ -183,7 +176,7 @@ public class CouchDBDao implements IDatabaseDao { view.setEndKey("[" + URLEncoder.encode("\"" + username + "\",{}", "UTF-8") + "]"); ViewResults sessions = this.getDatabase().view(view); - + List<Session> result = new ArrayList<Session>(); for (Document d : sessions.getResults()) { Session session = (Session) JSONObject.toBean(d.getJSONObject().getJSONObject("value"), Session.class); @@ -195,82 +188,81 @@ public class CouchDBDao implements IDatabaseDao { return null; } } - + @Override public List<Question> getSkillQuestions(String sessionKeyword) { Session session = this.getSessionFromKeyword(sessionKeyword); - if (session == null) { - return null; - } - + if (session == null) + throw new NotFoundException(); + try { View view = new View("skill_question/by_session_sorted_by_subject_and_text"); view.setStartKey("[" + URLEncoder.encode("\"" + session.get_id() + "\"", "UTF-8") + "]"); view.setEndKey("[" + URLEncoder.encode("\"" + session.get_id() + "\",{}", "UTF-8") + "]"); - + ViewResults questions = this.getDatabase().view(view); - if(questions == null || questions.isEmpty()) { + if (questions == null || questions.isEmpty()) { return null; } List<Question> result = new ArrayList<Question>(); - + MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry(); Morpher dynaMorpher = new BeanMorpher(PossibleAnswer.class, morpherRegistry); morpherRegistry.registerMorpher(dynaMorpher); for (Document d : questions.getResults()) { Question q = (Question) JSONObject.toBean(d.getJSONObject().getJSONObject("value"), Question.class); - Collection<PossibleAnswer> answers = JSONArray.toCollection(d.getJSONObject().getJSONObject("value").getJSONArray("possibleAnswers"), PossibleAnswer.class); + Collection<PossibleAnswer> answers = JSONArray.toCollection(d.getJSONObject().getJSONObject("value") + .getJSONArray("possibleAnswers"), PossibleAnswer.class); q.setPossibleAnswers(new ArrayList<PossibleAnswer>(answers)); result.add(q); } - + return result; } catch (UnsupportedEncodingException e) { return null; } } - + @Override public int getSkillQuestionCount(String sessionkey) { try { View view = new View("skill_question/count_by_session"); view.setKey(URLEncoder.encode("\"" + sessionkey + "\"", "UTF-8")); ViewResults results = this.getDatabase().view(view); - + if (results.getJSONArray("rows").optJSONObject(0) == null) { return 0; } - + return results.getJSONArray("rows").optJSONObject(0).optInt("value"); - + } catch (UnsupportedEncodingException e) { return 0; } } - + @Override public Session getSessionFromKeyword(String keyword) { try { View view = new View("session/by_keyword"); view.setKey(URLEncoder.encode("\"" + keyword + "\"", "UTF-8")); ViewResults results = this.getDatabase().view(view); - - if (results.getJSONArray("rows").optJSONObject(0) == null) { + + if (results.getJSONArray("rows").optJSONObject(0) == null) return null; - } - - return (Session) JSONObject.toBean( - results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"), Session.class); + + return (Session) JSONObject.toBean(results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"), + Session.class); } catch (UnsupportedEncodingException e) { return null; } } - + @Override public Session saveSession(Session session) { - + Document sessionDocument = new Document(); - sessionDocument.put("type","session"); + sessionDocument.put("type", "session"); sessionDocument.put("name", session.getName()); sessionDocument.put("shortName", session.getShortName()); sessionDocument.put("keyword", sessionService.generateKeyword()); @@ -281,16 +273,15 @@ public class CouchDBDao implements IDatabaseDao { } catch (IOException e) { return null; } - + return this.getSession(sessionDocument.getString("keyword")); } @Override public Feedback getFeedback(String keyword) { String sessionId = this.getSessionId(keyword); - if (sessionId == null) throw new NotFoundException(); - - logger.info("Time: {}", this.currentTimestamp()); + if (sessionId == null) + throw new NotFoundException(); View view = new View("understanding/by_session"); view.setGroup(true); @@ -300,52 +291,46 @@ public class CouchDBDao implements IDatabaseDao { logger.info("Feedback: {}", results.getJSONArray("rows")); + return this.createFeedbackObject(results); + } + + private Feedback createFeedbackObject(ViewResults results) { int values[] = { 0, 0, 0, 0 }; - + JSONArray rows = results.getJSONArray("rows"); + try { for (int i = 0; i <= 3; i++) { - String key = results.getJSONArray("rows").optJSONObject(i) - .optJSONArray("key").getString(1); + String key = rows.optJSONObject(i).optJSONArray("key").getString(1); + JSONObject feedback = rows.optJSONObject(i); + if (key.equals("Bitte schneller")) - values[0] = results.getJSONArray("rows").optJSONObject(i) - .getInt("value"); + values[0] = feedback.getInt("value"); if (key.equals("Kann folgen")) - values[1] = results.getJSONArray("rows").optJSONObject(i) - .getInt("value"); + values[1] = feedback.getInt("value"); if (key.equals("Zu schnell")) - values[2] = results.getJSONArray("rows").optJSONObject(i) - .getInt("value"); + values[2] = feedback.getInt("value"); if (key.equals("Nicht mehr dabei")) - values[3] = results.getJSONArray("rows").optJSONObject(i) - .getInt("value"); + values[3] = feedback.getInt("value"); } } catch (Exception e) { - return new Feedback( - values[0], - values[1], - values[2], - values[3] - ); + return new Feedback(values[0], values[1], values[2], values[3]); } - - return new Feedback( - values[0], - values[1], - values[2], - values[3] - ); + return new Feedback(values[0], values[1], values[2], values[3]); } @Override public boolean saveFeedback(String keyword, int value, de.thm.arsnova.entities.User user) { String sessionId = this.getSessionId(keyword); - if (sessionId == null) return false; - if (!(value >= 0 && value <= 3)) return false; - + if (sessionId == null) + return false; + if (!(value >= 0 && value <= 3)) + return false; + Document feedback = new Document(); List<Document> postedFeedback = findPreviousFeedback(sessionId, user); - - // Feedback can only be posted once. If there already is some feedback, we need to update it. + + // Feedback can only be posted once. If there already is some feedback, + // we need to update it. if (!postedFeedback.isEmpty()) { for (Document f : postedFeedback) { // Use the first found feedback and update value and timestamp @@ -365,51 +350,63 @@ public class CouchDBDao implements IDatabaseDao { feedback.put("timestamp", System.currentTimeMillis()); feedback.put("value", feedbackValueToString(value)); } - + try { this.getDatabase().saveDocument(feedback); } catch (IOException e) { return false; } - + return true; } - + private List<Document> findPreviousFeedback(String sessionId, de.thm.arsnova.entities.User user) { View view = new View("understanding/by_user"); try { view.setKey(URLEncoder.encode("[\"" + sessionId + "\", \"" + user.getUsername() + "\"]", "UTF-8")); - } catch(UnsupportedEncodingException e) { - return Collections.<Document>emptyList(); + } catch (UnsupportedEncodingException e) { + return Collections.<Document> emptyList(); } ViewResults results = this.getDatabase().view(view); return results.getResults(); } - + private String feedbackValueToString(int value) { switch (value) { - case 0: - return "Bitte schneller"; - case 1: - return "Kann folgen"; - case 2: - return "Zu schnell"; - case 3: - return "Nicht mehr dabei"; - default: - return null; + case 0: + return "Bitte schneller"; + case 1: + return "Kann folgen"; + case 2: + return "Zu schnell"; + case 3: + return "Nicht mehr dabei"; + default: + return null; } } + private int feedbackValueFromString(String value) { + if (value.equals("Bitte schneller")) + return 0; + if (value.equals("Kann folgen")) + return 1; + if (value.equals("Zu schnell")) + return 2; + if (value.equals("Nicht mehr dabei")) + return 3; + return Integer.MIN_VALUE; + } + @Override - @Transactional(isolation=Isolation.READ_COMMITTED) + @Transactional(isolation = Isolation.READ_COMMITTED) public boolean sessionKeyAvailable(String keyword) { View view = new View("session/by_keyword"); ViewResults results = this.getDatabase().view(view); - - return ! results.containsKey(keyword); + + return !results.containsKey(keyword); } - + private String getSessionId(String keyword) { View view = new View("session/by_keyword"); view.setKey(URLEncoder.encode("\"" + keyword + "\"")); @@ -418,10 +415,9 @@ public class CouchDBDao implements IDatabaseDao { if (results.getJSONArray("rows").optJSONObject(0) == null) return null; - return results.getJSONArray("rows").optJSONObject(0) - .optJSONObject("value").getString("_id"); + return results.getJSONArray("rows").optJSONObject(0).optJSONObject("value").getString("_id"); } - + private String getSessionKeyword(String internalSessionId) { try { View view = new View("session/by_id"); @@ -442,34 +438,25 @@ public class CouchDBDao implements IDatabaseDao { private String currentTimestamp() { return Long.toString(System.currentTimeMillis()); } - + private String actualUserName() { User user = userService.getCurrentUser(); - if(user == null) return null; + if (user == null) + return null; return user.getUsername(); } private Database getDatabase() { if (database == null) { try { - com.fourspaces.couchdb.Session session = new com.fourspaces.couchdb.Session( - databaseHost, - databasePort - ); - + 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 - ); + logger.error("Cannot connect to CouchDB database '" + databaseName + "' on host '" + databaseHost + + "' using port " + databasePort); } } - + return database; } @@ -482,7 +469,8 @@ public class CouchDBDao implements IDatabaseDao { q.put("subject", question.getSubject()); q.put("text", question.getText()); q.put("active", question.isActive()); - q.put("number", 0); // TODO: This number has to get incremented automatically + q.put("number", 0); // TODO: This number has to get incremented + // automatically q.put("releasedFor", question.getReleasedFor()); q.put("possibleAnswers", question.getPossibleAnswers()); q.put("noCorrect", question.isNoCorrect()); @@ -493,8 +481,7 @@ public class CouchDBDao implements IDatabaseDao { } return false; } - - + @Override public Question getQuestion(String id, String sessionKey) { Session s = this.getSessionFromKeyword(sessionKey); @@ -505,7 +492,7 @@ public class CouchDBDao implements IDatabaseDao { View view = new View("skill_question/by_id"); view.setKey(URLEncoder.encode("\"" + id + "\"", "UTF-8")); ViewResults results = this.getDatabase().view(view); - + if (results.getJSONArray("rows").optJSONObject(0) == null) { return null; } @@ -525,40 +512,44 @@ public class CouchDBDao implements IDatabaseDao { } return null; } - + @Override public LoggedIn registerAsOnlineUser(User u, Session s) { try { View view = new View("logged_in/all"); view.setKey(URLEncoder.encode("\"" + u.getUsername() + "\"", "UTF-8")); ViewResults results = this.getDatabase().view(view); - + LoggedIn loggedIn = new LoggedIn(); if (results.getJSONArray("rows").optJSONObject(0) != null) { JSONObject json = results.getJSONArray("rows").optJSONObject(0).optJSONObject("value"); loggedIn = (LoggedIn) JSONObject.toBean(json, LoggedIn.class); - Collection<VisitedSession> visitedSessions = JSONArray.toCollection(json.getJSONArray("visitedSessions"), VisitedSession.class); + Collection<VisitedSession> visitedSessions = JSONArray.toCollection( + json.getJSONArray("visitedSessions"), VisitedSession.class); loggedIn.setVisitedSessions(new ArrayList<VisitedSession>(visitedSessions)); } - + loggedIn.setUser(u.getUsername()); loggedIn.setSessionId(s.get_id()); loggedIn.addVisitedSession(s); loggedIn.updateTimestamp(); - + JSONObject json = JSONObject.fromObject(loggedIn); Document doc = new Document(json); if (doc.getId().isEmpty()) { - // If this is a new user without a logged_in document, we have to remove the following - // pre-filled fields. Otherwise, CouchDB will take these empty fields as genuine + // If this is a new user without a logged_in document, we have + // to remove the following + // pre-filled fields. Otherwise, CouchDB will take these empty + // fields as genuine // identifiers, and will throw errors afterwards. doc.remove("_id"); doc.remove("_rev"); } this.getDatabase().saveDocument(doc); - + LoggedIn l = (LoggedIn) JSONObject.toBean(doc.getJSONObject(), LoggedIn.class); - Collection<VisitedSession> visitedSessions = JSONArray.toCollection(doc.getJSONObject().getJSONArray("visitedSessions"), VisitedSession.class); + Collection<VisitedSession> visitedSessions = JSONArray.toCollection( + doc.getJSONObject().getJSONArray("visitedSessions"), VisitedSession.class); l.setVisitedSessions(new ArrayList<VisitedSession>(visitedSessions)); return l; } catch (UnsupportedEncodingException e) { @@ -579,7 +570,30 @@ public class CouchDBDao implements IDatabaseDao { return; } } - + + @Override + public Integer getMyFeedback(String keyword, User user) { + try { + String sessionId = this.getSessionId(keyword); + if (sessionId == null) + throw new NotFoundException(); + + View view = new View("understanding/by_user"); + view.setKey(URLEncoder.encode("[\"" + sessionId + "\", \"" + user.getUsername() + "\"]", "UTF-8")); + ViewResults results = this.getDatabase().view(view); + JSONArray rows = results.getJSONArray("rows"); + + if (rows.size() == 0) { + return null; + } + + JSONObject json = rows.optJSONObject(0).optJSONObject("value"); + return this.feedbackValueFromString(json.getString("value")); + } catch (UnsupportedEncodingException e) { + return null; + } + } + @Override public List<String> getQuestionIds(String sessionKey) { User u = userService.getCurrentUser(); diff --git a/src/main/java/de/thm/arsnova/dao/IDatabaseDao.java b/src/main/java/de/thm/arsnova/dao/IDatabaseDao.java index 63a357f4eac8950263b538ee84d29c85082f3985..db570db75c8d3e901610d23ff9fe5f1e7ce45179 100644 --- a/src/main/java/de/thm/arsnova/dao/IDatabaseDao.java +++ b/src/main/java/de/thm/arsnova/dao/IDatabaseDao.java @@ -22,29 +22,46 @@ package de.thm.arsnova.dao; import java.util.List; import de.thm.arsnova.entities.Feedback; -import de.thm.arsnova.entities.LoggedIn; import de.thm.arsnova.entities.Question; +import de.thm.arsnova.entities.LoggedIn; import de.thm.arsnova.entities.Session; import de.thm.arsnova.entities.User; public interface IDatabaseDao { public void cleanFeedbackVotes(int cleanupFeedbackDelay); + public Session getSessionFromKeyword(String keyword); + public Session getSession(String keyword); + public List<Session> getMySessions(String username); + public Session saveSession(Session session); + public Feedback getFeedback(String keyword); + public boolean saveFeedback(String keyword, int value, User user); + public boolean sessionKeyAvailable(String keyword); - + public boolean saveQuestion(Session session, Question question); + public Question getQuestion(String id, String sessionKey); + List<Question> getSkillQuestions(String session); + public int getSkillQuestionCount(String sessionkey); - + public LoggedIn registerAsOnlineUser(User u, Session s); + public void updateSessionOwnerActivity(Session session); + + public Integer getMyFeedback(String keyword, User user); + public List<String> getQuestionIds(String sessionKey); + public void deleteQuestion(String sessionKey, String questionId); + public List<String> getUnAnsweredQuestions(String sessionKey); + } \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/dao/package-info.java b/src/main/java/de/thm/arsnova/dao/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..2dcb75c6de8888c22d56f9433c54afca46d27c21 --- /dev/null +++ b/src/main/java/de/thm/arsnova/dao/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.dao; \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/entities/Authorize.java b/src/main/java/de/thm/arsnova/entities/Authorize.java index 170c7cd95af9bb9565d5b43c92fe71b7557bc7ef..a19d5bb082b8da306367de7d04c5a74c4d32e76e 100644 --- a/src/main/java/de/thm/arsnova/entities/Authorize.java +++ b/src/main/java/de/thm/arsnova/entities/Authorize.java @@ -3,22 +3,26 @@ package de.thm.arsnova.entities; public class Authorize { private String user; private String socketid; + public String getUser() { return user; } + public void setUser(String user) { this.user = user; } + public String getSocketid() { return socketid; } + public void setSocketid(String socketid) { this.socketid = socketid; } - + @Override public String toString() { return "user: " + user + ", socketid: " + socketid; - + } } diff --git a/src/main/java/de/thm/arsnova/entities/Feedback.java b/src/main/java/de/thm/arsnova/entities/Feedback.java index 46870c33c968c5099357c1fa8336165e9886b586..32a75632077ff60d80b262ded8233e849dbe31ca 100644 --- a/src/main/java/de/thm/arsnova/entities/Feedback.java +++ b/src/main/java/de/thm/arsnova/entities/Feedback.java @@ -5,7 +5,7 @@ import java.util.List; public class Feedback { private List<Integer> values; - + public Feedback(int a, int b, int c, int d) { values = new ArrayList<Integer>(); values.add(a); @@ -13,7 +13,7 @@ public class Feedback { values.add(c); values.add(d); } - + public List<Integer> getValues() { return values; } diff --git a/src/main/java/de/thm/arsnova/entities/LoggedIn.java b/src/main/java/de/thm/arsnova/entities/LoggedIn.java index dcea1ce4339ccb4963ed40af005f3df67582ad1c..d37decdb4d2ae44dd2dafbfa36cd0a390bc02a90 100644 --- a/src/main/java/de/thm/arsnova/entities/LoggedIn.java +++ b/src/main/java/de/thm/arsnova/entities/LoggedIn.java @@ -23,7 +23,7 @@ import java.util.ArrayList; import java.util.List; public class LoggedIn { - + private String _id; private String _rev; private String type; @@ -31,18 +31,18 @@ public class LoggedIn { private String sessionId; private long timestamp; private List<VisitedSession> visitedSessions = new ArrayList<VisitedSession>(); - + public LoggedIn() { this.type = "logged_in"; this.updateTimestamp(); } - + public void addVisitedSession(Session s) { if (!isAlreadyVisited(s)) { this.visitedSessions.add(new VisitedSession(s)); } } - + private boolean isAlreadyVisited(Session s) { for (VisitedSession vs : this.visitedSessions) { if (vs.get_id().equals(s.get_id())) { @@ -51,7 +51,7 @@ public class LoggedIn { } return false; } - + public void updateTimestamp() { this.timestamp = System.currentTimeMillis(); } diff --git a/src/main/java/de/thm/arsnova/entities/PossibleAnswer.java b/src/main/java/de/thm/arsnova/entities/PossibleAnswer.java index e02dc30ab3b0610e2e9b71f1129525f5e17051f4..e81f3c56d6050479c5ce20810707eab3c5107dd5 100644 --- a/src/main/java/de/thm/arsnova/entities/PossibleAnswer.java +++ b/src/main/java/de/thm/arsnova/entities/PossibleAnswer.java @@ -22,19 +22,19 @@ public class PossibleAnswer { private String text; private boolean correct; - + public String getText() { return text; } - + public void setText(String text) { this.text = text; } - + public boolean isCorrect() { return correct; } - + public void setCorrect(boolean correct) { this.correct = correct; } diff --git a/src/main/java/de/thm/arsnova/entities/Question.java b/src/main/java/de/thm/arsnova/entities/Question.java index 0ed8fadb5756b02591aae308c53da05be15b4631..afb100bd20beb1063caafe86ab7d78eb9806ee7d 100644 --- a/src/main/java/de/thm/arsnova/entities/Question.java +++ b/src/main/java/de/thm/arsnova/entities/Question.java @@ -31,13 +31,12 @@ public class Question { private List<PossibleAnswer> possibleAnswers; private boolean noCorrect; private String session; - - private int number; + + private int number; private int duration; private String _id; private String _rev; - - + public String getType() { return type; } @@ -45,7 +44,7 @@ public class Question { public void setType(String type) { this.type = type; } - + public String getQuestionType() { return questionType; } @@ -101,7 +100,7 @@ public class Question { public void setNoCorrect(boolean noCorrect) { this.noCorrect = noCorrect; } - + public String getSessionId() { return session; } @@ -109,7 +108,7 @@ public class Question { public void setSessionId(String session) { this.session = session; } - + public String getSession() { return session; } @@ -152,7 +151,7 @@ public class Question { @Override public String toString() { - return "Question type '" + this.questionType + "': " + this.subject + ", session: " + session + ";\n" + this.text + + return "Question type '" + this.questionType + "': " + this.subject + ";\n" + this.text + this.possibleAnswers; } } diff --git a/src/main/java/de/thm/arsnova/entities/Session.java b/src/main/java/de/thm/arsnova/entities/Session.java index 06c46c23bc643d57901fbe977a27bcdd59ef24b4..2d7eefd915bf8bdb96af2a598bf2fff4c2a437e4 100644 --- a/src/main/java/de/thm/arsnova/entities/Session.java +++ b/src/main/java/de/thm/arsnova/entities/Session.java @@ -18,9 +18,8 @@ */ package de.thm.arsnova.entities; - public class Session { - + private String type; private String name; private String shortName; @@ -30,59 +29,75 @@ public class Session { private long lastOwnerActivity; private String _id; private String _rev; - + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getShortName() { return shortName; } + public void setShortName(String shortName) { this.shortName = shortName; } + public String getKeyword() { return keyword; } + public void setKeyword(String keyword) { this.keyword = keyword; } + public String getCreator() { return creator; } + public void setCreator(String creator) { this.creator = creator; } + public boolean isActive() { return active; } + public void setActive(boolean active) { this.active = active; } - + public long getLastOwnerActivity() { return lastOwnerActivity; } + public void setLastOwnerActivity(long lastOwnerActivity) { this.lastOwnerActivity = lastOwnerActivity; } + public void set_id(String id) { _id = id; } + public String get_id() { return _id; } + public void set_rev(String rev) { _rev = rev; } + public String get_rev() { return _rev; } diff --git a/src/main/java/de/thm/arsnova/entities/User.java b/src/main/java/de/thm/arsnova/entities/User.java index adc8c14507daa5d9e0e0cd1e7a0de22b5891ae62..61e97598ac5053b35117c01bf18248f245b8a414 100644 --- a/src/main/java/de/thm/arsnova/entities/User.java +++ b/src/main/java/de/thm/arsnova/entities/User.java @@ -63,14 +63,16 @@ public class User implements Serializable { public String toString() { return "User, username: " + this.username + ", type: " + this.type; } + @Override public int hashCode() { - return username.concat(type).hashCode(); + return username.hashCode(); } - + @Override public boolean equals(Object obj) { - if (obj == null || ! obj.getClass().equals(this.getClass())) return false; + if (obj == null || !obj.getClass().equals(this.getClass())) + return false; User other = (User) obj; return this.username.equals(other.username) && this.type.equals(other.type); } diff --git a/src/main/java/de/thm/arsnova/entities/VisitedSession.java b/src/main/java/de/thm/arsnova/entities/VisitedSession.java index 50cb8819917b52d405653c3ffc73999275e9d54d..a6e28dd729b0f09c10d8e662881996496e915f6a 100644 --- a/src/main/java/de/thm/arsnova/entities/VisitedSession.java +++ b/src/main/java/de/thm/arsnova/entities/VisitedSession.java @@ -19,45 +19,46 @@ package de.thm.arsnova.entities; public class VisitedSession { - private String _id; - private String name; - private String keyword; - - public VisitedSession() {} - - public VisitedSession(Session s) { - this._id = s.get_id(); - this.name = s.getName(); - this.keyword = s.getKeyword(); - } - - public String get_id() { - return _id; - } - - public void set_id(String _id) { - this._id = _id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getKeyword() { - return keyword; - } - - public void setKeyword(String keyword) { - this.keyword = keyword; - } - - @Override - public String toString() { - return "VisitedSession [_id=" + _id + ", name=" + name - + ", keyword=" + keyword + "]"; - } - } \ No newline at end of file + private String _id; + private String name; + private String keyword; + + public VisitedSession() { + } + + public VisitedSession(Session s) { + this._id = s.get_id(); + this.name = s.getName(); + this.keyword = s.getKeyword(); + } + + public String get_id() { + return _id; + } + + public void set_id(String _id) { + this._id = _id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getKeyword() { + return keyword; + } + + public void setKeyword(String keyword) { + this.keyword = keyword; + } + + @Override + public String toString() { + return "VisitedSession [_id=" + _id + ", name=" + name + ", keyword=" + + keyword + "]"; + } +} \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/entities/package-info.java b/src/main/java/de/thm/arsnova/entities/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..f9851140e3cf9defa396590125430bd8aafed134 --- /dev/null +++ b/src/main/java/de/thm/arsnova/entities/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.entities; \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/exceptions/NoContentException.java b/src/main/java/de/thm/arsnova/exceptions/NoContentException.java new file mode 100644 index 0000000000000000000000000000000000000000..adb0e1140eec966d08b85592ca88fc962cb0b84a --- /dev/null +++ b/src/main/java/de/thm/arsnova/exceptions/NoContentException.java @@ -0,0 +1,5 @@ +package de.thm.arsnova.exceptions; + +public class NoContentException extends RuntimeException { + private static final long serialVersionUID = 1L; +} diff --git a/src/main/java/de/thm/arsnova/exceptions/package-info.java b/src/main/java/de/thm/arsnova/exceptions/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..609e116927c642cf07c14b696d6d15ba5a924610 --- /dev/null +++ b/src/main/java/de/thm/arsnova/exceptions/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.exceptions; \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/package-info.java b/src/main/java/de/thm/arsnova/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..30e6d4288f971f6b719cbd1e18001c351ef68566 --- /dev/null +++ b/src/main/java/de/thm/arsnova/package-info.java @@ -0,0 +1,2 @@ +package de.thm.arsnova; + diff --git a/src/main/java/de/thm/arsnova/services/FeedbackService.java b/src/main/java/de/thm/arsnova/services/FeedbackService.java index 2b4e7f728b5c36d87b9d9b7d8e8587819a9f708f..21e8d39cca30d2b85170c775b85902407b13743e 100644 --- a/src/main/java/de/thm/arsnova/services/FeedbackService.java +++ b/src/main/java/de/thm/arsnova/services/FeedbackService.java @@ -28,10 +28,10 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import de.thm.arsnova.annotation.Authenticated; import de.thm.arsnova.dao.IDatabaseDao; import de.thm.arsnova.entities.Feedback; import de.thm.arsnova.entities.User; +import de.thm.arsnova.exceptions.NoContentException; import de.thm.arsnova.socket.ARSnovaSocketIOServer; @Service @@ -39,37 +39,35 @@ public class FeedbackService implements IFeedbackService { @Autowired ARSnovaSocketIOServer server; - + /** * minutes, after which the feedback is deleted */ @Value("${feedback.cleanup}") private int cleanupFeedbackDelay; - + @Autowired IDatabaseDao databaseDao; - + @Autowired IUserService userService; - + public void setDatabaseDao(IDatabaseDao databaseDao) { this.databaseDao = databaseDao; } - + @Override - @Scheduled(fixedDelay=5000) + @Scheduled(fixedDelay = 5000) public void cleanFeedbackVotes() { - databaseDao.cleanFeedbackVotes(cleanupFeedbackDelay); + databaseDao.cleanFeedbackVotes(cleanupFeedbackDelay); } @Override - @Authenticated public Feedback getFeedback(String keyword) { return databaseDao.getFeedback(keyword); } - + @Override - @Authenticated public int getFeedbackCount(String keyword) { Feedback feedback = databaseDao.getFeedback(keyword); List<Integer> values = feedback.getValues(); @@ -77,28 +75,38 @@ public class FeedbackService implements IFeedbackService { } @Override - @Authenticated - public long getAverageFeedback(String sessionkey) { + public double getAverageFeedback(String sessionkey) { Feedback feedback = databaseDao.getFeedback(sessionkey); List<Integer> values = feedback.getValues(); - int count = values.get(0) + values.get(1) + values.get(2) + values.get(3); - int sum = values.get(1) + (values.get(2) * 2) + (values.get(3) * 3); + double count = values.get(0) + values.get(1) + values.get(2) + values.get(3); + double sum = values.get(1) + (values.get(2) * 2) + (values.get(3) * 3); + + if (count == 0) + throw new NoContentException(); + return sum / count; } - + + @Override + public long getAverageFeedbackRounded(String sessionkey) { + return Math.round(this.getAverageFeedback(sessionkey)); + } + @Override - @Authenticated public boolean saveFeedback(String keyword, int value, User user) { return databaseDao.saveFeedback(keyword, value, user); } /** * - * @param affectedUsers The user whose feedback got deleted along with all affected session keywords - * @param allAffectedSessions For convenience, this represents the union of all session keywords mentioned above. + * @param affectedUsers + * The user whose feedback got deleted along with all affected + * session keywords + * @param allAffectedSessions + * For convenience, this represents the union of all session + * keywords mentioned above. */ @Override - @Authenticated public void broadcastFeedbackChanges(Map<String, Set<String>> affectedUsers, Set<String> allAffectedSessions) { for (Map.Entry<String, Set<String>> e : affectedUsers.entrySet()) { // Is this user registered with a socket connection? @@ -109,4 +117,9 @@ public class FeedbackService implements IFeedbackService { } this.server.reportUpdatedFeedbackForSessions(allAffectedSessions); } + + @Override + public Integer getMyFeedback(String keyword, User user) { + return this.databaseDao.getMyFeedback(keyword, user); + } } diff --git a/src/main/java/de/thm/arsnova/services/IFeedbackService.java b/src/main/java/de/thm/arsnova/services/IFeedbackService.java index bacfb70f7fdfdf24f2a94b9ba672511a40796e3d..fa19d233e6f04bfffa2061f4551e7ac6a83c1f10 100644 --- a/src/main/java/de/thm/arsnova/services/IFeedbackService.java +++ b/src/main/java/de/thm/arsnova/services/IFeedbackService.java @@ -25,12 +25,22 @@ import java.util.Set; import de.thm.arsnova.entities.Feedback; import de.thm.arsnova.entities.User; - public interface IFeedbackService { public void cleanFeedbackVotes(); + public Feedback getFeedback(String keyword); + public int getFeedbackCount(String keyword); - public long getAverageFeedback(String sessionkey); + + public double getAverageFeedback(String sessionkey); + + public long getAverageFeedbackRounded(String sessionkey); + public boolean saveFeedback(String keyword, int value, User user); - public void broadcastFeedbackChanges(Map<String, Set<String>> affectedUsers, Set<String> allAffectedSessions); + + public void broadcastFeedbackChanges( + Map<String, Set<String>> affectedUsers, + Set<String> allAffectedSessions); + + public Integer getMyFeedback(String keyword, User user); } \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/services/IQuestionService.java b/src/main/java/de/thm/arsnova/services/IQuestionService.java index ee1aa11a96c48e6d11b990d4996ca89d11dd9609..931db1309322ea9e729544b474109f17d9cc45c0 100644 --- a/src/main/java/de/thm/arsnova/services/IQuestionService.java +++ b/src/main/java/de/thm/arsnova/services/IQuestionService.java @@ -23,13 +23,18 @@ import java.util.List; import de.thm.arsnova.entities.Question; - public interface IQuestionService { public boolean saveQuestion(Question question); + public Question getQuestion(String id, String sessionkey); + public List<Question> getSkillQuestions(String sessionkey); + public int getSkillQuestionCount(String sessionkey); + public List<String> getQuestionIds(String sessionKey); + public void deleteQuestion(String sessionKey, String questionId); + public List<String> getUnAnsweredQuestions(String sessionKey); } \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/services/ISessionService.java b/src/main/java/de/thm/arsnova/services/ISessionService.java index e93b70b02b1e3b71f8efa8700efcb9d7f9e35f38..b5327403a308522d5b871a2e5204cf47a855f604 100644 --- a/src/main/java/de/thm/arsnova/services/ISessionService.java +++ b/src/main/java/de/thm/arsnova/services/ISessionService.java @@ -25,12 +25,16 @@ import de.thm.arsnova.entities.LoggedIn; import de.thm.arsnova.entities.Session; import de.thm.arsnova.entities.User; - public interface ISessionService { public Session joinSession(String keyword); + public Session saveSession(Session session); + public boolean sessionKeyAvailable(String keyword); - public String generateKeyword(); + + public String generateKeyword(); + public List<Session> getMySessions(String username); + public LoggedIn registerAsOnlineUser(User user, String sessionkey); } \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/services/IUserService.java b/src/main/java/de/thm/arsnova/services/IUserService.java index dbec05934a87de614f4342280e8207a885569261..b309dad4a7b95763eae82d406f2a0e9ce4f517ae 100644 --- a/src/main/java/de/thm/arsnova/services/IUserService.java +++ b/src/main/java/de/thm/arsnova/services/IUserService.java @@ -10,14 +10,20 @@ import de.thm.arsnova.exceptions.UnauthorizedException; public interface IUserService { User getCurrentUser() throws UnauthorizedException; - + User getUser2SessionID(UUID sessionID); + void putUser2SessionID(UUID sessionID, User user); + void removeUser2SessionID(UUID sessionID); + Set<Map.Entry<UUID, User>> users2Session(); - + boolean isUserInSession(User user, String keyword); + List<String> getUsersInSession(String keyword); + void addCurrentUserToSessionMap(String keyword); + String getSessionForUser(String username); } diff --git a/src/main/java/de/thm/arsnova/services/QuestionService.java b/src/main/java/de/thm/arsnova/services/QuestionService.java index 279318e3dc69c48ecb3bddb71ea3a4ace068d75c..097b37dc6bc98e925d328d615780d33b15d208cb 100644 --- a/src/main/java/de/thm/arsnova/services/QuestionService.java +++ b/src/main/java/de/thm/arsnova/services/QuestionService.java @@ -28,6 +28,7 @@ import de.thm.arsnova.annotation.Authenticated; import de.thm.arsnova.dao.IDatabaseDao; import de.thm.arsnova.entities.Question; import de.thm.arsnova.entities.Session; +import de.thm.arsnova.exceptions.NoContentException; import de.thm.arsnova.socket.ARSnovaSocketIOServer; @Service @@ -35,34 +36,39 @@ public class QuestionService implements IQuestionService { @Autowired ARSnovaSocketIOServer server; - + @Autowired IDatabaseDao databaseDao; - + @Autowired IUserService userService; - + public void setDatabaseDao(IDatabaseDao databaseDao) { this.databaseDao = databaseDao; } - + @Override + @Authenticated public List<Question> getSkillQuestions(String sessionkey) { - return databaseDao.getSkillQuestions(sessionkey); + List<Question> result = databaseDao.getSkillQuestions(sessionkey); + if (result == null || result.size() == 0) + throw new NoContentException(); + return result; } - + @Override + @Authenticated public int getSkillQuestionCount(String sessionkey) { return databaseDao.getSkillQuestionCount(sessionkey); } - + @Override @Authenticated public boolean saveQuestion(Question question) { Session session = this.databaseDao.getSessionFromKeyword(question.getSession()); return this.databaseDao.saveQuestion(session, question); } - + @Override @Authenticated public Question getQuestion(String id, String sessionKey) { diff --git a/src/main/java/de/thm/arsnova/services/SessionService.java b/src/main/java/de/thm/arsnova/services/SessionService.java index 1a1ce89f0acc1e687868b9d5a6a593665d22147a..00bb43d1a6a40f068b8bb3bd9e17848647c3d1ab 100644 --- a/src/main/java/de/thm/arsnova/services/SessionService.java +++ b/src/main/java/de/thm/arsnova/services/SessionService.java @@ -38,17 +38,17 @@ public class SessionService implements ISessionService { @Autowired ARSnovaSocketIOServer server; - + @Autowired IDatabaseDao databaseDao; - + @Autowired IUserService userService; - + public void setDatabaseDao(IDatabaseDao databaseDao) { this.databaseDao = databaseDao; } - + @Override @Authenticated public Session joinSession(String keyword) { @@ -60,7 +60,7 @@ public class SessionService implements ISessionService { public List<Session> getMySessions(String username) { return databaseDao.getMySessions(username); } - + @Override @Authenticated public Session saveSession(Session session) { @@ -72,29 +72,15 @@ public class SessionService implements ISessionService { return databaseDao.sessionKeyAvailable(keyword); } - /** - * - * @param affectedUsers The user whose feedback got deleted along with all affected session keywords - * @param allAffectedSessions For convenience, this represents the union of all session keywords mentioned above. - */ - public void broadcastFeedbackChanges(Map<String, Set<String>> affectedUsers, Set<String> allAffectedSessions) { - for (Map.Entry<String, Set<String>> e : affectedUsers.entrySet()) { - // Is this user registered with a socket connection? - String connectedSocket = userService.getSessionForUser(e.getKey()); - if (connectedSocket != null) { - this.server.reportDeletedFeedback(e.getKey(), e.getValue()); - } - } - this.server.reportUpdatedFeedbackForSessions(allAffectedSessions); - } - @Override public String generateKeyword() { final int low = 10000000; final int high = 100000000; - String keyword = String.valueOf((int)(Math.random() * (high - low) + low)); - - if (this.sessionKeyAvailable(keyword)) return keyword; + String keyword = String + .valueOf((int) (Math.random() * (high - low) + low)); + + if (this.sessionKeyAvailable(keyword)) + return keyword; return generateKeyword(); } @@ -102,12 +88,13 @@ public class SessionService implements ISessionService { @Authenticated public LoggedIn registerAsOnlineUser(User user, String sessionkey) { Session session = this.joinSession(sessionkey); - if (session == null) return null; - + if (session == null) + return null; + if (session.getCreator().equals(user.getUsername())) { databaseDao.updateSessionOwnerActivity(session); } - + return databaseDao.registerAsOnlineUser(user, session); } } diff --git a/src/main/java/de/thm/arsnova/services/UserService.java b/src/main/java/de/thm/arsnova/services/UserService.java index 76499556f76d3acc4895897f483ce8d8c9d7db1a..075e85cd3a75d8516db2d4dc8f8d2b88347b5a66 100644 --- a/src/main/java/de/thm/arsnova/services/UserService.java +++ b/src/main/java/de/thm/arsnova/services/UserService.java @@ -36,48 +36,54 @@ import com.github.leleuj.ss.oauth.client.authentication.OAuthAuthenticationToken import de.thm.arsnova.entities.User; import de.thm.arsnova.exceptions.UnauthorizedException; -public class UserService implements IUserService, InitializingBean, DisposableBean { +public class UserService implements IUserService, InitializingBean, + DisposableBean { + + public static final Logger logger = LoggerFactory + .getLogger(UserService.class); - public static final Logger logger = LoggerFactory.getLogger(UserService.class); - private static final ConcurrentHashMap<UUID, User> socketid2user = new ConcurrentHashMap<UUID, User>(); private static final ConcurrentHashMap<String, String> user2session = new ConcurrentHashMap<String, String>(); - - + @Override public User getCurrentUser() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + Authentication authentication = SecurityContextHolder.getContext() + .getAuthentication(); if (authentication == null || authentication.getPrincipal() == null) { return null; } User user = null; - - if(authentication instanceof OAuthAuthenticationToken) { + + if (authentication instanceof OAuthAuthenticationToken) { OAuthAuthenticationToken token = (OAuthAuthenticationToken) authentication; - if(token.getUserProfile() instanceof Google2Profile) { - Google2Profile profile = (Google2Profile) token.getUserProfile(); + 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(); + } 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(); + } else if (token.getUserProfile() instanceof FacebookProfile) { + FacebookProfile profile = (FacebookProfile) token + .getUserProfile(); user = new User(profile); } } else if (authentication instanceof CasAuthenticationToken) { CasAuthenticationToken token = (CasAuthenticationToken) authentication; user = new User(token.getAssertion().getPrincipal()); - } else if(authentication instanceof AnonymousAuthenticationToken){ + } else if (authentication instanceof AnonymousAuthenticationToken) { AnonymousAuthenticationToken token = (AnonymousAuthenticationToken) authentication; user = new User(token); - } else if(authentication instanceof UsernamePasswordAuthenticationToken) { + } else if (authentication instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; user = new User(token); } - - if (user == null || user.getUsername().equals("anonymous")) throw new UnauthorizedException(); - + + if (user == null || user.getUsername().equals("anonymous")) + throw new UnauthorizedException(); + return user; } @@ -88,7 +94,7 @@ public class UserService implements IUserService, InitializingBean, DisposableBe @Override public void putUser2SessionID(UUID sessionID, User user) { - socketid2user.put(sessionID, user); + socketid2user.put(sessionID, user); } @Override @@ -100,34 +106,37 @@ public class UserService implements IUserService, InitializingBean, DisposableBe public void removeUser2SessionID(UUID sessionID) { socketid2user.remove(sessionID); } - + @Override public boolean isUserInSession(User user, String keyword) { - if (keyword == null) return false; + if (keyword == null) + return false; String session = user2session.get(user.getUsername()); - if(session == null) return false; + if (session == null) + return false; return keyword.equals(session); } - + @Override public List<String> getUsersInSession(String keyword) { List<String> result = new ArrayList<String>(); - for(Entry<String, String> e : user2session.entrySet()) { - if(e.getValue().equals(keyword)) { + for (Entry<String, String> e : user2session.entrySet()) { + if (e.getValue().equals(keyword)) { result.add(e.getKey()); } } return result; - } - + } + @Override - @Transactional(isolation=Isolation.READ_COMMITTED) + @Transactional(isolation = Isolation.READ_COMMITTED) public void addCurrentUserToSessionMap(String keyword) { User user = getCurrentUser(); - if (user == null) throw new UnauthorizedException(); - user2session.put(user.getUsername(), keyword); + if (user == null) + throw new UnauthorizedException(); + user2session.put(user.getUsername(), keyword); } - + @Override public String getSessionForUser(String username) { return user2session.get(username); @@ -138,40 +147,44 @@ public class UserService implements IUserService, InitializingBean, DisposableBe try { File tmpDir = new File(System.getProperty("java.io.tmpdir")); File store = new File(tmpDir, "arsnova.bin"); - if(!store.exists()) { + if (!store.exists()) { return; } - ObjectInputStream ois = new ObjectInputStream(new FileInputStream(store)); - Hashtable<String, Map<?, ?>> map = (Hashtable<String, Map<?, ?>>) ois.readObject(); + ObjectInputStream ois = new ObjectInputStream(new FileInputStream( + store)); + Hashtable<String, Map<?, ?>> map = (Hashtable<String, Map<?, ?>>) ois + .readObject(); ois.close(); Map<UUID, User> s2u = (Map<UUID, User>) map.get("socketid2user"); - Map<String, String> u2s = (Map<String, String>) map.get("user2session"); - + Map<String, String> u2s = (Map<String, String>) map + .get("user2session"); + logger.info("load from store: {}", map); - + socketid2user.putAll(s2u); user2session.putAll(u2s); - + } catch (IOException e) { logger.error("IOException during restoring UserService", e); } catch (ClassNotFoundException e) { - logger.error("ClassNotFoundException during restoring UserService", e); + logger.error("ClassNotFoundException during restoring UserService", + e); } } - + @Override public void destroy() { Hashtable<String, Map<?, ?>> map = new Hashtable<String, Map<?, ?>>(); map.put("socketid2user", socketid2user); map.put("user2session", user2session); - + try { File tmpDir = new File(System.getProperty("java.io.tmpdir")); File store = new File(tmpDir, "arsnova.bin"); - if(!store.exists()) { + if (!store.exists()) { store.createNewFile(); } - OutputStream file = new FileOutputStream (store); + OutputStream file = new FileOutputStream(store); ObjectOutputStream objOut = new ObjectOutputStream(file); objOut.writeObject(map); objOut.close(); diff --git a/src/main/java/de/thm/arsnova/services/package-info.java b/src/main/java/de/thm/arsnova/services/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..12742b6cbbe5149e7ac1dd84c4ca49e7f6a6efc6 --- /dev/null +++ b/src/main/java/de/thm/arsnova/services/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.services; \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java b/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java index f0a99ec58171e54d601e01dcf2285dc20f024280..2b23b251cbf808e86ed8d1d50983f1cb99a59d2c 100644 --- a/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java +++ b/src/main/java/de/thm/arsnova/socket/ARSnovaSocketIOServer.java @@ -33,15 +33,15 @@ public class ARSnovaSocketIOServer { @Autowired private IFeedbackService feedbackService; - + @Autowired private IQuestionService questionService; - + @Autowired private IUserService userService; - + private final Logger logger = LoggerFactory.getLogger(getClass()); - + private int portNumber; private String hostIp; private boolean useSSL = false; @@ -49,7 +49,7 @@ public class ARSnovaSocketIOServer { private String storepass; private final Configuration config; private SocketIOServer server; - + public ARSnovaSocketIOServer() { config = new Configuration(); } @@ -58,16 +58,16 @@ public class ARSnovaSocketIOServer { /** * hack: listen to ipv4 adresses */ - System.setProperty("java.net.preferIPv4Stack" , "true"); - + System.setProperty("java.net.preferIPv4Stack", "true"); + config.setPort(portNumber); config.setHostname(hostIp); - if(useSSL) { + if (useSSL) { try { InputStream stream = new FileInputStream(keystore); config.setKeyStore(stream); config.setKeyStorePassword(storepass); - } catch(FileNotFoundException e) { + } catch (FileNotFoundException e) { logger.error("Keystore {} not found on filesystem", keystore); } } @@ -76,64 +76,76 @@ public class ARSnovaSocketIOServer { server.addEventListener("setFeedback", Feedback.class, new DataListener<Feedback>() { @Override - public void onData(SocketIOClient client, Feedback data, AckRequest ackSender) { + public void onData(SocketIOClient client, Feedback data, + AckRequest ackSender) { /** - * do a check if user is in the session, for which he would give a feedback + * do a check if user is in the session, for which he + * would give a feedback */ - User u = userService.getUser2SessionID(client.getSessionId()); - if(u == null || userService.isUserInSession(u, data.getSessionkey()) == false) { + User u = userService.getUser2SessionID(client + .getSessionId()); + if (u == null + || userService.isUserInSession(u, + data.getSessionkey()) == false) { return; } - feedbackService.saveFeedback(data.getSessionkey(), data.getValue(), u); - + feedbackService.saveFeedback(data.getSessionkey(), + data.getValue(), u); + /** - * collect a list of users which are in the current session - * iterate over all connected clients and if send feedback, - * if user is in current session + * collect a list of users which are in the current + * session iterate over all connected clients and if + * send feedback, if user is in current session */ - List<String> users = userService.getUsersInSession(data.getSessionkey()); - de.thm.arsnova.entities.Feedback fb = feedbackService.getFeedback(data.getSessionkey()); - - for(SocketIOClient c : server.getAllClients()) { + List<String> users = userService.getUsersInSession(data + .getSessionkey()); + de.thm.arsnova.entities.Feedback fb = feedbackService + .getFeedback(data.getSessionkey()); + + for (SocketIOClient c : server.getAllClients()) { u = userService.getUser2SessionID(c.getSessionId()); - if(u != null && users.contains(u.getUsername())) { + if (u != null && users.contains(u.getUsername())) { c.sendEvent("updateFeedback", fb.getValues()); } } } - }); - - server.addEventListener("arsnova/question/create", Question.class, new DataListener<Question>(){ + }); + + server.addEventListener("arsnova/question/create", Question.class, + new DataListener<Question>() { + @Override + public void onData(SocketIOClient client, + Question question, AckRequest ackSender) { + questionService.saveQuestion(question); + } + }); + + server.addConnectListener(new ConnectListener() { @Override - public void onData(SocketIOClient client, Question question, AckRequest ackSender) { - questionService.saveQuestion(question); + public void onConnect(SocketIOClient client) { + logger.info("addConnectListener.onConnect: Client: {}", + new Object[] { client }); } }); - - server.addConnectListener(new ConnectListener() { - @Override - public void onConnect(SocketIOClient client) { - logger.info("addConnectListener.onConnect: Client: {}", new Object[] {client}); - } - }); - + server.addDisconnectListener(new DisconnectListener() { - @Override - public void onDisconnect(SocketIOClient client) { - logger.info("addDisconnectListener.onDisconnect: Client: {}", new Object[] {client}); - userService.removeUser2SessionID(client.getSessionId()); - } - }); - + @Override + public void onDisconnect(SocketIOClient client) { + logger.info("addDisconnectListener.onDisconnect: Client: {}", + new Object[] { client }); + userService.removeUser2SessionID(client.getSessionId()); + } + }); + server.start(); } public void stopServer() throws Exception { logger.debug("In stopServer method of class: {}", getClass().getName()); - for(SocketIOClient client : server.getAllClients()) { + for (SocketIOClient client : server.getAllClients()) { client.disconnect(); } - server.stop(); + server.stop(); } @@ -153,7 +165,7 @@ public class ARSnovaSocketIOServer { public void setHostIp(String hostIp) { this.hostIp = hostIp; } - + public String getStorepass() { return storepass; } @@ -186,10 +198,11 @@ public class ARSnovaSocketIOServer { if (connectionIds.isEmpty()) { return; } - + for (SocketIOClient client : server.getAllClients()) { - // Find the client whose feedback has been deleted and send a message. - if(connectionIds.contains(client.getSessionId())) { + // Find the client whose feedback has been deleted and send a + // message. + if (connectionIds.contains(client.getSessionId())) { client.sendEvent("removedFeedback", arsSessions); } } @@ -204,12 +217,13 @@ public class ARSnovaSocketIOServer { } return result; } - - + public void reportUpdatedFeedbackForSessions(Set<String> allAffectedSessions) { for (String sessionKey : allAffectedSessions) { - de.thm.arsnova.entities.Feedback fb = feedbackService.getFeedback(sessionKey); - server.getBroadcastOperations().sendEvent("updateFeedback", fb.getValues()); + de.thm.arsnova.entities.Feedback fb = feedbackService + .getFeedback(sessionKey); + server.getBroadcastOperations().sendEvent("updateFeedback", + fb.getValues()); } } } \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/socket/message/Feedback.java b/src/main/java/de/thm/arsnova/socket/message/Feedback.java index 2cf8e666557e0671c76e29d51d3977170705af11..2b5ac907eb38f802347f7b862c0552834631200e 100644 --- a/src/main/java/de/thm/arsnova/socket/message/Feedback.java +++ b/src/main/java/de/thm/arsnova/socket/message/Feedback.java @@ -2,8 +2,8 @@ package de.thm.arsnova.socket.message; public class Feedback { - private int value; - private String sessionkey; + private int value; + private String sessionkey; public String getSessionkey() { return sessionkey; @@ -19,8 +19,8 @@ public class Feedback { public void setValue(int value) { this.value = value; - } - + } + @Override public String toString() { return "Feedback, sessionkey: " + sessionkey + ", value: " + value; diff --git a/src/main/java/de/thm/arsnova/socket/message/package-info.java b/src/main/java/de/thm/arsnova/socket/message/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..b4bdfaaea736f38ab628a9dfffa93bc160842546 --- /dev/null +++ b/src/main/java/de/thm/arsnova/socket/message/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.socket.message; \ No newline at end of file diff --git a/src/main/java/de/thm/arsnova/socket/package-info.java b/src/main/java/de/thm/arsnova/socket/package-info.java new file mode 100644 index 0000000000000000000000000000000000000000..4c7eda994dfccdb9295c34caba2e539147be4dc9 --- /dev/null +++ b/src/main/java/de/thm/arsnova/socket/package-info.java @@ -0,0 +1 @@ +package de.thm.arsnova.socket; \ No newline at end of file diff --git a/src/test/java/de/thm/arsnova/AbstractSpringContextTestBase.java b/src/test/java/de/thm/arsnova/AbstractSpringContextTestBase.java index 651eec913758f622038fa2990d83f2036cf8fa34..02fe1ace237001392fd977f9568d5540099aa99c 100644 --- a/src/test/java/de/thm/arsnova/AbstractSpringContextTestBase.java +++ b/src/test/java/de/thm/arsnova/AbstractSpringContextTestBase.java @@ -38,35 +38,43 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ +@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/arsnova-servlet.xml", "file:src/main/webapp/WEB-INF/spring/spring-main.xml", - "file:src/test/resources/test-config.xml" -}) -public class AbstractSpringContextTestBase extends AbstractJUnit4SpringContextTests { - + "file:src/test/resources/test-config.xml" }) +public class AbstractSpringContextTestBase extends + AbstractJUnit4SpringContextTests { + protected MockHttpServletRequest request; protected MockHttpServletResponse response; - - protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response) - throws Exception { - final HandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class); - final HandlerExecutionChain handler = handlerMapping.getHandler(request); - assertNotNull("No handler found for request, check you request mapping", handler); - final Object controller = handler.getHandler(); - // if you want to override any injected attributes do it here + protected ModelAndView handle(HttpServletRequest request, + HttpServletResponse response) throws Exception { + final HandlerMapping handlerMapping = applicationContext + .getBean(RequestMappingHandlerMapping.class); + final HandlerExecutionChain handler = handlerMapping + .getHandler(request); + assertNotNull( + "No handler found for request, check you request mapping", + handler); + + final Object controller = handler.getHandler(); + // if you want to override any injected attributes do it here - final HandlerInterceptor[] interceptors = - handlerMapping.getHandler(request).getInterceptors(); - for (HandlerInterceptor interceptor : interceptors) { - final boolean carryOn = interceptor.preHandle(request, response, controller); - if (!carryOn) { - return null; - } - } - HandlerAdapter handlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);; - final ModelAndView mav = handlerAdapter.handle(request, response, controller); - return mav; - } + final HandlerInterceptor[] interceptors = handlerMapping.getHandler( + request).getInterceptors(); + for (HandlerInterceptor interceptor : interceptors) { + final boolean carryOn = interceptor.preHandle(request, response, + controller); + if (!carryOn) { + return null; + } + } + HandlerAdapter handlerAdapter = applicationContext + .getBean(RequestMappingHandlerAdapter.class); + ; + final ModelAndView mav = handlerAdapter.handle(request, response, + controller); + return mav; + } } diff --git a/src/test/java/de/thm/arsnova/WiringTest.java b/src/test/java/de/thm/arsnova/WiringTest.java index 06c0c355623259df5512dd00bd26aa587380f2cf..5f8590492afbb957ca1e662bed4636851a8c8f33 100644 --- a/src/test/java/de/thm/arsnova/WiringTest.java +++ b/src/test/java/de/thm/arsnova/WiringTest.java @@ -18,19 +18,18 @@ */ package de.thm.arsnova; - import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Unit test to verify Spring context wiring. - * + * */ public class WiringTest extends AbstractSpringContextTestBase { - @Test - public void testWiring() throws Exception { - assertTrue(applicationContext.getBeanDefinitionCount() > 0); - } + @Test + public void testWiring() throws Exception { + assertTrue(applicationContext.getBeanDefinitionCount() > 0); + } } \ No newline at end of file diff --git a/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java b/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java index 17e3b11a28435b37156af70e6c9f8514167f9d99..cea87b5a78954bd6ab3222a89f97d195014be638 100644 --- a/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java +++ b/src/test/java/de/thm/arsnova/controller/FeedbackControllerTest.java @@ -19,7 +19,6 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; import de.thm.arsnova.exceptions.NotFoundException; -import de.thm.arsnova.exceptions.UnauthorizedException; import de.thm.arsnova.services.StubUserService; @RunWith(SpringJUnit4ClassRunner.class) @@ -37,7 +36,7 @@ public class FeedbackControllerTest { @Autowired private FeedbackController feedbackController; - + @Autowired private StubUserService userService; @@ -49,41 +48,16 @@ public class FeedbackControllerTest { .getBean(AnnotationMethodHandlerAdapter.class); } - @Test(expected=NotFoundException.class) + @Test(expected = NotFoundException.class) public void testShouldNotGetFeedbackForUnknownSession() throws Exception { userService.setUserAuthenticated(true); - + request.setMethod("GET"); request.setRequestURI("/session/00000000/feedback"); - final ModelAndView mav = handlerAdapter.handle(request, response, feedbackController); - + final ModelAndView mav = handlerAdapter.handle(request, response, + feedbackController); + assertNull(mav); assertTrue(response.getStatus() == 404); } - - @Test(expected=UnauthorizedException.class) - public void testShouldNotGetFeedbackIfUnauthorized() throws Exception { - userService.setUserAuthenticated(false); - - request.setMethod("GET"); - request.setRequestURI("/session/00000000/feedback"); - final ModelAndView mav = handlerAdapter.handle(request, response, feedbackController); - - assertNull(mav); - assertTrue(response.getStatus() == 401); - } - - @Test(expected=UnauthorizedException.class) - public void testShouldNotSaveFeedbackIfUnauthorized() throws Exception { - userService.setUserAuthenticated(false); - - request.setMethod("POST"); - request.setRequestURI("/session/00000000/feedback"); - request.setContentType("application/json"); - request.setContent("0".getBytes()); - final ModelAndView mav = handlerAdapter.handle(request, response, feedbackController); - - assertNull(mav); - assertTrue(response.getStatus() == 401); - } } diff --git a/src/test/java/de/thm/arsnova/controller/LoginControllerTest.java b/src/test/java/de/thm/arsnova/controller/LoginControllerTest.java index d0989347804bb6f7d6559af84a7cc183d468ce7c..c6f2256fe76f2179c5da7838de9af5f5327d1240 100644 --- a/src/test/java/de/thm/arsnova/controller/LoginControllerTest.java +++ b/src/test/java/de/thm/arsnova/controller/LoginControllerTest.java @@ -42,13 +42,11 @@ import org.springframework.web.servlet.view.RedirectView; import de.thm.arsnova.services.StubUserService; - @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ +@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/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" }) public class LoginControllerTest { @Inject @@ -56,18 +54,19 @@ public class LoginControllerTest { private MockHttpServletRequest request; private MockHttpServletResponse response; private HandlerAdapter handlerAdapter; - + @Autowired private LoginController loginController; - + @Autowired private StubUserService userService; - + @Before public void setUp() throws Exception { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); - handlerAdapter = applicationContext.getBean(AnnotationMethodHandlerAdapter.class); + handlerAdapter = applicationContext + .getBean(AnnotationMethodHandlerAdapter.class); } @Test @@ -76,16 +75,18 @@ public class LoginControllerTest { request.setRequestURI("/doLogin"); request.addParameter("type", "guest"); - final ModelAndView mav = handlerAdapter.handle(request, response, loginController); + final ModelAndView mav = handlerAdapter.handle(request, response, + loginController); assertNotNull(mav); assertNotNull(mav.getView()); RedirectView view = (RedirectView) mav.getView(); assertEquals("/#auth/checkLogin", view.getUrl()); - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); assertEquals(auth.getClass(), UsernamePasswordAuthenticationToken.class); } - + @Test public void testReuseGuestLogin() throws Exception { request.setMethod("GET"); @@ -93,21 +94,23 @@ public class LoginControllerTest { request.addParameter("type", "guest"); request.addParameter("user", "Guest1234567890"); - final ModelAndView mav = handlerAdapter.handle(request, response, loginController); + final ModelAndView mav = handlerAdapter.handle(request, response, + loginController); assertNotNull(mav); assertNotNull(mav.getView()); RedirectView view = (RedirectView) mav.getView(); assertEquals("/#auth/checkLogin", view.getUrl()); - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); assertEquals(auth.getClass(), UsernamePasswordAuthenticationToken.class); assertEquals("Guest1234567890", auth.getName()); } - + @Test public void testUser() throws Exception { userService.setUserAuthenticated(true); - + request.setMethod("GET"); request.setRequestURI("/whoami"); @@ -120,20 +123,22 @@ public class LoginControllerTest { public void testLogoutWithoutRedirect() throws Exception { request.setMethod("GET"); request.setRequestURI("/logout"); - final ModelAndView mav = handlerAdapter.handle(request, response, loginController); + final ModelAndView mav = handlerAdapter.handle(request, response, + loginController); assertNotNull(mav); assertNotNull(mav.getView()); RedirectView view = (RedirectView) mav.getView(); assertEquals("/", view.getUrl()); } - + @Test public void testLogoutWithRedirect() throws Exception { request.setMethod("GET"); request.setRequestURI("/logout"); request.addHeader("referer", "/dojo-index.html"); - final ModelAndView mav = handlerAdapter.handle(request, response, loginController); + final ModelAndView mav = handlerAdapter.handle(request, response, + loginController); assertNotNull(mav); assertNotNull(mav.getView()); RedirectView view = (RedirectView) mav.getView(); diff --git a/src/test/java/de/thm/arsnova/controller/SessionControllerTest.java b/src/test/java/de/thm/arsnova/controller/SessionControllerTest.java index 52c7f7725f7fb6e5262bbd2fd57392b5996c7711..ce228e655522c80bd159909fd9d7e78dbc5d09f6 100644 --- a/src/test/java/de/thm/arsnova/controller/SessionControllerTest.java +++ b/src/test/java/de/thm/arsnova/controller/SessionControllerTest.java @@ -38,7 +38,7 @@ public class SessionControllerTest { @Autowired private SessionController sessionController; - + @Autowired private StubUserService userService; @@ -50,66 +50,71 @@ public class SessionControllerTest { .getBean(AnnotationMethodHandlerAdapter.class); } - @Test(expected=NotFoundException.class) + @Test(expected = NotFoundException.class) public void testShouldNotGetUnknownSession() throws Exception { userService.setUserAuthenticated(true); - + request.setMethod("GET"); request.setRequestURI("/session/00000000"); - final ModelAndView mav = handlerAdapter.handle(request, response, sessionController); - + final ModelAndView mav = handlerAdapter.handle(request, response, + sessionController); + assertNull(mav); assertTrue(response.getStatus() == 404); } - @Test(expected=ForbiddenException.class) + @Test(expected = ForbiddenException.class) public void testShouldNotGetForbiddenSession() throws Exception { userService.setUserAuthenticated(true); - + request.setMethod("GET"); request.setRequestURI("/session/99999999"); - final ModelAndView mav = handlerAdapter.handle(request, response, sessionController); + final ModelAndView mav = handlerAdapter.handle(request, response, + sessionController); assertNull(mav); assertTrue(response.getStatus() == 403); } - - @Test(expected=UnauthorizedException.class) + + @Test(expected = UnauthorizedException.class) public void testShouldNotGetSessionIfUnauthorized() throws Exception { userService.setUserAuthenticated(false); - + request.setMethod("GET"); request.setRequestURI("/session/00000000"); - final ModelAndView mav = handlerAdapter.handle(request, response, sessionController); - + final ModelAndView mav = handlerAdapter.handle(request, response, + sessionController); + assertNull(mav); assertTrue(response.getStatus() == 401); } - - @Test(expected=UnauthorizedException.class) + + @Test(expected = UnauthorizedException.class) public void testShouldNotGetSessionIfAnonymous() throws Exception { userService.setUserAuthenticated(false); userService.useAnonymousUser(); - + request.setMethod("GET"); request.setRequestURI("/session/00000000"); - final ModelAndView mav = handlerAdapter.handle(request, response, sessionController); - + final ModelAndView mav = handlerAdapter.handle(request, response, + sessionController); + assertNull(mav); assertTrue(response.getStatus() == 401); } - - @Test(expected=UnauthorizedException.class) + + @Test(expected = UnauthorizedException.class) public void testShouldCreateSessionIfUnauthorized() throws Exception { userService.setUserAuthenticated(false); - + request.setMethod("POST"); request.setRequestURI("/session"); request.setContentType("application/json"); request.setContent("{}".getBytes()); - - final ModelAndView mav = handlerAdapter.handle(request, response, sessionController); - + + final ModelAndView mav = handlerAdapter.handle(request, response, + sessionController); + assertNull(mav); assertTrue(response.getStatus() == 401); } diff --git a/src/test/java/de/thm/arsnova/controller/WelcomeControllerTest.java b/src/test/java/de/thm/arsnova/controller/WelcomeControllerTest.java index 9790d8055664d98b3481aa140ce1d035eae15123..5647c7271421362c8e4f2eb61a55ff2548591a05 100644 --- a/src/test/java/de/thm/arsnova/controller/WelcomeControllerTest.java +++ b/src/test/java/de/thm/arsnova/controller/WelcomeControllerTest.java @@ -36,15 +36,15 @@ public class WelcomeControllerTest extends AbstractSpringContextTestBase { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } - + @Test public void testIndexPage() throws Exception { request.setMethod("GET"); - request.setRequestURI("/"); + request.setRequestURI("/"); + + final ModelAndView mav = handle(request, response); + assertNotNull(mav); + assertEquals("redirect:/index.html", mav.getViewName()); + } - final ModelAndView mav = handle(request, response); - assertNotNull(mav); - assertEquals("redirect:/index.html", mav.getViewName()); - } - } diff --git a/src/test/java/de/thm/arsnova/dao/StubDatabaseDao.java b/src/test/java/de/thm/arsnova/dao/StubDatabaseDao.java index 5b746a10640b86b5d7896fcbadc8341dfa2e6596..9bbcbed03330cb22ec1f3946f0e10469ca57332f 100644 --- a/src/test/java/de/thm/arsnova/dao/StubDatabaseDao.java +++ b/src/test/java/de/thm/arsnova/dao/StubDatabaseDao.java @@ -1,11 +1,10 @@ package de.thm.arsnova.dao; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -15,6 +14,7 @@ import de.thm.arsnova.entities.Question; import de.thm.arsnova.entities.Session; import de.thm.arsnova.entities.User; import de.thm.arsnova.exceptions.ForbiddenException; +import de.thm.arsnova.exceptions.NoContentException; import de.thm.arsnova.exceptions.NotFoundException; @Component @@ -23,15 +23,14 @@ public class StubDatabaseDao implements IDatabaseDao { private static Map<String, Session> stubSessions = new ConcurrentHashMap<String, Session>(); private static Map<String, Feedback> stubFeedbacks = new ConcurrentHashMap<String, Feedback>(); - private static Map<Session, Question> stubQuestions = new ConcurrentHashMap<Session, Question>(); - - private final Logger logger = LoggerFactory.getLogger(getClass()); - + private static Map<String, List<Question>> stubQuestions = new ConcurrentHashMap<String, List<Question>>(); + public StubDatabaseDao() { fillWithDummySessions(); fillWithDummyFeedbacks(); + fillWithDummyQuestions(); } - + private void fillWithDummySessions() { Session session = new Session(); session.setActive(true); @@ -39,35 +38,44 @@ public class StubDatabaseDao implements IDatabaseDao { session.setKeyword("12345678"); session.setName("TestSession1"); session.setShortName("TS1"); - + stubSessions.put("12345678", session); - + session.setActive(true); session.setCreator("ptsr00"); session.setKeyword("87654321"); session.setName("TestSession2"); session.setShortName("TS2"); - + stubSessions.put("87654321", session); } - + private void fillWithDummyFeedbacks() { stubFeedbacks.put("12345678", new Feedback(0, 0, 0, 0)); stubFeedbacks.put("87654321", new Feedback(2, 3, 5, 7)); + stubFeedbacks.put("18273645", new Feedback(2, 3, 5, 11)); + } + + private void fillWithDummyQuestions() { + List<Question> questions = new ArrayList<Question>(); + questions.add(new Question()); + stubQuestions.put("12345678", questions); } - + @Override public void cleanFeedbackVotes(int cleanupFeedbackDelay) { - stubSessions.clear(); + stubSessions.clear(); } @Override public Session getSession(String keyword) { // Magic keyword for forbidden session - if (keyword.equals("99999999")) throw new ForbiddenException(); - + if (keyword.equals("99999999")) + throw new ForbiddenException(); + Session session = stubSessions.get(keyword); - if (session == null) throw new NotFoundException(); + if (session == null) + throw new NotFoundException(); return session; } @@ -81,11 +89,13 @@ public class StubDatabaseDao implements IDatabaseDao { @Override public Feedback getFeedback(String keyword) { // Magic keyword for forbidden session - if (keyword.equals("99999999")) throw new ForbiddenException(); - + if (keyword.equals("99999999")) + throw new ForbiddenException(); + Feedback feedback = stubFeedbacks.get(keyword); - if (feedback == null) throw new NotFoundException(); - + if (feedback == null) + throw new NotFoundException(); + return feedback; } @@ -94,19 +104,16 @@ public class StubDatabaseDao implements IDatabaseDao { if (stubFeedbacks.get(keyword) == null) { stubFeedbacks.put(keyword, new Feedback(0, 0, 0, 0)); } - + Feedback sessionFeedback = stubFeedbacks.get(keyword); - + List<Integer> values = sessionFeedback.getValues(); values.set(value, values.get(value) + 1); - + sessionFeedback = new Feedback(values.get(0), values.get(1), values.get(2), values.get(3)); - - stubFeedbacks.put( - keyword, - sessionFeedback - ); - + + stubFeedbacks.put(keyword, sessionFeedback); + return true; } @@ -123,7 +130,9 @@ public class StubDatabaseDao implements IDatabaseDao { @Override public boolean saveQuestion(Session session, Question question) { - stubQuestions.put(session, question); + List<Question> questions = stubQuestions.get(session.get_id()); + questions.add(question); + stubQuestions.put(session.get_id(), questions); return stubQuestions.get(session) != null; } @@ -135,16 +144,19 @@ public class StubDatabaseDao implements IDatabaseDao { @Override public List<Question> getSkillQuestions(String session) { - // TODO Auto-generated method stub - return null; + if (getSession(session) == null) + throw new NotFoundException(); + List<Question> questions = stubQuestions.get(session); + if (questions == null) + throw new NoContentException(); + return questions; } @Override public int getSkillQuestionCount(String sessionkey) { - // TODO Auto-generated method stub - return 0; + return stubQuestions.get(sessionkey).size(); } - + @Override public List<Session> getMySessions(String username) { // TODO Auto-generated method stub @@ -160,7 +172,13 @@ public class StubDatabaseDao implements IDatabaseDao { @Override public void updateSessionOwnerActivity(Session session) { // TODO Auto-generated method stub - + + } + + @Override + public Integer getMyFeedback(String keyword, User user) { + // TODO Auto-generated method stub + return null; } @Override diff --git a/src/test/java/de/thm/arsnova/services/FeedbackServiceTest.java b/src/test/java/de/thm/arsnova/services/FeedbackServiceTest.java index f33840187066beedf784ae45f349c60a4edeb32b..8332d19183dc8158b6025ae3289f504875dea33c 100644 --- a/src/test/java/de/thm/arsnova/services/FeedbackServiceTest.java +++ b/src/test/java/de/thm/arsnova/services/FeedbackServiceTest.java @@ -18,8 +18,8 @@ */ package de.thm.arsnova.services; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,11 +27,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import de.thm.arsnova.exceptions.NoContentException; import de.thm.arsnova.exceptions.NotFoundException; -import de.thm.arsnova.exceptions.UnauthorizedException; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ +@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/arsnova-servlet.xml", "file:src/main/webapp/WEB-INF/spring/spring-main.xml", "file:src/test/resources/test-config.xml" @@ -40,22 +40,16 @@ public class FeedbackServiceTest { @Autowired IFeedbackService feedbackService; - + @Autowired StubUserService userService; - @Test(expected=NotFoundException.class) + @Test(expected = NotFoundException.class) public void testShouldFindFeedbackForNonExistantSession() { userService.setUserAuthenticated(true); feedbackService.getFeedback("00000000"); } - - @Test(expected=UnauthorizedException.class) - public void testShouldNotReturnFeedbackIfUnauthorized() { - userService.setUserAuthenticated(false); - feedbackService.getFeedback("00000000"); - } - + @Test public void testShouldReturnFeedback() { userService.setUserAuthenticated(true); @@ -65,40 +59,46 @@ public class FeedbackServiceTest { assertEquals(5, (int) feedbackService.getFeedback("87654321").getValues().get(2)); assertEquals(7, (int) feedbackService.getFeedback("87654321").getValues().get(3)); } - - @Test(expected=NotFoundException.class) + + @Test(expected = NotFoundException.class) public void testShouldFindFeedbackCountForNonExistantSession() { userService.setUserAuthenticated(true); feedbackService.getFeedbackCount("00000000"); } - - @Test(expected=UnauthorizedException.class) - public void testShouldNotReturnFeedbackCountIfUnauthorized() { - userService.setUserAuthenticated(false); - feedbackService.getFeedbackCount("00000000"); - } - + @Test public void testShouldReturnFeedbackCount() { userService.setUserAuthenticated(true); assertEquals(17, feedbackService.getFeedbackCount("87654321")); } - - @Test(expected=NotFoundException.class) + + @Test(expected = NotFoundException.class) public void testShouldFindAverageFeedbackForNonExistantSession() { userService.setUserAuthenticated(true); feedbackService.getAverageFeedback("00000000"); } - - @Test(expected=UnauthorizedException.class) - public void testShouldNotReturnAverageFeedbackIfUnauthorized() { - userService.setUserAuthenticated(false); - feedbackService.getAverageFeedback("00000000"); + + @Test + public void testShouldReturnZeroFeedbackCountForNoFeedbackAtAll() { + userService.setUserAuthenticated(true); + assertEquals(0, feedbackService.getFeedbackCount("12345678")); + } + + @Test(expected = NoContentException.class) + public void testShouldReturnAverageFeedbackForNoFeedbackAtAll() { + userService.setUserAuthenticated(true); + feedbackService.getAverageFeedback("12345678"); } - + + @Test + public void testShouldReturnAverageFeedbackRounded() { + userService.setUserAuthenticated(true); + assertEquals(2, feedbackService.getAverageFeedbackRounded("18273645")); + } + @Test - public void testShouldReturnAverageFeedback() { + public void testShouldReturnAverageFeedbackNotRounded() { userService.setUserAuthenticated(true); - assertEquals(2, feedbackService.getAverageFeedback("87654321")); + assertEquals(2.1904, feedbackService.getAverageFeedback("18273645"), 0.001); } } \ No newline at end of file diff --git a/src/test/java/de/thm/arsnova/services/QuestionServiceTest.java b/src/test/java/de/thm/arsnova/services/QuestionServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..607f65476d93cd1e7f8cd819fb5b158069406e68 --- /dev/null +++ b/src/test/java/de/thm/arsnova/services/QuestionServiceTest.java @@ -0,0 +1,64 @@ +/* + * 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.services; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import de.thm.arsnova.exceptions.NotFoundException; +import de.thm.arsnova.exceptions.UnauthorizedException; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "file:src/main/webapp/WEB-INF/arsnova-servlet.xml", + "file:src/main/webapp/WEB-INF/spring/spring-main.xml", + "file:src/test/resources/test-config.xml" +}) +public class QuestionServiceTest { + + @Autowired + IQuestionService questionService; + + @Autowired + StubUserService userService; + + @Test(expected = UnauthorizedException.class) + public void testShouldNotReturnQuestionsIfNotAuthenticated() { + userService.setUserAuthenticated(false); + questionService.getSkillQuestions("12345678"); + + } + + @Test(expected = NotFoundException.class) + public void testShouldFindQuestionsForNonExistantSession() { + userService.setUserAuthenticated(true); + questionService.getSkillQuestions("00000000"); + } + + @Test + public void testShouldFindQuestions() { + userService.setUserAuthenticated(true); + assertEquals(1, questionService.getSkillQuestionCount("12345678")); + } +} \ No newline at end of file diff --git a/src/test/java/de/thm/arsnova/services/SessionServiceTest.java b/src/test/java/de/thm/arsnova/services/SessionServiceTest.java index 3ad94fdc68830216c34d8f03ccff2a78a475e251..e70816ce120ab80e22ef00f5ff6f3f251795944a 100644 --- a/src/test/java/de/thm/arsnova/services/SessionServiceTest.java +++ b/src/test/java/de/thm/arsnova/services/SessionServiceTest.java @@ -34,16 +34,15 @@ import de.thm.arsnova.exceptions.NotFoundException; import de.thm.arsnova.exceptions.UnauthorizedException; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ +@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/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" }) public class SessionServiceTest { @Autowired ISessionService sessionService; - + @Autowired StubUserService userService; @@ -52,23 +51,23 @@ public class SessionServiceTest { System.out.println(sessionService.generateKeyword()); assertTrue(sessionService.generateKeyword().matches("^[0-9]{8}$")); } - - @Test(expected=NotFoundException.class) + + @Test(expected = NotFoundException.class) public void testShouldFindNonExistantSession() { userService.setUserAuthenticated(true); sessionService.joinSession("00000000"); } - - @Test(expected=UnauthorizedException.class) + + @Test(expected = UnauthorizedException.class) public void testShouldNotReturnSessionIfUnauthorized() { userService.setUserAuthenticated(false); sessionService.joinSession("12345678"); } - - @Test(expected=UnauthorizedException.class) + + @Test(expected = UnauthorizedException.class) public void testShouldNotSaveSessionIfUnauthorized() { userService.setUserAuthenticated(false); - + Session session = new Session(); session.setActive(true); session.setCreator("ptsr00"); @@ -76,16 +75,16 @@ public class SessionServiceTest { session.setName("TestSessionX"); session.setShortName("TSX"); sessionService.saveSession(session); - + userService.setUserAuthenticated(true); - + assertNull(sessionService.joinSession("11111111")); } - + @Test public void testShouldSaveSession() { userService.setUserAuthenticated(true); - + Session session = new Session(); session.setActive(true); session.setCreator("ptsr00"); diff --git a/src/test/java/de/thm/arsnova/services/StubUserService.java b/src/test/java/de/thm/arsnova/services/StubUserService.java index 52e2fd8cfcb61def3135f27595f332671bd9b3ea..f12bf302597844620e42fefa44fa9cc16a3a63b7 100644 --- a/src/test/java/de/thm/arsnova/services/StubUserService.java +++ b/src/test/java/de/thm/arsnova/services/StubUserService.java @@ -7,19 +7,21 @@ import de.thm.arsnova.entities.User; public class StubUserService extends UserService { private User stubUser = null; - + public void setUserAuthenticated(boolean isAuthenticated) { if (isAuthenticated) { - stubUser = new User(new UsernamePasswordAuthenticationToken("ptsr00","testpassword")); + stubUser = new User(new UsernamePasswordAuthenticationToken( + "ptsr00", "testpassword")); return; } stubUser = null; } - + public void useAnonymousUser() { - stubUser = new User(new UsernamePasswordAuthenticationToken("anonymous","")); + stubUser = new User(new UsernamePasswordAuthenticationToken( + "anonymous", "")); } - + @Override public User getCurrentUser() { return stubUser;