javax.ws.rs.NotFoundException Java Examples

The following examples show how to use javax.ws.rs.NotFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SdxRepairService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #2
Source File: RealmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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
    }
}
 
Example #3
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: AuthServerTestEnricher.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #5
Source File: ServiceTemplateInstanceController.java    From container with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: CertificationResource.java    From clouditor with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: DocumentClientService.java    From yaas_java_jersey_wishlist with Apache License 2.0 6 votes vote down vote up
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);
    }
 
Example #8
Source File: GoogleAssetResourceIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@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");
    }

}
 
Example #9
Source File: AccountCredentialResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
    }
}
 
Example #10
Source File: ClientResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example #11
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @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);
}
 
Example #12
Source File: PortChainResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * 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"));
    }
}
 
Example #13
Source File: JAXRSClientMetricsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #14
Source File: UserStorageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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
    }
}
 
Example #15
Source File: JobResource.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@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));
  }
}
 
Example #16
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #17
Source File: DocumentClientService.java    From yaas_java_jersey_wishlist with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #18
Source File: AutomationClientResource.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #19
Source File: StatsRestServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #20
Source File: DeviceKeyWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: DoctorKafkaApi.java    From doctorkafka with Apache License 2.0 5 votes vote down vote up
protected KafkaClusterManager checkAndGetClusterManager(String clusterName) {
  KafkaClusterManager clusterManager = drkafka.getClusterManager(clusterName);
  if (clusterManager == null) {
    throw new NotFoundException("Unknown clustername:" + clusterName);
  }
  return clusterManager;
}
 
Example #22
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get authenticator configuration
 * @param id Configuration id
 */
@Path("config/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public AuthenticatorConfigRepresentation getAuthenticatorConfig(@PathParam("id") String id) {
    auth.realm().requireViewRealm();

    AuthenticatorConfigModel config = realm.getAuthenticatorConfigById(id);
    if (config == null) {
        throw new NotFoundException("Could not find authenticator config");

    }
    return ModelToRepresentation.toRepresentation(config);
}
 
Example #23
Source File: TestingResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/remove-user-session")
@Produces(MediaType.APPLICATION_JSON)
public Response removeUserSession(@QueryParam("realm") final String name, @QueryParam("session") final String sessionId) {
    RealmModel realm = getRealmByName(name);

    UserSessionModel sessionModel = session.sessions().getUserSession(realm, sessionId);
    if (sessionModel == null) {
        throw new NotFoundException("Session not found");
    }

    session.sessions().removeUserSession(realm, sessionModel);
    return Response.noContent().build();
}
 
Example #24
Source File: UserStorageProviderResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger sync of mapper data related to ldap mapper (roles, groups, ...)
 *
 * direction is "fedToKeycloak" or "keycloakToFed"
 *
 * @return
 */
@POST
@Path("{parentId}/mappers/{id}/sync")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public SynchronizationResult syncMapperData(@PathParam("parentId") String parentId, @PathParam("id") String mapperId, @QueryParam("direction") String direction) {
    auth.users().requireManage();

    ComponentModel parentModel = realm.getComponent(parentId);
    if (parentModel == null) throw new NotFoundException("Parent model not found");
    ComponentModel mapperModel = realm.getComponent(mapperId);
    if (mapperModel == null) throw new NotFoundException("Mapper model not found");

    LDAPStorageProvider ldapProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, parentModel);
    LDAPStorageMapper mapper = session.getProvider(LDAPStorageMapper.class, mapperModel);

    ServicesLogger.LOGGER.syncingDataForMapper(mapperModel.getName(), mapperModel.getProviderId(), direction);

    SynchronizationResult syncResult;
    if ("fedToKeycloak".equals(direction)) {
        syncResult = mapper.syncDataFromFederationProviderToKeycloak(realm);
    } else if ("keycloakToFed".equals(direction)) {
        syncResult = mapper.syncDataFromKeycloakToFederationProvider(realm);
    } else {
        throw new BadRequestException("Unknown direction: " + direction);
    }

    Map<String, Object> eventRep = new HashMap<>();
    eventRep.put("action", direction);
    eventRep.put("result", syncResult);
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(eventRep).success();
    return syncResult;
}
 
Example #25
Source File: RealmsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private RealmModel init(String realmName) {
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotFoundException("Realm does not exist");
    }
    session.getContext().setRealm(realm);
    return realm;
}
 
Example #26
Source File: FederatedStorageExportImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@After
public void cleanup() {
    try {
        testRealmResource().remove();
    } catch (NotFoundException ignore) {
    }
}
 
Example #27
Source File: StormtrooperResource.java    From okta-auth-java with Apache License 2.0 5 votes vote down vote up
@GET
    @Path("/{id}")
//    @RequiresPermissions("trooper:read")
    public Stormtrooper getTrooper(@PathParam("id") String id) {

        Stormtrooper stormtrooper = trooperDao.getStormtrooper(id);
        if (stormtrooper == null) {
            throw new NotFoundException();
        }
        return stormtrooper;
    }
 
Example #28
Source File: ClientResource.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
private Client findClient(Long id) {
	Client found = Client.findById( id );
	if ( found == null ) {
		throw new NotFoundException();
	}
	return found;
}
 
Example #29
Source File: Catalog.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getBook(@PathParam("id") final String id) throws IOException {
    final JsonObject book = store.get(id);

    if (book == null) {
        throw new NotFoundException("Book with does not exists: " + id);
    }

    return book;
}
 
Example #30
Source File: AccountsResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@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;
}