private void validateOAuthScope(NsiScope scope) throws ServiceException {
   if (!Security.getUserDetails().getNsiScopes().contains(scope)) {
     log.warn("OAuth access token not valid for {}", scope);
     throw createServiceException(
         ConnectionServiceProviderErrorCodes.SECURITY.MISSING_GRANTED_SCOPE);
   }
 }
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (Security.getUserDetails() == null) {
      LOGGER.debug("No user present");
      response.setStatus(403);
      return;
    }

    String transport = request.getParameter("transport");
    if (transport == null) {
      LOGGER.debug("No transport defined for the long polling call");
      response.setStatus(400);
      return;
    }

    if (transport.equals("longpollajax")
        || transport.equals("longpollxdr")
        || transport.equals("longpolljsonp")) {
      doLongPollConnect(request, response, transport);
      return;
    }

    LOGGER.debug("Do not understand the transport '{}'", transport);
    response.setStatus(400);
  }
  @Test
  public void do_switch_role_when_user_has_no_selected_role() throws Exception {
    user =
        new RichUserDetailsFactory()
            .addBodRoles(BodRole.createNewUser())
            .addUserGroup(new UserGroupFactory().setId("urn:user-group").create())
            .create();
    Security.setUserDetails(user);

    PhysicalResourceGroup pGroup = new PhysicalResourceGroupFactory().setActive(true).create();

    when(virtualResourceGroupServiceMock.findByAdminGroup("urn:user-group"))
        .thenReturn(Optional.empty());
    when(physicalResourceGroupServiceMock.find(2L)).thenReturn(Optional.of(pGroup));

    mockMvc
        .perform(
            post("/request")
                .param("physicalResourceGroupId", "2")
                .param("userGroupId", "urn:user-group")
                .param("bandwidth", "1111")
                .param("userLabel", "port")
                .param("message", "I want!"))
        .andExpect(view().name("redirect:/user"));

    assertThat(
        "Context should not be cleared",
        SecurityContextHolder.getContext().getAuthentication(),
        nullValue());

    verify(virtualResourceGroupServiceMock).save(any(VirtualResourceGroup.class));
    verify(virtualPortServiceMock)
        .requestCreateVirtualPort(eq(user), any(VirtualPortCreateRequestLink.class));
  }
  @Test
  public void request_virtual_port_without_email_should_continue() throws Exception {
    RichUserDetails user = new RichUserDetailsFactory().setEmail("").create();
    Security.setUserDetails(user);

    mockMvc
        .perform(get("/request"))
        .andExpect(model().attributeExists("userGroupViews"))
        .andExpect(view().name("virtualports/selectTeamForLocalVirtualPort"));
  }
  @Before
  public void setupAndLogin() {
    mockMvc = standaloneSetup(subject).build();

    UserGroup group1 = new UserGroupFactory().setName("A").setId("urn:user-group").create();
    UserGroup group2 = new UserGroupFactory().setName("B").create();
    UserGroup group3 = new UserGroupFactory().setName("C").create();
    user =
        new RichUserDetailsFactory()
            .addUserRole()
            .addUserGroup(group3)
            .addUserGroup(group1)
            .addUserGroup(group2)
            .create();
    Security.setUserDetails(user);
  }
  /**
   * The reservation method processes an NSI reservation request for inter-domain bandwidth. Those
   * parameters required for the request to proceed to a processing actor will be validated,
   * however, all other parameters will be validated in the processing actor.
   *
   * @param parameters The un-marshaled JAXB object holding the NSI reservation request.
   * @return The GenericAcknowledgmentType object returning the correlationId sent in the
   *     reservation request. We are acknowledging that we have received the request.
   * @throws ServiceException if we can determine there is processing error before digging into the
   *     request.
   */
  @Override
  public GenericAcknowledgmentType reserve(final ReserveRequestType reservationRequest)
      throws ServiceException {
    checkNotNull(reservationRequest);
    validateOAuthScope(NsiScope.RESERVE);

    log.info(
        "Received a NSI reserve request connectionId {}",
        reservationRequest.getReserve().getReservation().getConnectionId());

    Connection connection = RESERVE_REQUEST_TO_CONNECTION.apply(reservationRequest);

    final NsiRequestDetails requestDetails =
        new NsiRequestDetails(
            reservationRequest.getReplyTo(), reservationRequest.getCorrelationId());

    reserve(connection, requestDetails, Security.getUserDetails());

    return createGenericAcknowledgment(requestDetails.getCorrelationId());
  }
  private void doLongPollConnect(
      HttpServletRequest request, HttpServletResponse response, String transport) {
    response.setCharacterEncoding("utf-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setContentType("text/" + (transport.equals("longpolljsonp") ? "javascript" : "plain"));

    final String id = request.getParameter("id");
    final int count = Integer.parseInt(request.getParameter("count"));
    final int lastEventId = Integer.parseInt(request.getParameter("lastEventId"));

    AsyncContext aCtx = request.startAsync(request, response);
    aCtx.addListener(
        new AsyncListener() {
          @Override
          public void onTimeout(AsyncEvent event) throws IOException {
            LOGGER.debug("onTimeout {}: {}", id, event);
            cleanup(event);
          }

          @Override
          public void onStartAsync(AsyncEvent event) throws IOException {}

          @Override
          public void onError(AsyncEvent event) throws IOException {
            LOGGER.debug("onError {}: {}", id, event);
            cleanup(event);
          }

          @Override
          public void onComplete(AsyncEvent event) throws IOException {
            cleanup(event);
          }

          private void cleanup(AsyncEvent event) {
            connections.removeClient(id, count);
          }
        });

    connections.clientRequest(id, count, lastEventId, aCtx, Security.getUserDetails());
  }
  @Override
  public GenericAcknowledgmentType terminate(TerminateRequestType parameters)
      throws ServiceException {
    log.info(
        "Received a NSI terminate request for connectionId '{}'",
        parameters.getTerminate().getConnectionId());

    validateOAuthScope(NsiScope.TERMINATE);
    validateProviderNsa(parameters.getTerminate().getProviderNSA());

    Connection connection = getConnectionOrFail(parameters.getTerminate().getConnectionId());

    NsiRequestDetails requestDetails =
        new NsiRequestDetails(parameters.getReplyTo(), parameters.getCorrelationId());

    connectionService.asyncTerminate(
        connection.getId(),
        parameters.getTerminate().getRequesterNSA(),
        requestDetails,
        Security.getUserDetails());

    return createGenericAcknowledgment(requestDetails.getCorrelationId());
  }
  @RequestMapping(value = DELETE, params = ID_KEY, method = RequestMethod.DELETE)
  public String delete(
      Long id, @RequestParam(value = PAGE_KEY, required = false) Integer page, Model uiModel) {
    return physicalPortService
        .find(id)
        .map(
            port -> {
              if (port instanceof UniPort) {
                virtualServiceService
                    .findEntriesForUniPort((UniPort) port)
                    .forEach(
                        service ->
                            virtualServiceService.delete(service, Security.getUserDetails()));
              }

              physicalPortService.delete(id);

              uiModel.asMap().clear();
              uiModel.addAttribute(PAGE_KEY, page == null ? "1" : page.toString());

              return redirectPortListPage(port);
            })
        .orElse("redirect:");
  }
 @Before
 public void setUp() {
   user = new RichUserDetailsFactory().create();
   Security.setUserDetails(user);
 }