下面列出了怎么用javax.ws.rs.NotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Tests that a fetch of a non-existent port chain object throws an exception.
*/
@Test
public void testBadGet() {
expect(portChainService.getPortChain(anyObject()))
.andReturn(null).anyTimes();
replay(portChainService);
WebTarget wt = target();
try {
wt.path("port_chains/78dcd363-fc23-aeb6-f44b-56dc5aafb3ae")
.request().get(String.class);
fail("Fetch of non-existent port chain did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(),
containsString("HTTP 404 Not Found"));
}
}
public static void removeTestRealms(TestContext testContext, Keycloak adminClient) {
List<RealmRepresentation> testRealmReps = testContext.getTestRealmReps();
if (testRealmReps != null && !testRealmReps.isEmpty()) {
log.info("removing test realms after test class");
StringBuilder realms = new StringBuilder();
for (RealmRepresentation testRealm : testRealmReps) {
try {
adminClient.realms().realm(testRealm.getRealm()).remove();
realms.append(testRealm.getRealm()).append(", ");
} catch (NotFoundException e) {
// Ignore
}
}
log.info("removed realms: " + realms);
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/")
public Certification getCertification(@PathParam(value = "id") String certificationId) {
certificationId = sanitize(certificationId);
var certifications = this.service.getCertifications();
var certification = certifications.get(certificationId);
if (certification == null) {
throw new NotFoundException();
}
return certification;
}
@Test
public void ensureMissingFileReturns404() {
Map<String, String> payload = hashMap("name", "assettest");
ApiResponse postResponse = pathResource(getOrgAppPath("missingFile")).post(payload);
UUID assetId = postResponse.getEntities().get(0).getUuid();
assertNotNull(assetId);
try {
pathResource(getOrgAppPath("missingFile/assettest")).getAssetAsStream(true);
fail("Should fail as there isn't an asset to retrieve.");
} catch (NotFoundException nfe) {
} catch (Exception e) {
logger.error("Unexpected exception", e);
fail("Shouldn't return any other kind of exception");
}
}
/**
* Update a user label of specified credential of current user
*
* @param credentialId ID of the credential, which will be updated
* @param userLabel new user label as JSON string
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("{credentialId}/label")
@NoCache
public void setLabel(final @PathParam("credentialId") String credentialId, String userLabel) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId);
if (credential == null) {
throw new NotFoundException("Credential not found");
}
try {
String label = JsonSerialization.readValue(userLabel, String.class);
session.userCredentialManager().updateCredentialLabel(realm, user, credentialId, label);
} catch (IOException ioe) {
throw new ErrorResponseException(ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST));
}
}
public void deleteWishlist(final YaasAwareParameters yaasAware, final String wishlistId, final AccessToken token) {
final Response response = documentClient
.tenant(yaasAware.getHybrisTenant())
.client(client)
.dataType(WISHLIST_PATH)
.dataId(wishlistId)
.prepareDelete()
.withAuthorization(token.toAuthorizationHeaderValue())
.execute();
if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) {
return;
} else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
throw new NotFoundException("Cannot find wishlist with ID " + wishlistId, response);
}
throw ErrorHandler.resolveErrorResponse(response, token);
}
@GET
@Path("/{id}/results")
public JobResourceData getQueryResults(@PathParam("id") String id, @QueryParam("offset") @DefaultValue("0") Integer offset, @Valid @QueryParam("limit") @DefaultValue("100") Integer limit) {
Preconditions.checkArgument(limit <= 500,"limit can not exceed 500 rows");
try {
JobSummaryRequest request = JobSummaryRequest.newBuilder()
.setJobId(JobProtobuf.JobId.newBuilder().setId(id).build())
.setUserName(securityContext.getUserPrincipal().getName())
.build();
JobSummary jobSummary = jobs.getJobSummary(request);
if (jobSummary.getJobState() != JobState.COMPLETED) {
throw new BadRequestException(String.format("Can not fetch details for a job that is in [%s] state.", jobSummary.getJobState()));
}
// Additional wait not necessary since we check for job completion via JobState
return new JobResourceData(jobs, jobSummary, securityContext.getUserPrincipal().getName(),
getOrCreateAllocator("getQueryResults"), offset, limit);
} catch (JobNotFoundException e) {
throw new NotFoundException(String.format("Could not find a job with id [%s]", id));
}
}
@Test
public void usingClientProxyStopIsCalledWhenServerReturnsNotFound() throws Exception {
final JAXRSClientFactoryBean factory = new JAXRSClientFactoryBean();
factory.setResourceClass(Library.class);
factory.setAddress("http://localhost:" + wireMockRule.port() + "/");
factory.setFeatures(Arrays.asList(new MetricsFeature(provider)));
factory.setProvider(JacksonJsonProvider.class);
stubFor(get(urlEqualTo("/books/10"))
.willReturn(aResponse()
.withStatus(404)));
try {
final Library client = factory.create(Library.class);
expectedException.expect(NotFoundException.class);
client.getBook(10);
} finally {
Mockito.verify(resourceContext, times(1)).start(any(Exchange.class));
Mockito.verify(resourceContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
Mockito.verify(endpointContext, times(1)).start(any(Exchange.class));
Mockito.verify(endpointContext, times(1)).stop(anyLong(), anyLong(), anyLong(), any(Exchange.class));
Mockito.verifyNoInteractions(operationContext);
}
}
protected AttemptResult<StackV4Response> checkClusterStatusDuringRepair(SdxCluster sdxCluster) throws JsonProcessingException {
LOGGER.info("Repair polling cloudbreak for stack status: '{}' in '{}' env", sdxCluster.getClusterName(), sdxCluster.getEnvName());
try {
if (PollGroup.CANCELLED.equals(DatalakeInMemoryStateStore.get(sdxCluster.getId()))) {
LOGGER.info("Repair polling cancelled in inmemory store, id: " + sdxCluster.getId());
return AttemptResults.breakFor("Repair polling cancelled in inmemory store, id: " + sdxCluster.getId());
}
FlowState flowState = cloudbreakFlowService.getLastKnownFlowState(sdxCluster);
if (RUNNING.equals(flowState)) {
LOGGER.info("Repair polling will continue, cluster has an active flow in Cloudbreak, id: " + sdxCluster.getId());
return AttemptResults.justContinue();
} else {
return getStackResponseAttemptResult(sdxCluster, flowState);
}
} catch (NotFoundException e) {
LOGGER.debug("Stack not found on CB side " + sdxCluster.getClusterName(), e);
return AttemptResults.breakFor("Stack not found on CB side " + sdxCluster.getClusterName());
}
}
@Test
public void testRegistration() {
UserRepresentation memuser = new UserRepresentation();
memuser.setUsername("memuser");
String uid = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealmResource(), memuser, "password");
loginSuccessAndLogout("memuser", "password");
loginSuccessAndLogout("memuser", "password");
loginSuccessAndLogout("memuser", "password");
memuser = user(uid).toRepresentation();
assertNotNull(memuser);
assertNotNull(memuser.getOrigin());
ComponentRepresentation origin = testRealmResource().components().component(memuser.getOrigin()).toRepresentation();
Assert.assertEquals("memory", origin.getName());
testRealmResource().users().get(memuser.getId()).remove();
try {
user(uid).toRepresentation(); // provider doesn't implement UserQueryProvider --> have to lookup by uid
fail("`memuser` wasn't removed");
} catch (NotFoundException nfe) {
// expected
}
}
private void deleteFlow(String id, boolean isTopMostLevel) {
AuthenticationFlowModel flow = realm.getAuthenticationFlowById(id);
if (flow == null) {
throw new NotFoundException("Could not find flow with id");
}
if (flow.isBuiltIn()) {
throw new BadRequestException("Can't delete built in flow");
}
List<AuthenticationExecutionModel> executions = realm.getAuthenticationExecutions(id);
for (AuthenticationExecutionModel execution : executions) {
if(execution.getFlowId() != null) {
deleteFlow(execution.getFlowId(), false);
}
}
realm.removeAuthenticationFlow(flow);
// Use just one event for top-level flow. Using separate events won't work properly for flows of depth 2 or bigger
if (isTopMostLevel) adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).success();
}
/**
* Retrieve Client by ID
*
* @param automationClient the client with automation access performing this operation
* @param clientId the ID of the Client to retrieve
* @return the specified client, if found
*
* description Returns a single Client if found
* responseMessage 200 Found and retrieved Client with given ID
* responseMessage 404 Client with given ID not Found
*/
@Timed @ExceptionMetered
@GET
@Path("{clientId}")
public Response findClientById(
@Auth AutomationClient automationClient,
@PathParam("clientId") LongParam clientId) {
logger.info("Automation ({}) - Looking up an ID {}", automationClient.getName(), clientId);
Client client = clientDAO.getClientById(clientId.get())
.orElseThrow(NotFoundException::new);
ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(client));
return Response.ok()
.entity(ClientDetailResponse.fromClient(client, groups, ImmutableList.of()))
.build();
}
@GET
@Path("/static/{resource:.*}")
public Response getResource(@Context UriInfo uriInfo, @PathParam("resource") String resourcePath) {
if (resourcePath.contains("favicon")) {
return Response.status(404).build();
}
try {
final URL resourceURL = getClass().getResource("/web-ui/" + resourcePath);
final ResponseBuilder rb = Response.ok(resourceURL.openStream());
int ind = resourcePath.lastIndexOf('.');
if (ind != -1 && ind < resourcePath.length()) {
String ext = resourcePath.substring(ind + 1);
if ("js".equalsIgnoreCase(ext)) {
rb.type("application/javascript");
} else {
rb.type(MediaType.TEXT_HTML);
}
}
return rb.build();
} catch (IOException ex) {
throw new NotFoundException(ex);
}
}
/**
*
* @param scopeParam
* @param roleContainerId either realm name OR client UUID
* @return
*/
@Path("scope-mappings/{roleContainerId}")
public ClientScopeEvaluateScopeMappingsResource scopeMappings(@QueryParam("scope") String scopeParam, @PathParam("roleContainerId") String roleContainerId) {
auth.clients().requireView(client);
if (roleContainerId == null) {
throw new NotFoundException("No roleContainerId provided");
}
RoleContainerModel roleContainer = roleContainerId.equals(realm.getName()) ? realm : realm.getClientById(roleContainerId);
if (roleContainer == null) {
throw new NotFoundException("Role Container not found");
}
return new ClientScopeEvaluateScopeMappingsResource(roleContainer, auth, client, scopeParam, session);
}
/**
* Tests that a GET of a non-existent object throws an exception.
*/
@Test
public void testGetNonExistentDeviceKey() {
expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1)))
.andReturn(null)
.anyTimes();
replay(mockDeviceKeyService);
WebTarget wt = target();
try {
wt.path("keys/" + deviceKeyId1).request().get(String.class);
fail("GET of a non-existent device key did not throw an exception");
} catch (NotFoundException ex) {
assertThat(ex.getMessage(), containsString("HTTP 404 Not Found"));
}
verify(mockDeviceKeyService);
}
/**
* Modify a client
*
* @param currentName Client name
* @param request JSON request to modify the client
* @return the updated client
* <p>
* responseMessage 201 Client updated
* <p>
* responseMessage 404 Client not found
*/
@Timed @ExceptionMetered
@POST
@Path("{name}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public ClientDetailResponseV2 modifyClient(@Auth AutomationClient automationClient,
@PathParam("name") String currentName, @Valid ModifyClientRequestV2 request) {
Client client = clientDAOReadWrite.getClientByName(currentName)
.orElseThrow(NotFoundException::new);
String newName = request.name();
// TODO: implement change client (name, updatedAt, updatedBy)
throw new NotImplementedException(format(
"Need to implement mutation methods in DAO to rename %s to %s", client.getName(), newName));
}
public Wishlist getWishlist(final YaasAwareParameters yaasAware, final String id, final AccessToken token) {
final Response response = documentClient
.tenant(yaasAware.getHybrisTenant())
.client(client)
.dataType(WISHLIST_PATH)
.dataId(id)
.prepareGet()
.withAuthorization(token.toAuthorizationHeaderValue())
.execute();
if (response.getStatus() == Status.OK.getStatusCode()) {
final DocumentWishlist documentWishlist = response.readEntity(DocumentWishlist.class);
final Wishlist wishlist = documentWishlist.getWishlist();
wishlist.setCreatedAt(documentWishlist.getMetadata().getCreatedAt());
return wishlist;
} else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
throw new NotFoundException("Cannot find wishlist with ID " + id, response);
}
throw ErrorHandler.resolveErrorResponse(response, token);
}
/**
* Delete authenticator configuration
* @param id Configuration id
*/
@Path("config/{id}")
@DELETE
@NoCache
public void removeAuthenticatorConfig(@PathParam("id") String id) {
auth.realm().requireManageRealm();
AuthenticatorConfigModel config = realm.getAuthenticatorConfigById(id);
if (config == null) {
throw new NotFoundException("Could not find authenticator config");
}
for (AuthenticationFlowModel flow : realm.getAuthenticationFlows()) {
for (AuthenticationExecutionModel exe : realm.getAuthenticationExecutions(flow.getId())) {
if (id.equals(exe.getAuthenticatorConfig())) {
exe.setAuthenticatorConfig(null);
realm.updateAuthenticatorExecution(exe);
}
}
}
realm.removeAuthenticatorConfig(config);
adminEvent.operation(OperationType.DELETE).resource(ResourceType.AUTHENTICATOR_CONFIG).resourcePath(session.getContext().getUri()).success();
}
@Test
// KEYCLOAK-1110
public void deleteDefaultRole() {
RoleRepresentation role = new RoleRepresentation("test", "test", false);
realm.roles().create(role);
assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourcePath("test"), role, ResourceType.REALM_ROLE);
assertNotNull(realm.roles().get("test").toRepresentation());
RealmRepresentation rep = realm.toRepresentation();
rep.setDefaultRoles(new LinkedList<String>());
rep.getDefaultRoles().add("test");
realm.update(rep);
assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, Matchers.nullValue(String.class), rep, ResourceType.REALM);
realm.roles().deleteRole("test");
assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.roleResourcePath("test"), ResourceType.REALM_ROLE);
try {
realm.roles().get("testsadfsadf").toRepresentation();
fail("Expected NotFoundException");
} catch (NotFoundException e) {
// Expected
}
}
@POST
@Path("/{id}/deploymenttests")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(hidden = true, value = "")
public Response createDeploymentTest(@PathParam("id") final Integer id) {
logger.debug("Invoking createDeploymentTest");
// TODO: Check if instance belongs to CSAR and Service Template
final ServiceTemplateInstance sti = new ServiceTemplateInstanceRepository().find(Long.valueOf(id)).orElse(null);
if (sti == null) {
logger.info("Service template instance \"" + id + "\" of template \"" + serviceTemplate.getId()
+ "\" could not be found");
throw new NotFoundException("Service template instance \"" + id + "\" of template \""
+ serviceTemplate.getId() + "\" could not be found");
}
final DeploymentTest result = this.deploymentTestService.run(csar.id(), sti);
final URI location = this.uriInfo.getAbsolutePathBuilder().path(String.valueOf(result.getId())).build();
return Response.created(UriUtil.encode(location)).build();
}
@GET
@Path("{provider}")
public CloudAccount getAccount(@PathParam("provider") String provider) {
provider = sanitize(provider);
var account = this.service.getAccount(provider);
if (account == null) {
throw new NotFoundException();
}
return account;
}
@POST
@Path("{id}/disable")
public void disable(@PathParam("id") String id) {
id = sanitize(id);
var scan = service.getScan(id);
if (scan == null) {
LOGGER.error("Could not find scan with id {}", id);
throw new NotFoundException("Could not find scan with id " + id);
}
service.disableScan(scan);
}
/**
* Generate new client scope for specified service client. The "Frontend" clients, who will use this client scope, will be able to
* send their access token to authenticate against specified service client
*
* @param clientId Client ID of service client (typically bearer-only client)
* @return ID of the newly generated clientScope
*/
@Path("generate-audience-client-scope")
@POST
@NoCache
public String generateAudienceClientScope(@QueryParam("realm") final String realmName, final @QueryParam("clientId") String clientId) {
try {
RealmModel realm = getRealmByName(realmName);
ClientModel serviceClient = realm.getClientByClientId(clientId);
if (serviceClient == null) {
throw new NotFoundException("Referenced service client doesn't exists");
}
ClientScopeModel clientScopeModel = realm.addClientScope(clientId);
clientScopeModel.setProtocol(serviceClient.getProtocol()==null ? OIDCLoginProtocol.LOGIN_PROTOCOL : serviceClient.getProtocol());
clientScopeModel.setDisplayOnConsentScreen(true);
clientScopeModel.setConsentScreenText(clientId);
clientScopeModel.setIncludeInTokenScope(true);
// Add audience protocol mapper
ProtocolMapperModel audienceMapper = AudienceProtocolMapper.createClaimMapper("Audience for " + clientId, clientId, null,true, false);
clientScopeModel.addProtocolMapper(audienceMapper);
return clientScopeModel.getId();
} catch (ModelDuplicateException e) {
throw new BadRequestException("Client Scope " + clientId + " already exists");
}
}
@Test
void startProvisioning() {
long clusterId = CLUSTER_ID.incrementAndGet();
SdxCluster sdxCluster = generateValidSdxCluster(clusterId);
StackV4Response stackV4Response = new StackV4Response();
when(stackV4Endpoint.getByCrn(anyLong(), nullable(String.class), nullable(Set.class))).thenThrow(new NotFoundException());
when(stackV4Endpoint.post(anyLong(), any(StackV4Request.class))).thenReturn(stackV4Response);
when(sdxClusterRepository.findById(clusterId)).thenReturn(Optional.of(sdxCluster));
underTest.startStackProvisioning(clusterId, getEnvironmentResponse());
verify(cloudbreakFlowService).saveLastCloudbreakFlowChainId(sdxCluster, stackV4Response.getFlowIdentifier());
verify(sdxClusterRepository, times(1)).save(any(SdxCluster.class));
}
public HadoopAmbariCluster(ClusterResource cluster) {
this.cluster = cluster;
this.services = cluster.getServicesResource();
try {
cluster.getConfigsResource().hasConfig();
} catch (NotFoundException noe) {
supportSCV = false;
}
}
/**
* Get realm-level roles of the role's composite
*
* @param roleName role's name (not id!)
* @return
*/
@Path("{role-name}/composites/realm")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Set<RoleRepresentation> getRealmRoleComposites(final @PathParam("role-name") String roleName) {
auth.roles().requireView(roleContainer);
RoleModel role = roleContainer.getRole(roleName);
if (role == null) {
throw new NotFoundException("Could not find role");
}
return getRealmRoleComposites(role);
}
private boolean hasFlow() {
try {
return getTestContext().getCloudbreakClient().getCloudbreakClient()
.flowEndpoint()
.getFlowLogsByResourceName(getName()).stream().anyMatch(flowentry -> !flowentry.getFinalized());
} catch (NotFoundException e) {
return false;
}
}
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") final String id) throws IOException {
if (!store.remove(id)) {
throw new NotFoundException("Book with does not exists: " + id);
}
return Response.ok().build();
}
@Override
public void getApplication(String applicationIdString) {
ApplicationId appId = toApplicationId(applicationIdString);
ApplicationInstanceStatus status;
try {
status = orchestrator.getApplicationInstanceStatus(appId);
} catch (ApplicationIdNotFoundException e) {
throw new NotFoundException("Application " + applicationIdString + " could not be found");
}
if (status.equals(ApplicationInstanceStatus.NO_REMARKS)) {
throw new NotFoundException("Application " + applicationIdString + " is not suspended");
}
// Return void as we have nothing to return except 204 No
// Content. Unfortunately, Jersey outputs a warning for this case:
//
// The following warnings have been detected: HINT: A HTTP GET
// method, public void com.yahoo.vespa.orchestrator.resources.
// ApplicationSuspensionResource.getApplication(java.lang.String),
// returns a void type. It can be intentional and perfectly fine,
// but it is a little uncommon that GET method returns always "204
// No Content"
//
// We have whitelisted the warning for our systemtests.
//
// bakksjo has a pending jersey PR fix that avoids making the hint
// become a warning:
// https://github.com/jersey/jersey/pull/212
//
// TODO: Remove whitelisting and this comment once jersey has been
// fixed.
}
/**
* Retrieves the node ID of the document library of a particular site, creating the site, if it does not exist.
*
* @param client
* the client to use for making ReST API calls
* @param baseUrl
* the base URL of the Alfresco instance
* @param ticket
* the authentication ticket to use for calls to the ResT APIs
* @param siteId
* the ID of the site to retrieve / create
* @param siteTitle
* the title of the site to use if this operation cannot find an existing site and creates one lazily
* @return the node ID of the document library
*/
protected static String getOrCreateSiteAndDocumentLibrary(final ResteasyClient client, final String baseUrl, final String ticket,
final String siteId, final String siteTitle)
{
final SitesV1 sites = createAPI(client, baseUrl, SitesV1.class, ticket);
SiteResponseEntity site = null;
try
{
site = sites.getSite(siteId);
}
catch (final NotFoundException ignore)
{
// getOrCreate implies that site might not exist (yet)
}
if (site == null)
{
final SiteCreationRequestEntity siteToCreate = new SiteCreationRequestEntity();
siteToCreate.setId(siteId);
siteToCreate.setTitle(siteTitle);
siteToCreate.setVisibility(SiteVisibility.PUBLIC);
site = sites.createSite(siteToCreate, true, true, null);
}
final SiteContainerResponseEntity documentLibrary = sites.getSiteContainer(site.getId(), SiteService.DOCUMENT_LIBRARY);
return documentLibrary.getId();
}