org.eclipse.che.api.core.BadRequestException Java Examples

The following examples show how to use org.eclipse.che.api.core.BadRequestException. 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: RemoteServiceDescriptor.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: InviteService.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: WorkspaceKeyValidator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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));
      }
  }
}
 
Example #4
Source File: OAuthAuthenticationService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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();
}
 
Example #5
Source File: UserValidator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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");
  }
}
 
Example #6
Source File: Fabric8DelegatedOAuthAPI.java    From rh-che with Eclipse Public License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: FactoryBaseValidator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #8
Source File: UserService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #9
Source File: SshService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: FactoryService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example #11
Source File: KeycloakServiceClient.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example #12
Source File: ProfileService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: FactoryBaseValidatorTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: FactoryService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example #15
Source File: OrganizationServiceTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: FreeResourcesLimitService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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));
}
 
Example #17
Source File: FreeResourcesLimitService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: PreferencesService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #19
Source File: SetPermissionsFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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");
}
 
Example #20
Source File: RemovePermissionsFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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");
}
 
Example #21
Source File: TestUserImpl.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** 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();
}
 
Example #22
Source File: FreeResourcesLimitValidatorTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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))));
}
 
Example #23
Source File: URLFactoryBuilderTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #24
Source File: OrganizationService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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();
}
 
Example #25
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #26
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@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()));
}
 
Example #27
Source File: FactoryService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@Path("/{id}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Update factory information by configuration and specified identifier",
    notes =
        "Update factory based on the factory id which is passed in a path parameter. "
            + "For perform this operation user needs respective rights")
@ApiResponses({
  @ApiResponse(code = 200, message = "Factory successfully updated"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "User does not have rights to update factory"),
  @ApiResponse(code = 404, message = "Factory to update not found"),
  @ApiResponse(
      code = 409,
      message =
          "Conflict error occurred during factory update"
              + "(e.g. Factory with such name and creator already exists)"),
  @ApiResponse(code = 500, message = "Internal server error")
})
public FactoryDto updateFactory(
    @ApiParam(value = "Factory identifier") @PathParam("id") String factoryId, FactoryDto update)
    throws BadRequestException, NotFoundException, ServerException, ForbiddenException,
        ConflictException {
  requiredNotNull(update, "Factory configuration");
  update.setId(factoryId);
  final Factory existing = factoryManager.getById(factoryId);
  // check if the current user has enough access to edit the factory
  editValidator.validate(existing);
  factoryBuilder.checkValid(update, true);
  // validate the new content
  createValidator.validateOnCreate(update);
  return injectLinks(asDto(factoryManager.updateFactory(update)));
}
 
Example #28
Source File: FactoryService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Filters workspace projects and removes projects without source location. If there is no at
 * least one project with source location then {@link BadRequestException} will be thrown
 */
private static void excludeProjectsWithoutLocation(
    WorkspaceImpl usersWorkspace, String projectPath) throws BadRequestException {
  final boolean notEmptyPath = projectPath != null;
  // Condition for sifting valid project in user's workspace
  Predicate<ProjectConfig> predicate =
      projectConfig -> {
        // if project is a sub project (it's path contains another project) , then location can be
        // null
        final boolean isSubProject = projectConfig.getPath().indexOf('/', 1) != -1;
        final boolean hasNotEmptySource =
            projectConfig.getSource() != null
                && projectConfig.getSource().getType() != null
                && projectConfig.getSource().getLocation() != null;

        return !(notEmptyPath && !projectPath.equals(projectConfig.getPath()))
            && (isSubProject || hasNotEmptySource);
      };

  // Filtered out projects by path and source storage presence
  final List<ProjectConfigImpl> filtered =
      usersWorkspace.getConfig().getProjects().stream().filter(predicate).collect(toList());
  checkArgument(
      !filtered.isEmpty(),
      "Unable to create factory from this workspace, "
          + "because it does not contains projects with source storage");
  usersWorkspace.getConfig().setProjects(filtered);
}
 
Example #29
Source File: TestUserServiceClientImpl.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void remove(String id) throws ConflictException, ServerException {
  try {
    requestFactory.fromUrl(userServiceEndpoint + id).useDeleteMethod().request();
  } catch (IOException
      | BadRequestException
      | NotFoundException
      | UnauthorizedException
      | ForbiddenException ex) {
    throw new ServerException(ex);
  }
}
 
Example #30
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@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));
}