use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.
the class ProjectManager method createBatchProjects.
/**
* Create batch of projects according to their configurations.
* <p/>
* Notes: - a project will be created by importing when project configuration contains {@link SourceStorage} object,
* otherwise this one will be created corresponding its {@link NewProjectConfig}:
* <li> - {@link NewProjectConfig} object contains only one mandatory {@link NewProjectConfig#setPath(String)} field.
* In this case Project will be created as project of {@link BaseProjectType} type </li>
* <li> - a project will be created as project of {@link BaseProjectType} type with {@link Problem#code} = 12
* when declared primary project type is not registered, </li>
* <li> - a project will be created with {@link Problem#code} = 12 and without mixin project type
* when declared mixin project type is not registered</li>
* <li> - for creating a project by generator {@link NewProjectConfig#getOptions()} should be specified.</li>
*
* @param projectConfigList
* the list of configurations to create projects
* @param rewrite
* whether rewrite or not (throw exception otherwise) if such a project exists
* @return the list of new projects
* @throws BadRequestException
* when {@link NewProjectConfig} object not contains mandatory {@link NewProjectConfig#setPath(String)} field.
* @throws ConflictException
* when the same path project exists and {@code rewrite} is {@code false}
* @throws ForbiddenException
* when trying to overwrite the project and this one contains at least one locked file
* @throws NotFoundException
* when parent folder does not exist
* @throws UnauthorizedException
* if user isn't authorized to access to location at importing source code
* @throws ServerException
* if other error occurs
*/
public List<RegisteredProject> createBatchProjects(List<? extends NewProjectConfig> projectConfigList, boolean rewrite, ProjectOutputLineConsumerFactory lineConsumerFactory) throws BadRequestException, ConflictException, ForbiddenException, NotFoundException, ServerException, UnauthorizedException, IOException {
fileWatcherManager.suspend();
try {
final List<RegisteredProject> projects = new ArrayList<>(projectConfigList.size());
validateProjectConfigurations(projectConfigList, rewrite);
final List<NewProjectConfig> sortedConfigList = projectConfigList.stream().sorted((config1, config2) -> config1.getPath().compareTo(config2.getPath())).collect(Collectors.toList());
for (NewProjectConfig projectConfig : sortedConfigList) {
RegisteredProject registeredProject;
final String pathToProject = projectConfig.getPath();
//creating project(by config or by importing source code)
try {
final SourceStorage sourceStorage = projectConfig.getSource();
if (sourceStorage != null && !isNullOrEmpty(sourceStorage.getLocation())) {
doImportProject(pathToProject, sourceStorage, rewrite, lineConsumerFactory.setProjectName(projectConfig.getPath()));
} else if (!isVirtualFileExist(pathToProject)) {
registeredProject = doCreateProject(projectConfig, projectConfig.getOptions());
projects.add(registeredProject);
continue;
}
} catch (Exception e) {
if (!isVirtualFileExist(pathToProject)) {
//project folder is absent
rollbackCreatingBatchProjects(projects);
throw e;
}
}
//update project
if (isVirtualFileExist(pathToProject)) {
try {
registeredProject = updateProject(projectConfig);
} catch (Exception e) {
registeredProject = projectRegistry.putProject(projectConfig, asFolder(pathToProject), true, false);
final Problem problem = new Problem(NOT_UPDATED_PROJECT, "The project is not updated, caused by " + e.getLocalizedMessage());
registeredProject.getProblems().add(problem);
}
} else {
registeredProject = projectRegistry.putProject(projectConfig, null, true, false);
}
projects.add(registeredProject);
}
return projects;
} finally {
fileWatcherManager.resume();
}
}
use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.
the class GitHubKeyUploader method uploadKey.
@Override
public void uploadKey(String publicKey) throws IOException, UnauthorizedException {
final OAuthToken token = tokenProvider.getToken("github", EnvironmentContext.getCurrent().getSubject().getUserId());
if (token == null || token.getToken() == null) {
LOG.debug("Token not found, user need to authorize to upload key.");
throw new UnauthorizedException("To upload SSH key you need to authorize.");
}
StringBuilder answer = new StringBuilder();
final String url = String.format("https://api.github.com/user/keys?access_token=%s", token.getToken());
final List<GitHubKey> gitHubUserPublicKeys = getUserPublicKeys(url, answer);
for (GitHubKey gitHubUserPublicKey : gitHubUserPublicKeys) {
if (publicKey.startsWith(gitHubUserPublicKey.getKey())) {
return;
}
}
final Map<String, String> postParams = new HashMap<>(2);
postParams.put("title", "IDE SSH Key (" + new SimpleDateFormat().format(new Date()) + ")");
postParams.put("key", new String(publicKey.getBytes()));
final String postBody = JsonHelper.toJson(postParams);
LOG.debug("Upload public key: {}", postBody);
int responseCode;
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod(HttpMethod.POST);
conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
conn.setRequestProperty(HttpHeaders.CONTENT_LENGTH, String.valueOf(postBody.length()));
conn.setDoOutput(true);
try (OutputStream out = conn.getOutputStream()) {
out.write(postBody.getBytes());
}
responseCode = conn.getResponseCode();
} finally {
if (conn != null) {
conn.disconnect();
}
}
LOG.debug("Upload key response code: {}", responseCode);
if (responseCode != HttpURLConnection.HTTP_CREATED) {
throw new IOException(String.format("%d: Failed to upload public key to https://github.com/", responseCode));
}
}
use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.
the class SubversionApi method getRevisions.
public GetRevisionsResponse getRevisions(GetRevisionsRequest request) throws IOException, SubversionException, UnauthorizedException {
final File projectPath = new File(request.getProjectPath());
final List<String> uArgs = defaultArgs();
addOption(uArgs, "--revision", request.getRevisionRange());
uArgs.add("log");
final CommandLineResult result = runCommand(null, uArgs, projectPath, Arrays.asList(request.getPath()));
final GetRevisionsResponse response = DtoFactory.getInstance().createDto(GetRevisionsResponse.class).withCommand(result.getCommandLine().toString()).withOutput(result.getStdout()).withErrOutput(result.getStderr());
if (result.getExitCode() == 0) {
List<String> revisions = result.getStdout().parallelStream().filter(line -> line.split("\\|").length == 4).map(line -> line.split("\\|")[0].trim()).collect(Collectors.toList());
response.withRevisions(revisions);
}
return response;
}
use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.
the class DefaultHttpJsonRequest method doRequest.
/**
* Makes this request using {@link HttpURLConnection}.
*
* <p>Uses {@link HttpHeaders#AUTHORIZATION} header with value from {@link EnvironmentContext}.
* <br>uses {@link HttpHeaders#ACCEPT} header with "application/json" value.
* <br>Encodes query parameters in "UTF-8".
*
* @param timeout
* request timeout, used only if it is greater than 0
* @param url
* request url
* @param method
* request method
* @param body
* request body, must be instance of {@link JsonSerializable}
* @param parameters
* query parameters, may be null
* @param authorizationHeaderValue
* value of authorization header, may be null
* @return response to this request
* @throws IOException
* when connection content type is not "application/json"
* @throws ServerException
* when response code is 500 or it is different from 400, 401, 403, 404, 409
* @throws ForbiddenException
* when response code is 403
* @throws NotFoundException
* when response code is 404
* @throws UnauthorizedException
* when response code is 401
* @throws ConflictException
* when response code is 409
* @throws BadRequestException
* when response code is 400
*/
protected DefaultHttpJsonResponse doRequest(int timeout, String url, String method, Object body, List<Pair<String, ?>> parameters, String authorizationHeaderValue) throws IOException, ServerException, ForbiddenException, NotFoundException, UnauthorizedException, ConflictException, BadRequestException {
final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
final boolean hasQueryParams = parameters != null && !parameters.isEmpty();
if (hasQueryParams || authToken != null) {
final UriBuilder ub = UriBuilder.fromUri(url);
//remove sensitive information from url.
ub.replaceQueryParam("token", EMPTY_ARRAY);
if (hasQueryParams) {
for (Pair<String, ?> parameter : parameters) {
ub.queryParam(parameter.first, parameter.second);
}
}
url = ub.build().toString();
}
final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
conn.setReadTimeout(timeout > 0 ? timeout : 60000);
try {
conn.setRequestMethod(method);
//drop a hint for server side that we want to receive application/json
conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
if (!isNullOrEmpty(authorizationHeaderValue)) {
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authorizationHeaderValue);
} else if (authToken != null) {
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
}
if (body != null) {
conn.addRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
conn.setDoOutput(true);
if (HttpMethod.DELETE.equals(method)) {
//to avoid jdk bug described here http://bugs.java.com/view_bug.do?bug_id=7157360
conn.setRequestMethod(HttpMethod.POST);
conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
}
try (OutputStream output = conn.getOutputStream()) {
output.write(DtoFactory.getInstance().toJson(body).getBytes());
}
}
final int responseCode = conn.getResponseCode();
if ((responseCode / 100) != 2) {
InputStream in = conn.getErrorStream();
if (in == null) {
in = conn.getInputStream();
}
final String str;
try (Reader reader = new InputStreamReader(in)) {
str = CharStreams.toString(reader);
}
final String contentType = conn.getContentType();
if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
final ServiceError serviceError = DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
if (serviceError.getMessage() != null) {
if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
throw new ForbiddenException(serviceError);
} else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
throw new NotFoundException(serviceError);
} else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
throw new UnauthorizedException(serviceError);
} else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
throw new ConflictException(serviceError);
} else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
throw new ServerException(serviceError);
} else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
throw new BadRequestException(serviceError);
}
throw new ServerException(serviceError);
}
}
// Can't parse content as json or content has format other we expect for error.
throw new IOException(String.format("Failed access: %s, method: %s, response code: %d, message: %s", UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
}
final String contentType = conn.getContentType();
if (contentType != null && !contentType.startsWith(MediaType.APPLICATION_JSON)) {
throw new IOException(conn.getResponseMessage());
}
try (Reader reader = new InputStreamReader(conn.getInputStream())) {
return new DefaultHttpJsonResponse(CharStreams.toString(reader), responseCode);
}
} finally {
conn.disconnect();
}
}
use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.
the class GitHubFactory method getToken.
private String getToken() throws ServerException, UnauthorizedException {
OAuthToken token;
try {
token = oauthTokenProvider.getToken("github", EnvironmentContext.getCurrent().getSubject().getUserId());
} catch (IOException e) {
throw new ServerException(e.getMessage());
}
String oauthToken = token != null ? token.getToken() : null;
if (oauthToken == null || oauthToken.isEmpty()) {
throw new UnauthorizedException("User doesn't have access token to github");
}
return oauthToken;
}
Aggregations