Ejemplo n.º 1
0
  @Test
  public void shouldChooseVaderThemeBecauseOfTheContextFiltersDecreeSequence() {
    final String SUNNY = "sunny";
    final String ARISTO = "aristo";
    final String VADER = "vader";

    final DecreeSequence ds142 = mock(DecreeSequence.class);
    final DecreeSequence ds475 = mock(DecreeSequence.class);
    final User currentUser = mock(User.class);
    final PerDecreePreference pref142 = mock(PerDecreePreference.class);
    final PerDecreePreference pref475 = mock(PerDecreePreference.class);

    when(userSession.getCurrentUser()).thenReturn(currentUser);
    when(pref142.getDecreeSequence()).thenReturn(ds142);
    when(pref475.getDecreeSequence()).thenReturn(ds475);
    when(pref142.getTheme()).thenReturn(SUNNY);
    when(pref475.getTheme()).thenReturn(VADER);

    when(userSession.getUserPrefferedTheme()).thenReturn(Optional.of(ARISTO));

    when(contextualFilter.getDecreeSequence()).thenReturn(ds475);
    when(perDecreePreferenceRepository.findByUser(currentUser))
        .thenReturn(asList(pref142, pref475));

    String theme = controller.getCurrentThemeOrElse("aristo");

    assertThat(theme, is(VADER));
  }
Ejemplo n.º 2
0
 public static void setUserSession(HttpServletRequest request, String propertyName, Object obj) {
   UserSession gus = (UserSession) WebUtils.getSessionAttribute(request, Constant.SESS_USER);
   if (propertyName.equals(PROPERTY_USER)) gus.setUser((User) obj);
   else if (propertyName.equals(PROPERTY_LOGIN)) gus.setLogin((Integer) obj);
   else if (propertyName.equals(PROPERTY_BOX_LIST)) gus.setBoxList((List) obj);
   else if (propertyName.equals(PROPERTY_SEARCH)) gus.setSearchKey((String) obj);
 }
Ejemplo n.º 3
0
  @Route(method = HttpRequest.Method.GET, urlPattern = "/description")
  public HttpResponse description(HttpRequest request) {
    ArrayList<String> requiredCookies =
        new ArrayList<String>() {
          {
            add("auth");
          }
        };

    if (!SessionManager.getInstance().areCookiesValid(requiredCookies, request)) {
      HttpResponse res = new HttpResponse("auth cookie wasn't found!", 403);
      return res;
    }

    String sessionId = SessionManager.getSessionIdForRequest(request);
    UserSession userSession = (UserSession) SessionManager.getInstance().getSessionInfo(sessionId);
    if (userSession == null) {
      return new HttpResponse("Session is closed", 401);
    }

    User user = users.get(userSession.getName());
    if (user == null) {
      return new HttpResponse("Something went wrong, user info wasn't found", 404);
    }

    return new HttpResponse(user.getDescription(), 200);
  }
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {

    AccountForm accountForm = (AccountForm) command;
    try {
      if (accountForm.isNewAccount()) {
        this.petStore.insertAccount(accountForm.getAccount());
      } else {
        this.petStore.updateAccount(accountForm.getAccount());
      }
    } catch (DataIntegrityViolationException ex) {
      errors.rejectValue(
          "account.username",
          "USER_ID_ALREADY_EXISTS",
          "User ID already exists: choose a different ID.");
      return showForm(request, response, errors);
    }

    UserSession userSession =
        new UserSession(this.petStore.getAccount(accountForm.getAccount().getUsername()));
    PagedListHolder myList =
        new PagedListHolder(
            this.petStore.getProductListByCategory(
                accountForm.getAccount().getFavouriteCategoryId()));
    myList.setPageSize(4);
    userSession.setMyList(myList);
    request.getSession().setAttribute("userSession", userSession);
    return super.onSubmit(request, response, command, errors);
  }
Ejemplo n.º 5
0
  private void parseMetadata() throws ZipException, IOException, JAXBException, SAXException {
    ZipFile zipFile = null;
    try {
      // get the session.xml zip entry
      zipFile = new ZipFile(sessionFile);
      InputStream metadataStream =
          zipFile.getInputStream(zipFile.getEntry(UserSession.SESSION_DATA_FILENAME));

      // validate
      // ClientSession.getSchema().newValidator().validate(new StreamSource(metadataStream));

      // parse the metadata xml to java objects using jaxb
      Unmarshaller unmarshaller = UserSession.getPreviousJAXBContext().createUnmarshaller();
      unmarshaller.setSchema(UserSession.getPreviousSchema());
      NonStoppingValidationEventHandler validationEventHandler =
          new NonStoppingValidationEventHandler();
      unmarshaller.setEventHandler(validationEventHandler);
      this.sessionType =
          unmarshaller.unmarshal(new StreamSource(metadataStream), SessionType.class).getValue();

      if (validationEventHandler.hasEvents()) {
        throw new JAXBException(
            "Invalid session file:\n" + validationEventHandler.getValidationEventsAsString());
      }
    } finally {
      IOUtils.closeIfPossible(zipFile);
    }
  }
  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    // Long orderId  = (Long) WebUtils.getRequiredSessionAttribute(request, "orderId");
    int orderId = Integer.parseInt(request.getParameter("orderId"));
    Order order = this.orderService.getOrderById(orderId);

    UserSession userSession =
        (UserSession) WebUtils.getRequiredSessionAttribute(request, "userSession");

    if (userSession.getUser().getUsername().equals(order.getUser().getUsername())) {
      String message = request.getParameter("message");

      Map<String, Object> model = new HashMap<String, Object>();
      model.put("order", order);

      if (message != null) {
        // after the new order, there's thanks message
        model.put("message", message);
      }
      return new ModelAndView("ViewOrder", model);
    } else {
      return new ModelAndView("ValidationError", "message", "You may only view your own orders.");
    }
  }
Ejemplo n.º 7
0
 private static void updateLogoutInfo(UserSession userSession) {
   if (userSession != null) {
     userSession.setUserLogin(null);
     userSession.setIsLoggedIn(false);
     // Retain the last login info.
   }
 }
 protected Object formBackingObject(HttpServletRequest request) throws Exception {
   UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
   if (userSession != null) {
     return new AccountForm(this.petStore.getAccount(userSession.getAccount().getUsername()));
   } else {
     return new AccountForm();
   }
 }
Ejemplo n.º 9
0
  @Test(expected = ForbiddenException.class)
  public void check_project_permission_ko() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);
    when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER))
        .thenReturn(newArrayList("com.foo:Bar2"));

    session.checkProjectPermission(UserRole.USER, "com.foo:Bar");
  }
Ejemplo n.º 10
0
 /**
  * logic to accept or reject access to the page, check log in status
  *
  * @param req
  * @return true when authentication is deemed valid
  */
 boolean isAuth(HttpServletRequest req) {
   UserSession user;
   if (sans_blocage) return true;
   user = OutilsWeb.getUser(req);
   log.info(
       "user:"******";connected=" + ((user != null && user.isConnecte()) ? "true" : "false"));
   return user != null && user.isConnecte();
 }
Ejemplo n.º 11
0
 public static Object getUserSession(HttpServletRequest request, String propertyName) {
   UserSession gus = (UserSession) WebUtils.getSessionAttribute(request, Constant.SESS_USER);
   if (gus != null && propertyName.equals(PROPERTY_USER)) return gus.getUser();
   else if (gus != null && propertyName.equals(PROPERTY_LOGIN)) return gus.getLogin();
   else if (gus != null && propertyName.equals(PROPERTY_BOX_LIST)) return gus.getBoxList();
   else if (gus != null && propertyName.equals(PROPERTY_SEARCH)) return gus.getSearchKey();
   return null;
 }
Ejemplo n.º 12
0
  @Test(expected = ForbiddenException.class)
  public void check_component_key_permission_when_project_not_found() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);

    when(resourceDao.getRootProjectByComponentKey("com.foo:Bar:BarFile.xoo")).thenReturn(null);

    session.checkComponentPermission(UserRole.USER, "com.foo:Bar:BarFile.xoo");
  }
  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class);

    log.debug("Incoming message: {}", jsonMessage);

    switch (jsonMessage.get("id").getAsString()) {
      case "start":
        start(session, jsonMessage);
        break;
      case "show_faces":
        setVisualization(session, jsonMessage);
        break;
      case "scale_factor":
        setScaleFactor(session, jsonMessage);
        break;
      case "process_num_frames":
        setProcessNumberFrames(session, jsonMessage);
        break;
      case "width_to_process":
        setWidthToProcess(session, jsonMessage);
        break;
      case "get_stats":
        getStats(session);
        break;
      case "euclidean_dis":
        setEuclideanDistance(session, jsonMessage);
        break;
      case "area_threshold":
        setAreaThreshold(session, jsonMessage);
        break;
      case "track_treshold":
        setTrackThreshold(session, jsonMessage);
        break;
      case "stop":
        {
          UserSession user = users.remove(session.getId());
          if (user != null) {
            user.release();
          }
          break;
        }
      case "onIceCandidate":
        {
          JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();
          UserSession user = users.get(session.getId());
          if (user != null) {
            user.addCandidate(candidate);
          }
          break;
        }

      default:
        error(session, "Invalid message with id " + jsonMessage.get("id").getAsString());
        break;
    }
  }
Ejemplo n.º 14
0
  @Test
  public void currentUserSessuinShouldBeAskedForTheUserPrefferedThme() {

    when(userSession.getUserPrefferedTheme()).thenReturn(Optional.of("sunny"));

    String currentTheme = controller.getCurrentThemeOrElse("aristo");

    assertThat(currentTheme, is(equalTo(userSession.getUserPrefferedTheme().get())));
  }
Ejemplo n.º 15
0
  @Test(expected = ForbiddenException.class)
  public void check_global_Permission_ko() {
    UserSession session = newServerUserSession().setLogin("marius");

    when(authorizationDao.selectGlobalPermissions("marius"))
        .thenReturn(Arrays.asList("profileadmin", "admin"));

    session.checkGlobalPermission(GlobalPermissions.DASHBOARD_SHARING);
  }
 public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws Exception {
   UserSession userSession =
       (UserSession) WebUtils.getRequiredSessionAttribute(request, "userSession");
   String username = userSession.getAccount().getUsername();
   Map model = new HashMap();
   model.put("orderList", this.petStore.getOrdersByUsername(username));
   return new ModelAndView("ListOrders", model);
 }
Ejemplo n.º 17
0
  @Test
  public void check_global_Permission_ok() {
    UserSession session = newServerUserSession().setLogin("marius");

    when(authorizationDao.selectGlobalPermissions("marius"))
        .thenReturn(Arrays.asList("profileadmin", "admin"));

    session.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
  }
Ejemplo n.º 18
0
  @Test
  public void has_project_permission_by_uuid() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);
    when(authorizationDao.selectAuthorizedRootProjectsUuids(1, UserRole.USER))
        .thenReturn(newArrayList("ABCD"));

    assertThat(session.hasProjectPermissionByUuid(UserRole.USER, "ABCD")).isTrue();
    assertThat(session.hasProjectPermissionByUuid(UserRole.CODEVIEWER, "ABCD")).isFalse();
    assertThat(session.hasProjectPermissionByUuid(UserRole.ADMIN, "ABCD")).isFalse();
  }
Ejemplo n.º 19
0
  @Test
  public void check_project_uuid_permission_ok() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);

    ComponentDto project = ComponentTesting.newProjectDto();
    when(authorizationDao.selectAuthorizedRootProjectsUuids(1, UserRole.USER))
        .thenReturn(newArrayList(project.uuid()));

    session.checkProjectUuidPermission(UserRole.USER, project.uuid());
  }
Ejemplo n.º 20
0
  @Test(expected = ForbiddenException.class)
  public void check_component_dto_permission_ko() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);

    ComponentDto project = ComponentTesting.newProjectDto();
    when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER))
        .thenReturn(newArrayList(project.uuid()));

    session.checkComponentPermission(UserRole.USER, "another");
  }
Ejemplo n.º 21
0
  @Test
  public void has_global_permission() {
    UserSession session = newServerUserSession().setLogin("marius");

    when(authorizationDao.selectGlobalPermissions("marius"))
        .thenReturn(Arrays.asList("profileadmin", "admin"));

    assertThat(session.hasGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN)).isTrue();
    assertThat(session.hasGlobalPermission(GlobalPermissions.SYSTEM_ADMIN)).isTrue();
    assertThat(session.hasGlobalPermission(GlobalPermissions.DASHBOARD_SHARING)).isFalse();
  }
Ejemplo n.º 22
0
 private static void updateLoginInfo(UserSession userSession, UserLogin userLogin) {
   if ((userSession != null) && (userLogin != null)) {
     String userId = userLogin.getUserId();
     String password = userLogin.getPassword();
     if (StringUtils.isNotNullOrEmpty(userId) && StringUtils.isNotNullOrEmpty(password)) {
       userSession.setUserLogin(userLogin);
       userSession.setIsLoggedIn(true);
       userSession.setLastLogin(userId);
     }
   }
 }
Ejemplo n.º 23
0
  @Test(expected = ForbiddenException.class)
  public void check_component_key_permission_ko() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);

    when(resourceDao.getRootProjectByComponentKey("com.foo:Bar:BarFile.xoo"))
        .thenReturn(new ResourceDto().setKey("com.foo:Bar2"));
    when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER))
        .thenReturn(newArrayList("com.foo:Bar"));

    session.checkComponentPermission(UserRole.USER, "com.foo:Bar:BarFile.xoo");
  }
Ejemplo n.º 24
0
  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    JsonObject jsonMessage = gson.fromJson(message.getPayload(), JsonObject.class);

    log.debug("Incoming message: {}", jsonMessage);

    switch (jsonMessage.get("id").getAsString()) {
      case "start":
        start(session, jsonMessage);
        break;
      case "show_mouths":
        setVisualization(session, jsonMessage);
        break;
      case "scale_factor":
        log.debug("Case scale factor");
        setScaleFactor(session, jsonMessage);
        break;
      case "process_num_frames":
        log.debug("Case process num frames");
        setProcessNumberFrames(session, jsonMessage);
        break;
      case "width_to_process":
        log.debug("Case width to process");
        setWidthToProcess(session, jsonMessage);
        break;
      case "stop":
        {
          UserSession user = users.remove(session.getId());
          if (user != null) {
            user.release();
          }
          break;
        }
      case "onIceCandidate":
        {
          JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();

          UserSession user = users.get(session.getId());
          if (user != null) {
            IceCandidate cand =
                new IceCandidate(
                    candidate.get("candidate").getAsString(),
                    candidate.get("sdpMid").getAsString(),
                    candidate.get("sdpMLineIndex").getAsInt());
            user.addCandidate(cand);
          }
          break;
        }

      default:
        sendError(session, "Invalid message with id " + jsonMessage.get("id").getAsString());
        break;
    }
  }
Ejemplo n.º 25
0
  @Test(expected = ForbiddenException.class)
  public void check_component_uuid_permission_ko() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);

    ComponentDto project = ComponentTesting.newProjectDto();
    ComponentDto file = ComponentTesting.newFileDto(project, "file-uuid");
    when(resourceDao.selectResource("file-uuid"))
        .thenReturn(new ResourceDto().setProjectUuid(project.uuid()));
    when(authorizationDao.selectAuthorizedRootProjectsUuids(1, UserRole.USER))
        .thenReturn(newArrayList(project.uuid()));

    session.checkComponentUuidPermission(UserRole.USER, "another-uuid");
  }
Ejemplo n.º 26
0
  private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {
      // Media Logic (Media Pipeline and Elements)
      UserSession user = new UserSession();
      MediaPipeline pipeline = kurento.createMediaPipeline();
      user.setMediaPipeline(pipeline);
      WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
      user.setWebRtcEndpoint(webRtcEndpoint);
      users.put(session.getId(), user);

      webRtcEndpoint.addOnIceCandidateListener(
          new EventListener<OnIceCandidateEvent>() {

            @Override
            public void onEvent(OnIceCandidateEvent event) {
              JsonObject response = new JsonObject();
              response.addProperty("id", "iceCandidate");
              response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
              try {
                synchronized (session) {
                  session.sendMessage(new TextMessage(response.toString()));
                }
              } catch (IOException e) {
                log.debug(e.getMessage());
              }
            }
          });

      mouth = new NuboMouthDetector.Builder(pipeline).build();

      webRtcEndpoint.connect(mouth);
      mouth.connect(webRtcEndpoint);

      // SDP negotiation (offer and answer)
      String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
      String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

      // Sending response back to client
      JsonObject response = new JsonObject();
      response.addProperty("id", "startResponse");
      response.addProperty("sdpAnswer", sdpAnswer);

      synchronized (session) {
        session.sendMessage(new TextMessage(response.toString()));
      }
      webRtcEndpoint.gatherCandidates();

    } catch (Throwable t) {
      sendError(session, t.getMessage());
    }
  }
Ejemplo n.º 27
0
  @Test
  public void has_component_permission() {
    UserSession session = newServerUserSession().setLogin("marius").setUserId(1);

    String componentKey = "com.foo:Bar:BarFile.xoo";
    when(resourceDao.getRootProjectByComponentKey(componentKey))
        .thenReturn(new ResourceDto().setKey(componentKey));
    when(authorizationDao.selectAuthorizedRootProjectsKeys(1, UserRole.USER))
        .thenReturn(newArrayList(componentKey));

    assertThat(session.hasComponentPermission(UserRole.USER, componentKey)).isTrue();
    assertThat(session.hasComponentPermission(UserRole.CODEVIEWER, componentKey)).isFalse();
    assertThat(session.hasComponentPermission(UserRole.ADMIN, componentKey)).isFalse();
  }
  private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {

      String sessionId = session.getId();
      UserSession user = new UserSession(sessionId);
      users.put(sessionId, user);
      webRtcEndpoint = user.getWebRtcEndpoint();

      // Ice Candidate
      webRtcEndpoint.addOnIceCandidateListener(
          new EventListener<OnIceCandidateEvent>() {
            @Override
            public void onEvent(OnIceCandidateEvent event) {
              JsonObject response = new JsonObject();
              response.addProperty("id", "iceCandidate");
              response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
              sendMessage(session, new TextMessage(response.toString()));
            }
          });

      face = new NuboFaceDetector.Builder(user.getMediaPipeline()).build();
      face.activateServerEvents(1, 3000);
      addFaceListener();

      webRtcEndpoint.connect(face);
      face.connect(webRtcEndpoint);

      // SDP negotiation (offer and answer)
      String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
      String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

      // Sending response back to client
      JsonObject response = new JsonObject();
      response.addProperty("id", "startResponse");
      response.addProperty("sdpAnswer", sdpAnswer);

      synchronized (session) {
        sendMessage(session, new TextMessage(response.toString()));
      }
      webRtcEndpoint.gatherCandidates();

    } catch (NotEnoughResourcesException e) {
      log.warn("Not enough resources", e);
      notEnoughResources(session);
    } catch (Throwable t) {
      log.error("Exception starting session", t);
      error(session, t.getClass().getSimpleName() + ": " + t.getMessage());
    }
  }
Ejemplo n.º 29
0
  @Get
  public Representation getUserAccount() {
    String authhoken = getCookies().getValues(Cookies.AUTH_TOKEN);

    if (StringUtils.isNotBlank(authhoken)) {
      UserSession session = sessions.get(UUID.fromString(authhoken));
      if (!Objects.equal(session, UserSession.EMPTY)) {
        getResponse().setStatus(org.restlet.data.Status.SUCCESS_OK);
        return new JsonRepresentation(session.getUser());
      }
    }

    getResponse().setStatus(org.restlet.data.Status.CLIENT_ERROR_FORBIDDEN);
    return new StringRepresentation("");
  }
Ejemplo n.º 30
0
 @Test
 public void shouldProvideSessionIdOnPost() throws Exception {
   when(httpSession.getId()).thenReturn("ABC123");
   resource.acceptRepresentation(null);
   ArgumentCaptor<StringRepresentation> arg = ArgumentCaptor.forClass(StringRepresentation.class);
   verify(response).setEntity(arg.capture());
   assertEquals("ABC123", arg.getValue().getText());
 }