org.gitlab4j.api.GitLabApiException Java Examples
The following examples show how to use
org.gitlab4j.api.GitLabApiException.
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: GitLabPersonalAccessTokenCreator.java From gitlab-branch-source-plugin with MIT License | 6 votes |
@SuppressWarnings("unused") @RequirePOST public FormValidation doCreateTokenByPassword( @QueryParameter String serverUrl, @QueryParameter String login, @QueryParameter String password) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); try { String tokenName = UUID.randomUUID().toString(); String token = AccessTokenUtils.createPersonalAccessToken( defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL), login, password, tokenName, GL_PLUGIN_REQUIRED_SCOPE ); tokenName = getShortName(tokenName); createCredentials(serverUrl, token, login, tokenName); return FormValidation.ok( "Created credentials with id %s", tokenName ); } catch (GitLabApiException e) { return FormValidation .error(e, "Can't create GL token for %s - %s", login, e.getMessage()); } }
Example #2
Source File: IssuesStatisticsFilter.java From gitlab4j-api with MIT License | 6 votes |
@JsonIgnore public GitLabApiForm getQueryParams() throws GitLabApiException { return (new GitLabApiForm() .withParam("labels", (labels != null ? String.join(",", labels) : null)) .withParam("iids", iids) .withParam("milestone", milestone) .withParam("scope", scope) .withParam("author_id", authorId) .withParam("assignee_id", assigneeId) .withParam("my_reaction_emoji", myReactionEmoji) .withParam("search", search) .withParam("in", in) .withParam("created_after", ISO8601.toString(createdAfter, false)) .withParam("created_before", ISO8601.toString(createdBefore, false)) .withParam("updated_after", ISO8601.toString(updatedAfter, false)) .withParam("updated_before", ISO8601.toString(updatedBefore, false)) .withParam("confidential", confidential)); }
Example #3
Source File: WebHookManager.java From gitlab4j-api with MIT License | 6 votes |
/** * Verifies the provided Event and fires it off to the registered listeners. * * @param event the Event instance to handle * @throws GitLabApiException if the event is not supported */ public void handleEvent(Event event) throws GitLabApiException { LOGGER.info("handleEvent: object_kind=" + event.getObjectKind()); switch (event.getObjectKind()) { case BuildEvent.OBJECT_KIND: case IssueEvent.OBJECT_KIND: case JobEvent.OBJECT_KIND: case MergeRequestEvent.OBJECT_KIND: case NoteEvent.OBJECT_KIND: case PipelineEvent.OBJECT_KIND: case PushEvent.OBJECT_KIND: case TagPushEvent.OBJECT_KIND: case WikiPageEvent.OBJECT_KIND: fireEvent(event); break; default: String message = "Unsupported event object_kind, object_kind=" + event.getObjectKind(); LOGGER.warning(message); throw new GitLabApiException(message); } }
Example #4
Source File: UrlEncoder.java From gitlab4j-api with MIT License | 6 votes |
/** * URL encodes a String in compliance with GitLabs special differences. * * @param s the String to URL encode * @return the URL encoded strings * @throws GitLabApiException if any exception occurs */ public static String urlEncode(String s) throws GitLabApiException { try { String encoded = URLEncoder.encode(s, "UTF-8"); // Since the encode method encodes plus signs as %2B, // we can simply replace the encoded spaces with the correct encoding here encoded = encoded.replace("+", "%20"); encoded = encoded.replace(".", "%2E"); encoded = encoded.replace("-", "%2D"); encoded = encoded.replace("_", "%5F"); return (encoded); } catch (Exception e) { throw new GitLabApiException(e); } }
Example #5
Source File: AccessTokenUtils.java From gitlab4j-api with MIT License | 6 votes |
/** * Adds the specified form param to the form data StringBuilder. If the provided formData is null, * will create the StringBuilder instance first. * * @param formData the StringBuilder instance holding the form data, if null will create the StringBuilder * @param name the form param name * @param value the form param value * @return the form data StringBuilder * @throws GitLabApiException if any error occurs. */ public static final StringBuilder addFormData(StringBuilder formData, String name, String value) throws GitLabApiException { if (formData == null) { formData = new StringBuilder(); } else if (formData.length() > 0) { formData.append("&"); } formData.append(name); formData.append("="); try { formData.append(URLEncoder.encode(value, "UTF-8")); return (formData); } catch (Exception e) { throw new GitLabApiException(e); } }
Example #6
Source File: WebHookManager.java From choerodon-starters with Apache License 2.0 | 6 votes |
/** * Verifies the provided Event and fires it off to the registered listeners. * * @param event the Event instance to handle * @throws GitLabApiException if the event is not supported */ public void handleEvent(Event event) throws GitLabApiException { LOG.info("handleEvent: object_kind=" + event.getObjectKind()); switch (event.getObjectKind()) { case BuildEvent.OBJECT_KIND: case IssueEvent.OBJECT_KIND: case MergeRequestEvent.OBJECT_KIND: case NoteEvent.OBJECT_KIND: case PipelineEvent.OBJECT_KIND: case PushEvent.OBJECT_KIND: case TagPushEvent.OBJECT_KIND: case WikiPageEvent.OBJECT_KIND: break; default: String message = "Unsupported event object_kind, object_kind=" + event.getObjectKind(); LOG.warning(message); throw new GitLabApiException(message); } fireEvent(event); }
Example #7
Source File: GitLabHookCreator.java From gitlab-branch-source-plugin with MIT License | 6 votes |
public static String createWebHookWhenMissing(GitLabApi gitLabApi, String project, String hookUrl, String secretToken) throws GitLabApiException { ProjectHook projectHook = gitLabApi.getProjectApi().getHooksStream(project) .filter(hook -> hookUrl.equals(hook.getUrl())) .findFirst() .orElseGet(GitLabHookCreator::createWebHook); if (projectHook.getId() == null) { gitLabApi.getProjectApi().addHook(project, hookUrl, projectHook, false, secretToken); return "created"; } // Primarily done due to legacy reason, secret token might not be configured in previous releases. So setting up hook url with the token. if(!isTokenEqual(projectHook.getToken(), secretToken)) { projectHook.setToken(secretToken); gitLabApi.getProjectApi().modifyHook(projectHook); return "modified"; } return "already created"; }
Example #8
Source File: GitLabHookCreator.java From gitlab-branch-source-plugin with MIT License | 6 votes |
public static void createSystemHookWhenMissing(GitLabServer server, PersonalAccessToken credentials) { String systemHookUrl = getHookUrl(server, false); try { GitLabApi gitLabApi = new GitLabApi(server.getServerUrl(), credentials.getToken().getPlainText()); SystemHook systemHook = gitLabApi.getSystemHooksApi() .getSystemHookStream() .filter(hook -> systemHookUrl.equals(hook.getUrl())) .findFirst() .orElse(null); if (systemHook == null) { gitLabApi.getSystemHooksApi().addSystemHook(systemHookUrl, server.getSecretToken().getPlainText(), false, false, false); } } catch (GitLabApiException e) { LOGGER.log(Level.INFO, "User is not admin so cannot set system hooks", e); } }
Example #9
Source File: GitLabSCMSource.java From gitlab-branch-source-plugin with MIT License | 6 votes |
public int getProjectId(@QueryParameter String projectPath, @QueryParameter String serverName) { List<GitLabServer> gitLabServers = GitLabServers.get().getServers(); if (gitLabServers.size() == 0) { return -1; } try { GitLabApi gitLabApi; if (StringUtils.isBlank(serverName)) { gitLabApi = apiBuilder(gitLabServers.get(0).getName()); } else { gitLabApi = apiBuilder(serverName); } if (StringUtils.isNotBlank(projectPath)) { return gitLabApi.getProjectApi().getProject(projectPath).getId(); } } catch (GitLabApiException e) { return -1; } return -1; }
Example #10
Source File: GitLabOwner.java From gitlab-branch-source-plugin with MIT License | 6 votes |
@NonNull public static GitLabOwner fetchOwner(GitLabApi gitLabApi, String projectOwner) { try { Group group = gitLabApi.getGroupApi().getGroup(projectOwner); return new GitLabGroup(group.getName(), group.getWebUrl(), group.getAvatarUrl(), group.getId(), group.getFullName(), group.getDescription()); } catch (GitLabApiException e) { if (e.getHttpStatus() != 404) { throw new IllegalStateException("Unable to fetch Group", e); } try { User user = gitLabApi.getUserApi().getUser(projectOwner); // If user is not found, null is returned if (user == null) { throw new IllegalStateException( String.format("Owner '%s' is neither a user/group/subgroup", projectOwner)); } return new GitLabUser(user.getName(), user.getWebUrl(), user.getAvatarUrl(), user.getId()); } catch (GitLabApiException e1) { throw new IllegalStateException("Unable to fetch User", e1); } } }
Example #11
Source File: GitLabSCMFile.java From gitlab-branch-source-plugin with MIT License | 6 votes |
@NonNull @Override protected Type type() throws IOException, InterruptedException { if (isDir) { return Type.DIRECTORY; } try { gitLabApi.getRepositoryFileApi() .getFile(projectPath, getPath(), ref); return Type.REGULAR_FILE; } catch (GitLabApiException e) { if (e.getHttpStatus() != 404) { throw new IOException(e); } try { gitLabApi.getRepositoryApi().getTree(projectPath, getPath(), ref); return Type.DIRECTORY; } catch (GitLabApiException ex) { if (e.getHttpStatus() != 404) { throw new IOException(e); } } } return Type.NONEXISTENT; }
Example #12
Source File: GitLabSCMSource.java From gitlab-branch-source-plugin with MIT License | 5 votes |
protected Project getGitlabProject(GitLabApi gitLabApi) { if (gitlabProject == null) { try { gitlabProject = gitLabApi.getProjectApi().getProject(projectPath); sshRemote = gitlabProject.getSshUrlToRepo(); httpRemote = gitlabProject.getHttpUrlToRepo(); projectId = gitlabProject.getId(); } catch (GitLabApiException e) { throw new IllegalStateException("Failed to retrieve project " + projectPath, e); } } return gitlabProject; }
Example #13
Source File: AccessTokenUtils.java From gitlab4j-api with MIT License | 5 votes |
/** * Reads and returns the content from the provided URLConnection. * * @param connection the URLConnection to read the content from * @return the read content as a String * @throws GitLabApiException if any error occurs */ protected static String getContent(URLConnection connection) throws GitLabApiException { StringBuilder buf = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { reader.lines().forEach(b -> buf.append(b)); } catch (IOException ioe) { throw new GitLabApiException(ioe); } return (buf.toString()); }
Example #14
Source File: AccessTokenUtils.java From gitlab4j-api with MIT License | 5 votes |
/** * Logs out the user associated with the GitLab session cookie. * * @param baseUrl the GitLab server base URL * @param cookies the GitLab session cookie to logout * @throws GitLabApiException if any error occurs */ protected static final void logout(final String baseUrl, final String cookies) throws GitLabApiException { // Save so it can be restored later boolean savedFollowRedirects = HttpURLConnection.getFollowRedirects(); try { // Must manually follow redirects if (savedFollowRedirects) { HttpURLConnection.setFollowRedirects(false); } String urlString = baseUrl + "/users/sign_out"; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setRequestProperty("Cookie", cookies); connection.setRequestMethod("GET"); connection.setReadTimeout(10000); connection.setConnectTimeout(10000); // Make sure a redirect was provided, otherwise it is a logout failure int responseCode = connection.getResponseCode(); if (responseCode != 302) { throw new GitLabApiException("Logout failure, aborting!"); } } catch (IOException ioe) { throw new GitLabApiException(ioe); } finally { if (savedFollowRedirects) { HttpURLConnection.setFollowRedirects(true); } } }
Example #15
Source File: GitLabPipelineStatusNotifier.java From gitlab-branch-source-plugin with MIT License | 5 votes |
/** * Log comment on Commits and Merge Requests upon build complete. */ private static void logComment(Run<?, ?> build, TaskListener listener) { GitLabSCMSource source = getSource(build); if (source == null) { return; } final GitLabSCMSourceContext sourceContext = getSourceContext(build, source); if (!sourceContext.logCommentEnabled()) { return; } String url = getRootUrl(build); if (url.isEmpty()) { listener.getLogger().println( "Can not determine Jenkins root URL. Comments are disabled until a root URL is" + " configured in Jenkins global configuration."); return; } Result result = build.getResult(); LOGGER.log(Level.FINE, String.format("Log Comment Result: %s", result)); String note = ""; String symbol = ""; if (Result.SUCCESS.equals(result)) { if (!sourceContext.doLogSuccess()) { return; } symbol = ":heavy_check_mark: "; note = "The Jenkins CI build passed "; } else if (Result.UNSTABLE.equals(result)) { symbol = ":heavy_multiplication_x: "; note = "The Jenkins CI build failed "; } else if (Result.FAILURE.equals(result)) { symbol = ":heavy_multiplication_x: "; note = "The Jenkins CI build failed "; } else if (result != null) { // ABORTED, NOT_BUILT. symbol = ":no_entry_sign: "; note = "The Jenkins CI build aborted "; } String suffix = " - [Details](" + url + ")"; SCMRevision revision = SCMRevisionAction.getRevision(source, build); try { GitLabApi gitLabApi = GitLabHelper.apiBuilder(source.getServerName()); String sudoUsername = sourceContext.getSudoUser(); if (!sudoUsername.isEmpty()) { gitLabApi.sudo(sudoUsername); } final String buildName = "**" + getStatusName(sourceContext, build, revision) + ":** "; final String hash; if (revision instanceof BranchSCMRevision) { hash = ((BranchSCMRevision) revision).getHash(); gitLabApi.getCommitsApi().addComment( source.getProjectPath(), hash, symbol + buildName + note + suffix ); } else if (revision instanceof MergeRequestSCMRevision) { MergeRequestSCMHead head = (MergeRequestSCMHead) revision.getHead(); gitLabApi.getNotesApi().createMergeRequestNote( source.getProjectPath(), Integer.valueOf(head.getId()), symbol + buildName + note + suffix ); } else if (revision instanceof GitTagSCMRevision) { hash = ((GitTagSCMRevision) revision).getHash(); gitLabApi.getCommitsApi().addComment( source.getProjectPath(), hash, symbol + buildName + note + suffix ); } } catch (GitLabApiException e) { LOGGER.log(Level.WARNING, "Exception caught:" + e, e); } }
Example #16
Source File: ApplicationSettings.java From gitlab4j-api with MIT License | 5 votes |
public Object addSetting(String setting, Object value) throws GitLabApiException { Setting appSetting = Setting.forValue(setting); if (appSetting != null) { return (addSetting(appSetting, value)); } settings.put(setting, value); return (value); }
Example #17
Source File: SystemHookManager.java From gitlab4j-api with MIT License | 5 votes |
/** * Fire the event to the registered listeners. * * @param event the SystemHookEvent instance to fire to the registered event listeners * @throws GitLabApiException if the event is not supported */ public void fireEvent(SystemHookEvent event) throws GitLabApiException { if (event instanceof ProjectSystemHookEvent) { fireProjectEvent((ProjectSystemHookEvent) event); } else if (event instanceof TeamMemberSystemHookEvent) { fireTeamMemberEvent((TeamMemberSystemHookEvent) event); } else if (event instanceof UserSystemHookEvent) { fireUserEvent((UserSystemHookEvent) event); } else if (event instanceof KeySystemHookEvent) { fireKeyEvent((KeySystemHookEvent) event); } else if (event instanceof GroupSystemHookEvent) { fireGroupEvent((GroupSystemHookEvent) event); } else if (event instanceof GroupMemberSystemHookEvent) { fireGroupMemberEvent((GroupMemberSystemHookEvent) event); } else if (event instanceof PushSystemHookEvent) { firePushEvent((PushSystemHookEvent) event); } else if (event instanceof TagPushSystemHookEvent) { fireTagPushEvent((TagPushSystemHookEvent) event); } else if (event instanceof RepositorySystemHookEvent) { fireRepositoryEvent((RepositorySystemHookEvent) event); } else if (event instanceof MergeRequestSystemHookEvent) { fireMergeRequestEvent((MergeRequestSystemHookEvent) event); } else { String message = "Unsupported event, event_named=" + event.getEventName(); LOGGER.warning(message); throw new GitLabApiException(message); } }
Example #18
Source File: SystemHookManager.java From gitlab4j-api with MIT License | 5 votes |
/** * Verifies the provided Event and fires it off to the registered listeners. * * @param event the Event instance to handle * @throws GitLabApiException if the event is not supported */ public void handleEvent(SystemHookEvent event) throws GitLabApiException { if (event != null) { LOGGER.info("handleEvent:" + event.getClass().getSimpleName() + ", eventName=" + event.getEventName()); fireEvent(event); } else { LOGGER.warning("handleEvent: provided event cannot be null!"); } }
Example #19
Source File: ApplicationSettings.java From gitlab4j-api with MIT License | 5 votes |
public Object addSetting(Setting setting, Object value) throws GitLabApiException { if (value instanceof JsonNode) { value = jsonNodeToValue((JsonNode)value); } setting.validate(value); settings.put(setting.toString(), value); return (value); }
Example #20
Source File: CommitAction.java From choerodon-starters with Apache License 2.0 | 5 votes |
public CommitAction withFileContent(File file, String filePath, Encoding encoding) throws GitLabApiException { this.encoding = (encoding != null ? encoding : Encoding.TEXT); this.filePath = filePath; try { content = FileUtils.getFileContentAsString(file, this.encoding); } catch (IOException e) { throw new GitLabApiException(e); } return (this); }
Example #21
Source File: CommitAction.java From gitlab4j-api with MIT License | 5 votes |
public CommitAction withFileContent(File file, String filePath, Encoding encoding) throws GitLabApiException { this.encoding = (encoding != null ? encoding : Encoding.TEXT); this.filePath = filePath; try { content = FileUtils.getFileContentAsString(file, this.encoding); } catch (IOException e) { throw new GitLabApiException(e); } return (this); }
Example #22
Source File: GitLabSCMFileSystem.java From gitlab-branch-source-plugin with MIT License | 5 votes |
@Override public long lastModified() throws IOException { try { return gitLabApi.getCommitsApi().getCommit(projectPath, ref).getCommittedDate().getTime(); } catch (GitLabApiException e) { throw new IOException("Failed to retrieve last modified time", e); } }
Example #23
Source File: GitUtils.java From swagger-showdoc with Apache License 2.0 | 5 votes |
/** * 获取项目id * @param projectName * @return */ private static Integer getProjectId(String projectName){ try { List<Project> projects = gitLabApi.getProjectApi().getProjects(projectName); if(projects.size() == 1){ return projects.get(0).getId(); } } catch (GitLabApiException e) { e.printStackTrace(); } return null; }
Example #24
Source File: GitLabWebHookAction.java From gitlab-branch-source-plugin with MIT License | 5 votes |
public HttpResponse doPost(StaplerRequest request) throws IOException, GitLabApiException { if (!request.getMethod().equals("POST")) { return HttpResponses .error(HttpServletResponse.SC_BAD_REQUEST, "Only POST requests are supported, this was a " + request.getMethod() + " request"); } if (!"application/json".equals(request.getContentType())) { return HttpResponses .error(HttpServletResponse.SC_BAD_REQUEST, "Only application/json content is supported, this was " + request .getContentType()); } String type = request.getHeader("X-Gitlab-Event"); if (StringUtils.isBlank(type)) { return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "Expecting a GitLab event, missing expected X-Gitlab-Event header"); } String secretToken = request.getHeader("X-Gitlab-Token"); if(!isValidToken(secretToken)) { return HttpResponses.error(HttpServletResponse.SC_UNAUTHORIZED, "Expecting a valid secret token"); } String origin = SCMEvent.originOf(request); WebHookManager webHookManager = new WebHookManager(); webHookManager.addListener(new GitLabWebHookListener(origin)); webHookManager.handleEvent(request); return HttpResponses.ok(); // TODO find a better response }
Example #25
Source File: GitLabSCMFile.java From gitlab-branch-source-plugin with MIT License | 5 votes |
private List<TreeItem> fetchTree() throws IOException { try { return gitLabApi.getRepositoryApi().getTree(projectPath, getPath(), ref); } catch (GitLabApiException e) { throw new IOException(String.format("%s not found at %s", getPath(), ref)); } }
Example #26
Source File: GitLabSystemHookAction.java From gitlab-branch-source-plugin with MIT License | 5 votes |
public HttpResponse doPost(StaplerRequest request) throws GitLabApiException { if (!request.getMethod().equals("POST")) { return HttpResponses .error(HttpServletResponse.SC_BAD_REQUEST, "Only POST requests are supported, this was a " + request.getMethod() + " request"); } if (!"application/json".equals(request.getContentType())) { return HttpResponses .error(HttpServletResponse.SC_BAD_REQUEST, "Only application/json content is supported, this was " + request .getContentType()); } String type = request.getHeader("X-Gitlab-Event"); if (StringUtils.isBlank(type)) { return HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "Expecting a GitLab event, missing expected X-Gitlab-Event header"); } String secretToken = request.getHeader("X-Gitlab-Token"); if(!isValidToken(secretToken)) { return HttpResponses.error(HttpServletResponse.SC_UNAUTHORIZED, "Expecting a valid secret token"); } String origin = SCMEvent.originOf(request); SystemHookManager systemHookManager = new SystemHookManager(); systemHookManager.addListener(new GitLabSystemHookListener(origin)); systemHookManager.handleEvent(request); return HttpResponses.ok(); // TODO find a better response }
Example #27
Source File: GitLabSCMFile.java From gitlab-branch-source-plugin with MIT License | 5 votes |
private InputStream fetchFile() throws IOException { try { return gitLabApi.getRepositoryFileApi().getRawFile(projectPath, ref, getPath()); } catch (GitLabApiException e) { throw new IOException(String.format("%s not found at %s", getPath(), ref)); } }
Example #28
Source File: GitLabSCMSource.java From gitlab-branch-source-plugin with MIT License | 5 votes |
public HashMap<String, AccessLevel> getMembers() { HashMap<String, AccessLevel> members = new HashMap<>(); try { GitLabApi gitLabApi = apiBuilder(serverName); for (Member m : gitLabApi.getProjectApi().getAllMembers(projectPath)) { members.put(m.getUsername(), m.getAccessLevel()); } } catch (GitLabApiException e) { LOGGER.log(Level.WARNING, "Exception while fetching members" + e, e); return new HashMap<>(); } return members; }
Example #29
Source File: CommitAction.java From gitlab4j-api with MIT License | 4 votes |
public CommitAction withFileContent(String filePath, Encoding encoding) throws GitLabApiException { File file = new File(filePath); return (withFileContent(file, filePath, encoding)); }
Example #30
Source File: WebHookManager.java From gitlab4j-api with MIT License | 4 votes |
/** * Fire the event to the registered listeners. * * @param event the Event instance to fire to the registered event listeners * @throws GitLabApiException if the event is not supported */ public void fireEvent(Event event) throws GitLabApiException { switch (event.getObjectKind()) { case BuildEvent.OBJECT_KIND: fireBuildEvent((BuildEvent) event); break; case IssueEvent.OBJECT_KIND: fireIssueEvent((IssueEvent) event); break; case JobEvent.OBJECT_KIND: fireJobEvent((JobEvent) event); break; case MergeRequestEvent.OBJECT_KIND: fireMergeRequestEvent((MergeRequestEvent) event); break; case NoteEvent.OBJECT_KIND: fireNoteEvent((NoteEvent) event); break; case PipelineEvent.OBJECT_KIND: firePipelineEvent((PipelineEvent) event); break; case PushEvent.OBJECT_KIND: firePushEvent((PushEvent) event); break; case TagPushEvent.OBJECT_KIND: fireTagPushEvent((TagPushEvent) event); break; case WikiPageEvent.OBJECT_KIND: fireWikiPageEvent((WikiPageEvent) event); break; default: String message = "Unsupported event object_kind, object_kind=" + event.getObjectKind(); LOGGER.warning(message); throw new GitLabApiException(message); } }