Example usage for org.springframework.security.authentication TestingAuthenticationToken TestingAuthenticationToken

List of usage examples for org.springframework.security.authentication TestingAuthenticationToken TestingAuthenticationToken

Introduction

In this page you can find the example usage for org.springframework.security.authentication TestingAuthenticationToken TestingAuthenticationToken.

Prototype

public TestingAuthenticationToken(Object principal, Object credentials) 

Source Link

Usage

From source file:org.openeos.wf.test.WorkflowServiceTestCase.java

@Test
public void testAutoAddUserParameter() {
    WorkflowEngine engine = mock(WorkflowEngine.class);
    ServiceRegistration<WorkflowEngine> registration = bc.registerService(WorkflowEngine.class, engine, null);
    URL test1 = getClass().getClassLoader().getResource(TEST1_FILE);
    Deployment deploy1 = workflowService.createDeployment().key("testAutoAddUserParameter").addURL(test1)
            .enableDuplicateFiltering().deploy();
    WorkflowDefinition def = workflowService.getLastWorkflowDefinitionByKey(TEST1_KEY);

    SecurityContextHolder.getContext()/*from   ww  w .j  av  a  2 s.com*/
            .setAuthentication(new TestingAuthenticationToken("testUser", "testCredentials"));

    workflowService.startProcess(def.getId());

    ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class);

    verify(engine).startProcess(eq(def.getId()), captor.capture());

    Map<String, Object> parameters = captor.getValue();
    assertEquals("testUser", parameters.get(org.openeos.wf.Constants.LANUCHER_USER_PARAMETER));

    registration.unregister();
    workflowService.revertDeployment(deploy1.getId());

    SecurityContextHolder.getContext().setAuthentication(null);
}

From source file:org.cloudfoundry.identity.uaa.oauth.TokenAdminEndpointsTests.java

@Test
public void testRevokeTokenForClient() throws Exception {
    Mockito.when(tokenServices.findTokensByClientId("foo"))
            .thenReturn(Collections.<OAuth2AccessToken>singleton(new DefaultOAuth2AccessToken("FOO")));
    Mockito.when(tokenServices.revokeToken("FOO")).thenReturn(true);
    SimpleMessage result = endpoints.revokeClientToken("foo", new StandardPasswordEncoder().encode("FOO"),
            new TestingAuthenticationToken("foo", ""));
    assertEquals("ok", result.getStatus());
}

From source file:org.cloudfoundry.identity.uaa.oauth.TokenAdminEndpointsTests.java

@Test(expected = NoSuchTokenException.class)
public void testRevokeInvalidTokenForClient() throws Exception {
    SimpleMessage result = endpoints.revokeClientToken("foo", "FOO", new TestingAuthenticationToken("foo", ""));
    assertEquals("ok", result.getStatus());
}

From source file:at.ac.univie.isc.asio.engine.DatasetResourceTest.java

@Test
public void forward_request_principal() throws Exception {
    final TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
    authentication.setDetails(new DelegatedCredentialsDetails(Identity.from("test", "password")));
    securityContext.setAuthentication(authentication);
    subject.acceptForm(requestParameters, async, request);
    verify(connector).accept(params.capture());
    assertThat(params.getValue().owner().get(), Matchers.<Principal>is(Identity.from("test", "password")));
}

From source file:alfio.controller.ReservationFlowIntegrationTest.java

/**
 * Test a complete offline payment flow.
 * Will not check in detail.../*w w w. ja v a 2  s  .  c o m*/
 */
@Test
public void reservationFlowTest() throws Exception {

    String eventName = event.getShortName();

    assertTrue(checkInManager.findAllFullTicketInfo(event.getId()).isEmpty());

    List<EventStatistic> eventStatistic = eventStatisticsManager.getAllEventsWithStatistics(user);
    assertEquals(1, eventStatistic.size());
    assertTrue(eventStatisticsManager
            .getTicketSoldStatistics(event.getId(), new Date(0), DateUtils.addDays(new Date(), 1)).isEmpty());
    EventWithAdditionalInfo eventWithAdditionalInfo = eventStatisticsManager
            .getEventWithAdditionalInfo(event.getShortName(), user);
    assertEquals(0, eventWithAdditionalInfo.getNotSoldTickets());
    assertEquals(0, eventWithAdditionalInfo.getSoldTickets());
    assertEquals(20, eventWithAdditionalInfo.getAvailableSeats());

    eventManager.toggleActiveFlag(event.getId(), user, true);
    // list events
    String eventList = eventController.listEvents(new BindingAwareModelMap(), Locale.ENGLISH);
    if (eventManager.getPublishedEvents().size() == 1) {
        Assert.assertTrue(eventList.startsWith("redirect:/"));
    } else {
        assertEquals("/event/event-list", eventList);
    }
    //

    // show event
    String showEvent = eventController.showEvent(eventName, new BindingAwareModelMap(),
            new MockHttpServletRequest(), Locale.ENGLISH);
    assertEquals("/event/show-event", showEvent);
    //

    // check calendar
    checkCalendar(eventName);
    //

    String redirectResult = reserveTicket(eventName);
    String redirectStart = "redirect:/event/" + eventName + "/reservation/";
    // check reservation success
    Assert.assertTrue(redirectResult.startsWith(redirectStart));
    Assert.assertTrue(redirectResult.endsWith("/book"));
    //

    String reservationIdentifier = redirectResult.substring(redirectStart.length()).replace("/book", "");

    // check that the payment page is shown
    String reservationPage = reservationController.showPaymentPage(eventName, reservationIdentifier, null, null,
            null, null, null, null, null, null, null, null, null, new BindingAwareModelMap(), Locale.ENGLISH);
    assertEquals("/event/reservation-page", reservationPage);
    //

    // pay offline
    String successPage = payOffline(eventName, reservationIdentifier);
    assertEquals("redirect:/event/" + eventName + "/reservation/" + reservationIdentifier + "/success",
            successPage);
    //

    //go to success page, payment is still pending
    String confirmationPage = reservationController.showConfirmationPage(eventName, reservationIdentifier,
            false, false, new BindingAwareModelMap(), Locale.ENGLISH, new MockHttpServletRequest());
    Assert.assertTrue(confirmationPage.endsWith("/waitingPayment"));

    assertEquals("/event/reservation-waiting-for-payment", reservationController.showWaitingPaymentPage(
            eventName, reservationIdentifier, new BindingAwareModelMap(), Locale.ENGLISH));

    //
    validatePayment(eventName, reservationIdentifier);
    //

    Assert.assertTrue(reservationController.showWaitingPaymentPage(eventName, reservationIdentifier,
            new BindingAwareModelMap(), Locale.ENGLISH).endsWith("/success"));

    //
    TicketDecorator ticketDecorator = checkReservationComplete(eventName, reservationIdentifier);
    //

    String ticketIdentifier = ticketDecorator.getUuid();

    //ticket is still not assigned, will redirect
    Assert.assertTrue(ticketController
            .showTicket(eventName, ticketIdentifier, false, Locale.ENGLISH, new BindingAwareModelMap())
            .startsWith("redirect:/event/"));
    Assert.assertTrue(ticketController
            .showTicketForUpdate(eventName, ticketIdentifier, new BindingAwareModelMap(), Locale.ENGLISH)
            .startsWith("redirect:/event/"));
    //

    String fname1 = "Test";
    String lname1 = "McTest";

    //assign ticket to person
    assignTicket(eventName, reservationIdentifier, ticketIdentifier, fname1, lname1);

    assertEquals(1, checkInManager.findAllFullTicketInfo(event.getId()).size());

    assertEquals("/event/update-ticket", ticketController.showTicketForUpdate(eventName, ticketIdentifier,
            new BindingAwareModelMap(), Locale.ENGLISH));

    //
    assertEquals("/event/show-ticket", ticketController.showTicket(eventName, ticketIdentifier, false,
            Locale.ENGLISH, new BindingAwareModelMap()));
    //
    checkCSV(eventName, ticketIdentifier, fname1 + " " + lname1);

    // use api to update
    UpdateTicketOwnerForm updateTicketOwnerForm = new UpdateTicketOwnerForm();
    updateTicketOwnerForm.setFirstName("Test");
    updateTicketOwnerForm.setLastName("Testson");
    updateTicketOwnerForm.setEmail("testmctest@test.com");
    updateTicketOwnerForm.setUserLanguage("en");
    reservationApiController.assignTicketToPerson(eventName, ticketIdentifier, true, updateTicketOwnerForm,
            new BeanPropertyBindingResult(updateTicketOwnerForm, "updateTicketForm"),
            new MockHttpServletRequest(), new BindingAwareModelMap(), null);
    checkCSV(eventName, ticketIdentifier, "Test Testson");
    //

    //update
    String fname2 = "Test";
    String lname2 = "OTest";
    assignTicket(eventName, reservationIdentifier, ticketIdentifier, fname2, lname2);
    checkCSV(eventName, ticketIdentifier, fname2 + " " + lname2);

    //lock ticket
    Principal principal = Mockito.mock(Principal.class);
    Mockito.when(principal.getName()).thenReturn(user);
    eventApiController.toggleTicketLocking(eventName, ticketDecorator.getCategoryId(), ticketDecorator.getId(),
            principal);

    assignTicket(eventName, reservationIdentifier, ticketIdentifier, fname1, fname2);
    checkCSV(eventName, ticketIdentifier, fname2 + " " + lname2);

    //ticket has changed, update
    ticketDecorator = checkReservationComplete(eventName, reservationIdentifier);

    // check stats after selling one ticket
    assertFalse(eventStatisticsManager
            .getTicketSoldStatistics(event.getId(), new Date(0), DateUtils.addDays(new Date(), 2)).isEmpty());
    EventWithAdditionalInfo eventWithAdditionalInfo2 = eventStatisticsManager
            .getEventWithAdditionalInfo(event.getShortName(), user);
    assertEquals(0, eventWithAdditionalInfo2.getNotSoldTickets());
    assertEquals(1, eventWithAdditionalInfo2.getSoldTickets());
    assertEquals(20, eventWithAdditionalInfo2.getAvailableSeats());
    assertEquals(0, eventWithAdditionalInfo2.getCheckedInTickets());

    //--- check in sequence
    String ticketCode = ticketDecorator.ticketCode(event.getPrivateKey());
    TicketAndCheckInResult ticketAndCheckInResult = checkInApiController.findTicketWithUUID(event.getId(),
            ticketIdentifier, ticketCode);
    assertEquals(CheckInStatus.OK_READY_TO_BE_CHECKED_IN, ticketAndCheckInResult.getResult().getStatus());
    CheckInApiController.TicketCode tc = new CheckInApiController.TicketCode();
    tc.setCode(ticketCode);
    assertEquals(CheckInStatus.SUCCESS, checkInApiController
            .checkIn(event.getId(), ticketIdentifier, tc, new TestingAuthenticationToken("ciccio", "ciccio"))
            .getResult().getStatus());
    List<ScanAudit> audits = scanAuditRepository.findAllForEvent(event.getId());
    assertFalse(audits.isEmpty());
    assertTrue(audits.stream().anyMatch(sa -> sa.getTicketUuid().equals(ticketIdentifier)));

    TicketAndCheckInResult ticketAndCheckInResultOk = checkInApiController.findTicketWithUUID(event.getId(),
            ticketIdentifier, ticketCode);
    assertEquals(CheckInStatus.ALREADY_CHECK_IN, ticketAndCheckInResultOk.getResult().getStatus());

    // check stats after check in one ticket
    assertFalse(eventStatisticsManager
            .getTicketSoldStatistics(event.getId(), new Date(0), DateUtils.addDays(new Date(), 1)).isEmpty());
    EventWithAdditionalInfo eventWithAdditionalInfo3 = eventStatisticsManager
            .getEventWithAdditionalInfo(event.getShortName(), user);
    assertEquals(0, eventWithAdditionalInfo3.getNotSoldTickets());
    assertEquals(0, eventWithAdditionalInfo3.getSoldTickets());
    assertEquals(20, eventWithAdditionalInfo3.getAvailableSeats());
    assertEquals(1, eventWithAdditionalInfo3.getCheckedInTickets());

    //test revert check in
    assertTrue(checkInApiController.revertCheckIn(event.getId(), ticketIdentifier, principal));
    assertFalse(checkInApiController.revertCheckIn(event.getId(), ticketIdentifier, principal));
    TicketAndCheckInResult ticketAndCheckInResult2 = checkInApiController.findTicketWithUUID(event.getId(),
            ticketIdentifier, ticketCode);
    assertEquals(CheckInStatus.OK_READY_TO_BE_CHECKED_IN, ticketAndCheckInResult2.getResult().getStatus());

    UsersApiController.UserWithPasswordAndQRCode sponsorUser = usersApiController
            .insertUser(new UserModification(null, event.getOrganizationId(), "SPONSOR", "sponsor", "first",
                    "last", "email@email.com"), "http://localhost:8080", principal);
    Principal sponsorPrincipal = Mockito.mock(Principal.class);
    Mockito.when(sponsorPrincipal.getName()).thenReturn(sponsorUser.getUsername());

    // check failures
    assertEquals(CheckInStatus.EVENT_NOT_FOUND,
            attendeeApiController.scanBadge(
                    new AttendeeApiController.SponsorScanRequest("not-existing-event", "not-existing-ticket"),
                    sponsorPrincipal).getBody().getResult().getStatus());
    assertEquals(CheckInStatus.TICKET_NOT_FOUND,
            attendeeApiController
                    .scanBadge(new AttendeeApiController.SponsorScanRequest(eventName, "not-existing-ticket"),
                            sponsorPrincipal)
                    .getBody().getResult().getStatus());
    assertEquals(CheckInStatus.INVALID_TICKET_STATE,
            attendeeApiController
                    .scanBadge(new AttendeeApiController.SponsorScanRequest(eventName, ticketIdentifier),
                            sponsorPrincipal)
                    .getBody().getResult().getStatus());
    //

    // check stats after revert check in one ticket
    assertFalse(eventStatisticsManager
            .getTicketSoldStatistics(event.getId(), new Date(0), DateUtils.addDays(new Date(), 1)).isEmpty());
    EventWithAdditionalInfo eventWithAdditionalInfo4 = eventStatisticsManager
            .getEventWithAdditionalInfo(event.getShortName(), user);
    assertEquals(0, eventWithAdditionalInfo4.getNotSoldTickets());
    assertEquals(1, eventWithAdditionalInfo4.getSoldTickets());
    assertEquals(20, eventWithAdditionalInfo4.getAvailableSeats());
    assertEquals(0, eventWithAdditionalInfo4.getCheckedInTickets());

    CheckInApiController.TicketCode tc2 = new CheckInApiController.TicketCode();
    tc2.setCode(ticketCode);
    TicketAndCheckInResult ticketAndcheckInResult = checkInApiController.checkIn(event.getId(),
            ticketIdentifier, tc2, new TestingAuthenticationToken("ciccio", "ciccio"));
    assertEquals(CheckInStatus.SUCCESS, ticketAndcheckInResult.getResult().getStatus());
    //

    //
    List<Integer> offlineIdentifiers = checkInApiController.getOfflineIdentifiers(event.getShortName(), 0L,
            new MockHttpServletResponse(), principal);
    assertTrue(offlineIdentifiers.isEmpty());
    configurationRepository.insertEventLevel(event.getOrganizationId(), event.getId(),
            ConfigurationKeys.OFFLINE_CHECKIN_ENABLED.name(), "true", null);
    configurationRepository.insert(ConfigurationKeys.ALFIO_PI_INTEGRATION_ENABLED.name(), "true", null);
    offlineIdentifiers = checkInApiController.getOfflineIdentifiers(event.getShortName(), 0L,
            new MockHttpServletResponse(), principal);
    assertFalse(offlineIdentifiers.isEmpty());
    Map<String, String> payload = checkInApiController.getOfflineEncryptedInfo(event.getShortName(),
            Collections.emptyList(), offlineIdentifiers, principal);
    assertEquals(1, payload.size());
    Ticket ticket = ticketAndcheckInResult.getTicket();
    String ticketKey = ticket.hmacTicketInfo(event.getPrivateKey());
    String hashedTicketKey = DigestUtils.sha256Hex(ticketKey);
    String encJson = payload.get(hashedTicketKey);
    assertNotNull(encJson);
    String ticketPayload = CheckInManager.decrypt(ticket.getUuid() + "/" + ticketKey, encJson);
    Map<String, String> jsonPayload = Json.fromJson(ticketPayload, new TypeReference<Map<String, String>>() {
    });
    assertNotNull(jsonPayload);
    assertEquals(8, jsonPayload.size());
    assertEquals("Test", jsonPayload.get("firstName"));
    assertEquals("OTest", jsonPayload.get("lastName"));
    assertEquals("Test OTest", jsonPayload.get("fullName"));
    assertEquals(ticket.getUuid(), jsonPayload.get("uuid"));
    assertEquals("testmctest@test.com", jsonPayload.get("email"));
    assertEquals("CHECKED_IN", jsonPayload.get("status"));
    String categoryName = ticketCategoryRepository.findByEventId(event.getId()).stream().findFirst()
            .orElseThrow(IllegalStateException::new).getName();
    assertEquals(categoryName, jsonPayload.get("category"));
    //

    // check register sponsor scan success flow
    assertTrue(attendeeApiController.getScannedBadges(event.getShortName(),
            EventUtil.JSON_DATETIME_FORMATTER.format(LocalDateTime.of(1970, 1, 1, 0, 0)), sponsorPrincipal)
            .getBody().isEmpty());
    assertEquals(CheckInStatus.SUCCESS,
            attendeeApiController
                    .scanBadge(new AttendeeApiController.SponsorScanRequest(eventName, ticket.getUuid()),
                            sponsorPrincipal)
                    .getBody().getResult().getStatus());
    assertEquals(1,
            attendeeApiController.getScannedBadges(event.getShortName(),
                    EventUtil.JSON_DATETIME_FORMATTER.format(LocalDateTime.of(1970, 1, 1, 0, 0)),
                    sponsorPrincipal).getBody().size());
    //

    eventManager.deleteEvent(event.getId(), principal.getName());

}

From source file:org.finra.herd.rest.JobRestControllerTest.java

/**
 * This is a happy path test for the REST endpoint. All the detailed tests are in the service tier.
 *//* ww w. j a  v a 2 s .  com*/
@Test
public void testGetJobs() throws Exception {
    // Delete all jobs from the history table so we start clean.
    deleteAllHistoricJobs();

    // There should be no jobs initially.
    JobSummaries jobSummaries = jobRestController.getJobs(NO_NAMESPACE, NO_ACTIVITI_JOB_NAME,
            NO_ACTIVITI_JOB_STATUS, NO_START_TIME, NO_END_TIME);
    assertEquals(0, jobSummaries.getJobSummaries().size());

    // Create a "standard" job definition we can run a job against.
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH);

    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setNamespaceAuthorizations(
            new HashSet<>(Arrays.asList(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD,
                    Arrays.asList(NamespacePermissionEnum.values())))));
    SecurityContextHolder.getContext()
            .setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper("username", "", true,
                    true, true, true, Collections.emptyList(), applicationUser), null));

    // Create and start a job that will wait at a User task which will keep it running. Then complete the wait task which will cause the job to complete.
    Job completedJob = jobService.createAndStartJob(
            jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
    List<Task> tasks = activitiTaskService.createTaskQuery().processInstanceId(completedJob.getId()).list();
    activitiTaskService.complete(tasks.get(0).getId());

    // Query all the jobs which will have all 3 jobs created.
    jobSummaries = jobRestController.getJobs(NO_NAMESPACE, NO_ACTIVITI_JOB_NAME, NO_ACTIVITI_JOB_STATUS,
            NO_START_TIME, NO_END_TIME);
    assertEquals(1, jobSummaries.getJobSummaries().size());

    // Get the job summary and perform some validation.
    JobSummary jobSummary = jobSummaries.getJobSummaries().get(0);
    assertNotNull(jobSummary.getStartTime()); // Ensure a start time is present (all jobs must have a start time).
    assertNotNull(jobSummary.getEndTime()); // Ensure that the job has an end time since it's completed.
    assertEquals(TEST_ACTIVITI_NAMESPACE_CD, jobSummary.getNamespace()); // Namespace should match the query filter.
    assertEquals(TEST_ACTIVITI_JOB_NAME, jobSummary.getJobName()); // Job name should match the query filter.
    assertEquals(JobStatusEnum.COMPLETED, jobSummary.getStatus()); // Make sure the status is running to match the filter.
    assertEquals(0, jobSummary.getTotalExceptions()); // No exceptions should be present.
}

From source file:org.finra.herd.service.JobServiceTest.java

@Test
public void testDeleteJobAssertAccessDeniedWhenUserHasNoPermissions() throws Exception {
    // Start a job that will wait in a receive task
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH);
    Job job = jobService.createAndStartJob(
            jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext()// w  ww  .j  av a  2 s . com
            .setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(username, "password",
                    false, false, false, false, Collections.emptyList(), applicationUser), null));

    try {
        jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason"));
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(
                String.format("User \"%s\" does not have \"[EXECUTE]\" permission(s) to the namespace \"%s\"",
                        username, TEST_ACTIVITI_NAMESPACE_CD),
                e.getMessage());
    }
}

From source file:org.finra.herd.service.JobServiceTest.java

@Test
public void testDeleteJobAssertNoErrorWhenUserHasPermissions() throws Exception {
    // Start a job that will wait in a receive task
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH);
    Job job = jobService.createAndStartJob(
            jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD,
            Arrays.asList(NamespacePermissionEnum.EXECUTE)));
    SecurityContextHolder.getContext()//w ww  .  j  ava  2s . c o m
            .setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(username, "password",
                    false, false, false, false, Collections.emptyList(), applicationUser), null));

    try {
        jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason"));
    } catch (AccessDeniedException e) {
        fail();
    }
}

From source file:org.finra.herd.service.JobServiceTest.java

@Test
public void testGetJobAssertAccessDeniedGivenJobCompletedAndUserDoesNotHavePermissions() throws Exception {
    jobDefinitionServiceTestHelper.createJobDefinition(null);
    Job job = jobService.createAndStartJob(
            jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext()/*  www  .  j  a v  a  2 s  . co  m*/
            .setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(username, "password",
                    false, false, false, false, Collections.emptyList(), applicationUser), null));

    try {
        jobService.getJob(job.getId(), false);
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"",
                username, TEST_ACTIVITI_NAMESPACE_CD), e.getMessage());
    }
}

From source file:org.finra.herd.service.JobServiceTest.java

@Test
public void testGetJobAssertNoErrorGivenJobCompletedAndUserDoesHasPermissions() throws Exception {
    jobDefinitionServiceTestHelper.createJobDefinition(null);
    Job job = jobService.createAndStartJob(
            jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String username = "username";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(username);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD,
            Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext()//www .j a  v  a2s. com
            .setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(username, "password",
                    false, false, false, false, Collections.emptyList(), applicationUser), null));

    try {
        jobService.getJob(job.getId(), false);
    } catch (AccessDeniedException e) {
        fail();
    }
}