下面列出了javax.ws.rs.core.Response.Status#FORBIDDEN 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(path = "/add", method = RequestMethod.GET)
public int add(int x, int y) {
if (x == 99) {
throw new NullPointerException("un expected NPE test.");
}
if (x == 88) {
ErrorData data = new ErrorData();
data.setId(12);
data.setMessage("not allowed id.");
throw new InvocationException(Status.FORBIDDEN, data);
}
if (x == 77) {
throw new IllegalStateException("77");
}
return x + y;
}
/**
* Checks whether the broker is allowed to do read-write operations based on the existence of a node in global
* zookeeper.
*
* @throws WebApplicationException
* if broker has a read only access if broker is not connected to the global zookeeper
*/
public void validatePoliciesReadOnlyAccess() {
boolean arePoliciesReadOnly = true;
try {
arePoliciesReadOnly = globalZkCache().exists(POLICIES_READONLY_FLAG_PATH);
} catch (Exception e) {
log.warn("Unable to fetch contents of [{}] from global zookeeper", POLICIES_READONLY_FLAG_PATH, e);
throw new RestException(e);
}
if (arePoliciesReadOnly) {
log.debug("Policies are read-only. Broker cannot do read-write operations");
throw new RestException(Status.FORBIDDEN, "Broker is forbidden to do read-write operations");
} else {
// Make sure the broker is connected to the global zookeeper before writing. If not, throw an exception.
if (globalZkCache().getZooKeeper().getState() != States.CONNECTED) {
log.debug("Broker is not connected to the global zookeeper");
throw new RestException(Status.PRECONDITION_FAILED,
"Broker needs to be connected to global zookeeper before making a read-write operation");
} else {
// Do nothing, just log the message.
log.debug("Broker is allowed to make read-write operations");
}
}
}
/**
* deletes a whole derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - the MyCoRe Object ID
* @param pathParamMcrDerID - the MyCoRe Derivate ID
* @return a Jersey Response Object
* @throws MCRRestAPIException
*/
public static Response deleteDerivate(UriInfo info, HttpServletRequest request, String pathParamMcrObjID,
String pathParamMcrDerID) throws MCRRestAPIException {
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
try {
MCRMetadataManager.deleteMCRDerivate(derID);
return Response
.created(info.getBaseUriBuilder().path("objects/" + objID + "/derivates").build())
.type("application/xml; charset=UTF-8")
.build();
} catch (MCRAccessException e) {
throw new MCRRestAPIException(Status.FORBIDDEN,
new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "Could not delete derivate", e.getMessage()));
}
}
protected void validateClusterForTenant(String tenant, String cluster) {
TenantInfo tenantInfo;
try {
tenantInfo = pulsar().getConfigurationCache().propertiesCache().get(path(POLICIES, tenant))
.orElseThrow(() -> new RestException(Status.NOT_FOUND, "Tenant does not exist"));
} catch (Exception e) {
log.error("Failed to get tenant admin data for tenant");
throw new RestException(e);
}
// Check if tenant is allowed on the cluster
if (!tenantInfo.getAllowedClusters().contains(cluster)) {
String msg = String.format("Cluster [%s] is not in the list of allowed clusters list for tenant [%s]",
cluster, tenant);
log.info(msg);
throw new RestException(Status.FORBIDDEN, msg);
}
log.info("Successfully validated clusters on tenant [{}]", tenant);
}
@Deprecated
@GET
@Path("tables/{tableName}/segments")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get a map from server to segments hosted by the server (deprecated, use 'GET /segments/{tableName}/servers' instead)", notes = "Get a map from server to segments hosted by the server (deprecated, use 'GET /segments/{tableName}/servers' instead)")
public List<Map<String, String>> getServerToSegmentsMapDeprecated1(
@ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName,
@ApiParam(value = "MUST be null") @QueryParam("state") String stateStr,
@ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr)
throws JsonProcessingException {
if (stateStr != null) {
throw new WebApplicationException("Cannot toggle segment state", Status.FORBIDDEN);
}
List<String> tableNamesWithType =
getExistingTableNamesWithType(tableName, Constants.validateTableType(tableTypeStr));
List<Map<String, String>> resultList = new ArrayList<>(tableNamesWithType.size());
for (String tableNameWithType : tableNamesWithType) {
// NOTE: DO NOT change the format for backward-compatibility
Map<String, String> resultForTable = new LinkedHashMap<>();
resultForTable.put("tableName", tableNameWithType);
resultForTable.put("segments",
JsonUtils.objectToString(_pinotHelixResourceManager.getServerToSegmentsMap(tableNameWithType)));
resultList.add(resultForTable);
}
return resultList;
}
private KeycloakIdentity createIdentity(boolean checkProtectionScope) {
KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
ResourceServer resourceServer = getResourceServer(identity);
KeycloakSession keycloakSession = authorization.getKeycloakSession();
RealmModel realm = keycloakSession.getContext().getRealm();
ClientModel client = realm.getClientById(resourceServer.getId());
if (checkProtectionScope) {
if (!identity.hasClientRole(client.getClientId(), "uma_protection")) {
throw new ErrorResponseException(OAuthErrorException.INVALID_SCOPE, "Requires uma_protection scope.", Status.FORBIDDEN);
}
}
return identity;
}
@Override
public Response toResponse(AuthenticationException exception) {
Status status = Status.FORBIDDEN;
ApiErrorDetails errorDetails = new ApiErrorDetails();
errorDetails.setStatus(status.getStatusCode());
errorDetails.setTitle(status.getReasonPhrase());
errorDetails.setMessage(exception.getMessage());
errorDetails.setPath(uriInfo.getAbsolutePath().getPath());
return Response.status(status).entity(errorDetails).type(MediaType.APPLICATION_JSON).build();
}
@Override
public Response toResponse(AuthenticationTokenRefreshmentException exception) {
Status status = Status.FORBIDDEN;
ApiErrorDetails errorDetails = new ApiErrorDetails();
errorDetails.setStatus(status.getStatusCode());
errorDetails.setTitle(status.getReasonPhrase());
errorDetails.setMessage("The authentication token cannot be refreshed.");
errorDetails.setPath(uriInfo.getAbsolutePath().getPath());
return Response.status(status).entity(errorDetails).type(MediaType.APPLICATION_JSON).build();
}
@Test
public void testAfterReceiveResponseNullProduceProcessor(@Mocked Invocation invocation,
@Mocked HttpServletResponseEx responseEx,
@Mocked OperationMeta operationMeta,
@Mocked RestOperationMeta swaggerRestOperation) throws Exception {
CommonExceptionData data = new CommonExceptionData("abcd");
new Expectations() {
{
invocation.getOperationMeta();
result = operationMeta;
operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
result = swaggerRestOperation;
invocation.findResponseType(403);
result = SimpleType.constructUnsafe(CommonExceptionData.class);
responseEx.getStatus();
result = 403;
responseEx.getStatusType();
result = Status.FORBIDDEN;
responseEx.getBodyBuffer();
result = Buffer.buffer(JsonUtils.writeValueAsString(data).getBytes());
}
};
Response response = filter.afterReceiveResponse(invocation, responseEx);
Assert.assertEquals(403, response.getStatusCode());
Assert.assertEquals("Forbidden", response.getReasonPhrase());
Assert.assertEquals(InvocationException.class, response.<InvocationException>getResult().getClass());
InvocationException invocationException = response.getResult();
Assert.assertEquals(
403,
invocationException.getStatusCode());
Assert.assertEquals(
"CommonExceptionData [message=abcd]",
invocationException.getErrorData().toString());
}
private void checkRequest(String resourceId, UmaPermissionRepresentation representation) {
ResourceStore resourceStore = this.authorization.getStoreFactory().getResourceStore();
Resource resource = resourceStore.findById(resourceId, resourceServer.getId());
if (resource == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Resource [" + resourceId + "] cannot be found", Response.Status.BAD_REQUEST);
}
if (!resource.getOwner().equals(identity.getId())) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resource owner can access policies for resource [" + resourceId + "]", Status.BAD_REQUEST);
}
if (!resource.isOwnerManagedAccess()) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resources with owner managed accessed can have policies", Status.BAD_REQUEST);
}
if (!resourceServer.isAllowRemoteResourceManagement()) {
throw new ErrorResponseException(OAuthErrorException.REQUEST_NOT_SUPPORTED, "Remote Resource Management not enabled on resource server [" + resourceServer.getId() + "]", Status.FORBIDDEN);
}
if (representation != null) {
Set<String> resourceScopes = resource.getScopes().stream().map(scope -> scope.getName()).collect(Collectors.toSet());
Set<String> scopes = representation.getScopes();
if (scopes == null || scopes.isEmpty()) {
scopes = resourceScopes;
representation.setScopes(scopes);
}
if (!resourceScopes.containsAll(scopes)) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Some of the scopes [" + scopes + "] are not valid for resource [" + resourceId + "]", Response.Status.BAD_REQUEST);
}
if (representation.getCondition() != null) {
if (!Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Script upload not supported", Status.BAD_REQUEST);
}
}
}
}
@Override
public Response toResponse(AuthenticationTokenRefreshmentException exception) {
Status status = Status.FORBIDDEN;
ApiErrorDetails errorDetails = new ApiErrorDetails();
errorDetails.setStatus(status.getStatusCode());
errorDetails.setTitle(status.getReasonPhrase());
errorDetails.setMessage("The authentication token cannot be refreshed.");
errorDetails.setPath(uriInfo.getAbsolutePath().getPath());
return Response.status(status).entity(errorDetails).type(MediaType.APPLICATION_JSON).build();
}
public void createTenant(TenantDto dto) {
if (getIdentityService().isReadOnly()) {
throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
}
Tenant newTenant = getIdentityService().newTenant(dto.getId());
dto.update(newTenant);
getIdentityService().saveTenant(newTenant);
}
public void validateNamespacePolicyOperation(NamespaceName namespaceName, PolicyName policy, PolicyOperation operation) {
if (pulsar().getConfiguration().isAuthenticationEnabled() && pulsar().getBrokerService().isAuthorizationEnabled()) {
if (!isClientAuthenticated(clientAppId())) {
throw new RestException(Status.FORBIDDEN, "Need to authenticate to perform the request");
}
Boolean isAuthorized = pulsar().getBrokerService().getAuthorizationService()
.allowNamespacePolicyOperation(namespaceName, policy, operation, originalPrincipal(), clientAppId(), clientAuthData());
if (!isAuthorized) {
throw new RestException(Status.FORBIDDEN, String.format("Unauthorized to validateNamespacePolicyOperation for" +
" operation [%s] on namespace [%s] on policy [%s]", operation.toString(), namespaceName, policy.toString()));
}
}
}
public void validateNamespaceOperation(NamespaceName namespaceName, NamespaceOperation operation) {
if (pulsar().getConfiguration().isAuthenticationEnabled() && pulsar().getBrokerService().isAuthorizationEnabled()) {
if (!isClientAuthenticated(clientAppId())) {
throw new RestException(Status.FORBIDDEN, "Need to authenticate to perform the request");
}
Boolean isAuthorized = pulsar().getBrokerService().getAuthorizationService()
.allowNamespaceOperation(namespaceName, operation, originalPrincipal(), clientAppId(), clientAuthData());
if (!isAuthorized) {
throw new RestException(Status.FORBIDDEN, String.format("Unauthorized to validateNamespaceOperation for" +
" operation [%s] on namespace [%s]", operation.toString(), namespaceName));
}
}
}
@Override
public Response toResponse(AuthorizationException exception) {
Status status;
if (exception instanceof UnauthorizedException) {
status = Status.FORBIDDEN;
} else {
status = Status.UNAUTHORIZED;
}
return Response.status(status).build();
}
@Override
Status getResponseStatus() {
return Status.FORBIDDEN;
}
@Override
Status getResponseStatus() {
return Status.FORBIDDEN;
}
public ForbiddenException(String msg) {
super(new Exception(msg), Status.FORBIDDEN);
}
@Override
Status getResponseStatus() {
return Status.FORBIDDEN;
}
@Override
Status getResponseStatus() {
return Status.FORBIDDEN;
}