Java源码示例:org.eclipse.che.api.core.BadRequestException
示例1
/**
* Validates that factory can be used at present time (used on accept)
*
* @param factory factory to validate
* @throws BadRequestException if since date greater than current date<br>
* @throws BadRequestException if until date less than current date<br>
*/
protected void validateCurrentTimeBetweenSinceUntil(FactoryDto factory)
throws BadRequestException {
final PoliciesDto policies = factory.getPolicies();
if (policies == null) {
return;
}
final Long since = policies.getSince() == null ? 0L : policies.getSince();
final Long until = policies.getUntil() == null ? 0L : policies.getUntil();
if (since != 0 && currentTimeMillis() < since) {
throw new BadRequestException(FactoryConstants.ILLEGAL_FACTORY_BY_SINCE_MESSAGE);
}
if (until != 0 && currentTimeMillis() > until) {
throw new BadRequestException(FactoryConstants.ILLEGAL_FACTORY_BY_UNTIL_MESSAGE);
}
}
示例2
@Override
public Response authenticate(
UriInfo uriInfo,
String oauthProvider,
List<String> scopes,
String redirectAfterLogin,
HttpServletRequest request)
throws BadRequestException {
String accountLinkingUrl =
authServiceClient.getAccountLinkingURL(null, oauthProvider, redirectAfterLogin);
if (Strings.isNullOrEmpty(accountLinkingUrl)) {
LOG.error("Failed to get GitHub account linking URL");
return Response.status(500).build();
}
return Response.temporaryRedirect(URI.create(accountLinkingUrl)).build();
}
示例3
/**
* Checks whether password is ok.
*
* @param password password to check
* @throws BadRequestException when password is not valid
*/
public void checkPassword(String password) throws BadRequestException {
if (password == null) {
throw new BadRequestException("Password required");
}
if (password.length() < 8) {
throw new BadRequestException("Password should contain at least 8 characters");
}
int numOfLetters = 0;
int numOfDigits = 0;
for (char passwordChar : password.toCharArray()) {
if (Character.isDigit(passwordChar)) {
numOfDigits++;
} else if (Character.isLetter(passwordChar)) {
numOfLetters++;
}
}
if (numOfDigits == 0 || numOfLetters == 0) {
throw new BadRequestException("Password should contain letters and digits");
}
}
示例4
@DELETE
@Path("/{domain}")
@ApiOperation(value = "Remove invite")
@ApiResponses({
@ApiResponse(code = 204, message = "The invitation successfully removed"),
@ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public void remove(
@ApiParam("Domain id") @PathParam("domain") String domain,
@ApiParam(value = "Instance id", required = true) @QueryParam("instance") String instance,
@ApiParam(value = "User email", required = true) @QueryParam("email") String email)
throws BadRequestException, ServerException {
checkArgument(!isNullOrEmpty(instance), "Instance id required");
checkArgument(!isNullOrEmpty(email), "User email required");
inviteManager.remove(domain, instance, email);
}
示例5
@PUT
@Path("/attributes")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_CURRENT_PROFILE_ATTRIBUTES)
@ApiOperation(
value = "Update the profile attributes of the currently logged in user",
notes =
"The replace strategy is used for the update, so all the existing profile "
+ "attributes will be override with incoming values")
public ProfileDto updateAttributes(
@ApiParam("New profile attributes") Map<String, String> updates)
throws NotFoundException, ServerException, BadRequestException {
checkAttributes(updates);
final ProfileImpl profile = new ProfileImpl(profileManager.getById(userId()));
profile.setAttributes(updates);
profileManager.update(profile);
return linksInjector.injectLinks(
asDto(profile, userManager.getById(profile.getUserId())), getServiceContext());
}
示例6
@Test(expectedExceptions = BadRequestException.class)
public void shouldNotValidateIfFindReplaceActionInsufficientParams() throws Exception {
// given
validator = new TesterFactoryBaseValidator();
Map<String, String> params = new HashMap<>();
params.put("in", "pom.xml");
// find is missing!
params.put("replace", "123");
List<IdeActionDto> actions =
singletonList(newDto(IdeActionDto.class).withId("findReplace").withProperties(params));
IdeDto ide =
newDto(IdeDto.class)
.withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(actions));
FactoryDto factoryWithAccountId = requireNonNull(getInstance().clone(factory)).withIde(ide);
// when
validator.validateProjectActions(factoryWithAccountId);
}
示例7
/**
* Creates factory image from input stream. InputStream should be closed manually.
*
* @param is input stream with image data
* @param mediaType media type of image
* @param name image name
* @return factory image, if {@param is} has no content then empty factory image will be returned
* @throws BadRequestException when factory image exceeded maximum size
* @throws ServerException when any server errors occurs
*/
public static FactoryImage createImage(InputStream is, String mediaType, String name)
throws BadRequestException, ServerException {
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int read;
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, read);
if (out.size() > 1024 * 1024) {
throw new BadRequestException("Maximum upload size exceeded.");
}
}
if (out.size() == 0) {
return new FactoryImage();
}
out.flush();
return new FactoryImage(out.toByteArray(), mediaType, name);
} catch (IOException ioEx) {
throw new ServerException(ioEx.getLocalizedMessage());
}
}
示例8
@DELETE
@Path("/{id}")
@ApiOperation(
value = "Removes the workspace",
notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
@ApiResponse(code = 204, message = "The workspace successfully removed"),
@ApiResponse(code = 403, message = "The user does not have access to remove the workspace"),
@ApiResponse(code = 404, message = "The workspace doesn't exist"),
@ApiResponse(code = 409, message = "The workspace is not stopped(has runtime)"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public void delete(@ApiParam("The workspace id") @PathParam("id") String id)
throws BadRequestException, ServerException, NotFoundException, ConflictException,
ForbiddenException {
workspaceManager.removeWorkspace(id);
}
示例9
@Test(dataProvider = "devfiles")
public void checkThatDtoHasCorrectNames(DevfileImpl devfile, String expectedGenerateName)
throws BadRequestException, ServerException, DevfileException, IOException,
OverrideParameterException {
DefaultFactoryUrl defaultFactoryUrl = mock(DefaultFactoryUrl.class);
FileContentProvider fileContentProvider = mock(FileContentProvider.class);
when(defaultFactoryUrl.devfileFileLocation()).thenReturn("anything");
when(devfileManager.parseYaml(anyString(), anyMap())).thenReturn(devfile);
when(urlFetcher.fetchSafely(anyString())).thenReturn("anything");
FactoryDto factory =
urlFactoryBuilder
.createFactoryFromDevfile(defaultFactoryUrl, fileContentProvider, emptyMap())
.get();
assertNull(factory.getDevfile().getMetadata().getName());
assertEquals(factory.getDevfile().getMetadata().getGenerateName(), expectedGenerateName);
}
示例10
/** To instantiate user with specific name, e-mail, password and offline token. */
@AssistedInject
public TestUserImpl(
TestUserServiceClientFactory testUserServiceClientFactory,
TestAuthServiceClient authServiceClient,
@Assisted RemovableUserProvider testUserProvider,
@Assisted("name") String name,
@Assisted("email") String email,
@Assisted("password") String password)
throws NotFoundException, ServerException, BadRequestException {
this.authServiceClient = authServiceClient;
this.testUserProvider = testUserProvider;
this.name = name;
this.email = email;
this.password = password;
this.userServiceClient = testUserServiceClientFactory.create(this);
this.id = userServiceClient.findByEmail(email).getId();
}
示例11
@Test
public void shouldRespond400IfInstanceIsNotValid() throws Exception {
when(subject.hasPermission("test", "test123", SET_PERMISSIONS)).thenReturn(false);
doThrow(new BadRequestException("instance is not valid"))
.when(instanceValidator)
.validate(any(), any());
final Response response =
given()
.auth()
.basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
.contentType("application/json")
.when()
.delete(SECURE_PATH + "/permissions/test?instance=test123&user123");
assertEquals(response.getStatusCode(), 400);
assertEquals(unwrapError(response), "instance is not valid");
verifyZeroInteractions(permissionsService);
verify(instanceValidator).validate("test", "test123");
}
示例12
@Test
public void shouldRespond400IfInstanceIsNotValid() throws Exception {
when(subject.hasPermission("test", "test123", SET_PERMISSIONS)).thenReturn(false);
doThrow(new BadRequestException("instance is not valid"))
.when(instanceValidator)
.validate(any(), any());
final Response response =
given()
.auth()
.basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
.contentType("application/json")
.body(
DtoFactory.newDto(PermissionsDto.class)
.withDomainId("test")
.withInstanceId("test123")
.withUserId("user123")
.withActions(Collections.singletonList("read")))
.when()
.post(SECURE_PATH + "/permissions");
assertEquals(response.getStatusCode(), 400);
assertEquals(unwrapError(response), "instance is not valid");
verifyZeroInteractions(permissionsService);
verify(instanceValidator).validate("test", "test123");
}
示例13
@POST
@Consumes(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_PREFERENCES)
@ApiOperation(
value = "Saves preferences of logged in user",
notes = "All the existing user's preferences will be override by this method")
@ApiResponses({
@ApiResponse(code = 204, message = "Preferences successfully saved"),
@ApiResponse(code = 400, message = "Request doesn't contain new preferences"),
@ApiResponse(code = 500, message = "Couldn't save preferences due to internal server error")
})
public void save(Map<String, String> preferences) throws BadRequestException, ServerException {
if (preferences == null) {
throw new BadRequestException("Required non-null new preferences");
}
preferenceManager.save(userId(), preferences);
}
示例14
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Store free resources limit", response = FreeResourcesLimitDto.class)
@ApiResponses({
@ApiResponse(code = 201, message = "The resources limit successfully stored"),
@ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
@ApiResponse(code = 409, message = "The specified account doesn't exist"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public Response storeFreeResourcesLimit(
@ApiParam(value = "Free resources limit") FreeResourcesLimitDto resourcesLimit)
throws BadRequestException, NotFoundException, ConflictException, ServerException {
freeResourcesLimitValidator.check(resourcesLimit);
return Response.status(201)
.entity(DtoConverter.asDto(freeResourcesLimitManager.store(resourcesLimit)))
.build();
}
示例15
@GET
@Path("/{accountId}")
@Produces(APPLICATION_JSON)
@ApiOperation(
value = "Get free resources limit for account with given id",
response = FreeResourcesLimitDto.class)
@ApiResponses({
@ApiResponse(code = 200, message = "The resources limit successfully fetched"),
@ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
@ApiResponse(code = 404, message = "Resources limit for given account was not found"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public FreeResourcesLimitDto getFreeResourcesLimit(
@ApiParam(value = "Account id") @PathParam("accountId") String accountId)
throws BadRequestException, NotFoundException, ServerException {
return DtoConverter.asDto(freeResourcesLimitManager.get(accountId));
}
示例16
public ServiceDescriptor getServiceDescriptor() throws IOException, ServerException {
if (serviceDescriptor == null) {
synchronized (this) {
if (serviceDescriptor == null) {
try {
serviceDescriptor =
requestFactory
.fromUrl(baseUrl)
.useOptionsMethod()
.request()
.as(getServiceDescriptorClass(), null);
} catch (NotFoundException
| ConflictException
| UnauthorizedException
| BadRequestException
| ForbiddenException e) {
throw new ServerException(e.getServiceError());
}
}
}
}
return serviceDescriptor;
}
示例17
@Test(
expectedExceptions = BadRequestException.class,
expectedExceptionsMessageRegExp =
"Free resources limit should contain only one resources with type 'test'.")
public void
shouldThrowBadRequestExceptionWhenAccountResourcesLimitContainTwoResourcesWithTheSameType()
throws Exception {
// when
validator.check(
DtoFactory.newDto(FreeResourcesLimitDto.class)
.withAccountId("account123")
.withResources(
Arrays.asList(
DtoFactory.newDto(ResourceDto.class)
.withType("test")
.withUnit("mb")
.withAmount(1230),
DtoFactory.newDto(ResourceDto.class)
.withType("test")
.withUnit("mb")
.withAmount(3))));
}
示例18
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Create new organization", response = OrganizationDto.class)
@ApiResponses({
@ApiResponse(code = 201, message = "The organization successfully created"),
@ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
@ApiResponse(
code = 409,
message =
"Conflict error occurred during the organization creation"
+ "(e.g. The organization with such name already exists)"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public Response create(
@ApiParam(value = "Organization to create", required = true) OrganizationDto organization)
throws BadRequestException, NotFoundException, ConflictException, ServerException {
organizationValidator.checkOrganization(organization);
return Response.status(201)
.entity(
linksInjector.injectLinks(
asDto(organizationManager.create(organization)), getServiceContext()))
.build();
}
示例19
@Test
public void shouldThrowBadRequestWhenCreatingNonValidOrganization() throws Exception {
doThrow(new BadRequestException("non valid organization"))
.when(validator)
.checkOrganization(any());
final OrganizationDto toCreate = createOrganization();
final Response response =
given()
.auth()
.basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
.contentType("application/json")
.body(toCreate)
.when()
.expect()
.statusCode(400)
.post(SECURE_PATH + "/organization");
final ServiceError error = unwrapDto(response, ServiceError.class);
assertEquals(error.getMessage(), "non valid organization");
verify(validator).checkOrganization(toCreate);
}
示例20
@GET
@Path("/namespace/{namespace:.*}")
@Produces(APPLICATION_JSON)
@ApiOperation(
value = "Get workspaces by given namespace",
notes = "This operation can be performed only by authorized user",
response = WorkspaceDto.class,
responseContainer = "List")
@ApiResponses({
@ApiResponse(code = 200, message = "The workspaces successfully fetched"),
@ApiResponse(code = 500, message = "Internal server error occurred during workspaces fetching")
})
public List<WorkspaceDto> getByNamespace(
@ApiParam("Workspace status") @QueryParam("status") String status,
@ApiParam("The namespace") @PathParam("namespace") String namespace)
throws ServerException, BadRequestException {
return asDtosWithLinks(
Pages.stream(
(maxItems, skipCount) ->
workspaceManager.getByNamespace(namespace, false, maxItems, skipCount))
.filter(ws -> status == null || status.equalsIgnoreCase(ws.getStatus().toString()))
.collect(toList()));
}
示例21
/**
* Gets auth token from given identity provider.
*
* @param oauthProvider provider name
* @return KeycloakTokenResponse token response
* @throws ForbiddenException when HTTP request was forbidden
* @throws BadRequestException when HTTP request considered as bad
* @throws IOException when unable to parse error response
* @throws NotFoundException when requested URL not found
* @throws ServerException when other error occurs
* @throws UnauthorizedException when no token present for user or user not linked to provider
*/
public KeycloakTokenResponse getIdentityProviderToken(String oauthProvider)
throws ForbiddenException, BadRequestException, IOException, NotFoundException,
ServerException, UnauthorizedException {
String url =
UriBuilder.fromUri(keycloakSettings.get().get(AUTH_SERVER_URL_SETTING))
.path("/realms/{realm}/broker/{provider}/token")
.build(keycloakSettings.get().get(REALM_SETTING), oauthProvider)
.toString();
try {
String response = doRequest(url, HttpMethod.GET, null);
// Successful answer is not a json, but key=value&foo=bar format pairs
return DtoFactory.getInstance()
.createDtoFromJson(toJson(response), KeycloakTokenResponse.class);
} catch (BadRequestException e) {
if (assotiateUserPattern.matcher(e.getMessage()).matches()) {
// If user has no link with identity provider yet,
// we should threat this as unauthorized and send to OAuth login page.
throw new UnauthorizedException(e.getMessage());
}
throw e;
}
}
示例22
/**
* Provides a suitable resolver for the given parameters. If there is no at least one resolver
* able to process parameters,then {@link BadRequestException} will be thrown
*
* @return suitable service-specific resolver or default one
*/
public FactoryParametersResolver getFactoryParametersResolver(Map<String, String> parameters)
throws BadRequestException {
if (specificFactoryParametersResolvers != null) {
for (FactoryParametersResolver factoryParametersResolver :
specificFactoryParametersResolvers) {
if (factoryParametersResolver.accept(parameters)) {
return factoryParametersResolver;
}
}
}
if (defaultFactoryResolver.accept(parameters)) {
return defaultFactoryResolver;
} else {
throw new BadRequestException(FACTORY_NOT_RESOLVABLE);
}
}
示例23
/**
* Checks that key consists either from workspaceId or username:workspace_name string.
*
* @param key key string to validate
* @throws BadRequestException if validation is failed
*/
public static void validateKey(String key) throws BadRequestException {
String[] parts = key.split(":", -1); // -1 is to prevent skipping trailing part
switch (parts.length) {
case 1:
{
return; // consider it's id
}
case 2:
{
if (parts[1].isEmpty()) {
throw new BadRequestException(
"Wrong composite key format - workspace name required to be set.");
}
break;
}
default:
{
throw new BadRequestException(
format("Wrong composite key %s. Format should be 'username:workspace_name'. ", key));
}
}
}
示例24
@GET
@Path("authenticate")
public Response authenticate(
@QueryParam("oauth_provider") String providerName,
@QueryParam("request_method") String requestMethod,
@QueryParam("signature_method") String signatureMethod,
@QueryParam("redirect_after_login") String redirectAfterLogin)
throws OAuthAuthenticationException, BadRequestException {
requiredNotNull(providerName, "Provider name");
requiredNotNull(redirectAfterLogin, "Redirect after login");
final OAuthAuthenticator oauth = getAuthenticator(providerName);
final String authUrl =
oauth.getAuthenticateUrl(getRequestUrl(uriInfo), requestMethod, signatureMethod);
return Response.temporaryRedirect(URI.create(authUrl)).build();
}
示例25
@GET
@Path("/find")
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_USER)
@ApiOperation("Get user by email or name")
@ApiResponses({
@ApiResponse(code = 200, message = "The response contains requested user entity"),
@ApiResponse(code = 404, message = "User with requested email/name not found"),
@ApiResponse(code = 500, message = "Impossible to get user due to internal server error")
})
public UserDto find(
@ApiParam("User email, if it is set then name shouldn't be") @QueryParam("email")
String email,
@ApiParam("User name, if is is set then email shouldn't be") @QueryParam("name") String name)
throws NotFoundException, ServerException, BadRequestException {
if (email == null && name == null) {
throw new BadRequestException("Missed user's email or name");
}
if (email != null && name != null) {
throw new BadRequestException(
"Expected either user's email or name, while both values received");
}
final User user = name == null ? userManager.getByEmail(email) : userManager.getByName(name);
return linksInjector.injectLinks(asDto(user), getServiceContext());
}
示例26
@DELETE
@Path("{service}")
@ApiOperation(
value =
"Remove the ssh pair by the name of pair and name of service owned by the current user")
@ApiResponses({
@ApiResponse(code = 204, message = "The ssh pair successfully removed"),
@ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
@ApiResponse(code = 404, message = "The ssh pair doesn't exist"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public void removePair(
@ApiParam("Name of service") @PathParam("service") String service,
@ApiParam(value = "Name of ssh pair", required = true) @QueryParam("name") String name)
throws ServerException, NotFoundException, BadRequestException {
requiredNotNull(name, "Name of ssh pair");
sshManager.removePair(getCurrentUserId(), service, name);
}
示例27
@POST
@Path("/{id}/runtime")
@Produces(APPLICATION_JSON)
@ApiOperation(
value = "Start the workspace by the id",
notes =
"This operation can be performed only by the workspace owner."
+ "The workspace starts asynchronously")
@ApiResponses({
@ApiResponse(code = 200, message = "The workspace is starting"),
@ApiResponse(code = 404, message = "The workspace with specified id doesn't exist"),
@ApiResponse(
code = 403,
message = "The user is not workspace owner." + "The operation is not allowed for the user"),
@ApiResponse(code = 409, message = "Any conflict occurs during the workspace start"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto startById(
@ApiParam("The workspace id") @PathParam("id") String workspaceId,
@ApiParam("The name of the workspace environment that should be used for start")
@QueryParam("environment")
String envName,
@QueryParam(DEBUG_WORKSPACE_START) @DefaultValue("false") Boolean debugWorkspaceStart)
throws ServerException, BadRequestException, NotFoundException, ForbiddenException,
ConflictException {
Map<String, String> options = new HashMap<>();
if (debugWorkspaceStart) {
options.put(DEBUG_WORKSPACE_START, debugWorkspaceStart.toString());
options.put(DEBUG_WORKSPACE_START_LOG_LIMIT_BYTES, logLimitBytes.toString());
}
return asDtoWithLinksAndToken(workspaceManager.startWorkspace(workspaceId, envName, options));
}
示例28
/** Return user's {@link GithubToken} from the fabric8 auth github endpoint. */
public GithubToken getGithubToken()
throws ServerException, ForbiddenException, NotFoundException, UnauthorizedException,
BadRequestException, IOException {
String response = doRequest(githubTokenEndpoint, HttpMethod.GET, null);
return gson.fromJson(response, GithubToken.class);
}
示例29
@POST
@Path("/{id}/project")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
value = "Adds a new project to the workspace",
notes = "This operation can be performed only by the workspace owner")
@ApiResponses({
@ApiResponse(code = 200, message = "The project successfully added to the workspace"),
@ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
@ApiResponse(code = 403, message = "The user does not have access to add the project"),
@ApiResponse(code = 404, message = "The workspace not found"),
@ApiResponse(code = 409, message = "Any conflict error occurs"),
@ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto addProject(
@ApiParam("The workspace id") @PathParam("id") String id,
@ApiParam(value = "The new project", required = true) ProjectConfigDto newProject)
throws ServerException, BadRequestException, NotFoundException, ConflictException,
ForbiddenException {
requiredNotNull(newProject, "New project config");
final WorkspaceImpl workspace = workspaceManager.getWorkspace(id);
if (workspace.getConfig() == null) {
throw new ConflictException(
"This method can not be invoked for workspace created from Devfile. Use update workspace method instead.");
}
workspace.getConfig().getProjects().add(new ProjectConfigImpl(newProject));
return asDtoWithLinksAndToken(doUpdate(id, workspace));
}
示例30
private void checkAttributes(Map<String, String> attributes) throws BadRequestException {
if (attributes == null) {
throw new BadRequestException("Update attributes required");
}
for (String value : attributes.values()) {
if (value == null) {
throw new BadRequestException("Update attributes must not be null");
}
}
}