Giter Club home page Giter Club logo

gerrit-rest-java-client's Introduction

gerrit-rest-java-client

Linux Build Windows Build Coverage Status Quality Gate Status Maintainability Rating Maven Central

Introduction

Java implementation of the Gerrit Code Review Tool REST API.

Only Gerrit 2.6 or newer is supported (missing / incomplete REST API in older versions).

This implementation is used for example as base for the Gerrit IntelliJ Plugin.

Many different authentication-methods are supported (HTTP basic, HTTP digest, LDAP with form, HTTP password from Gerrit setting, ...).

Usage

This library implements com.google.gerrit.extensions.api.GerritApi.

You just need a few lines to get it working:

GerritRestApiFactory gerritRestApiFactory = new GerritRestApiFactory();
GerritAuthData.Basic authData = new GerritAuthData.Basic("http://localhost:8080");
// or: authData = new GerritAuthData.Basic("https://example.com/gerrit", "user", "password");
GerritApi gerritApi = gerritRestApiFactory.create(authData);
List<ChangeInfo> changes = gerritApi.changes().query("status:merged").withLimit(10).get();

If you like to write a script instead of a full Java application, you might want to use Groovy. There is a basic Groovy example available.

Note: It is not guaranteed that all interfaces are implemented. If an implementation is missing, you get a com.google.gerrit.extensions.restapi.NotImplementedException. Feel free to implement it and create a pull request at GitHub - it is quite easy! :)

Note: The source of com.google.gerrit.extensions is included in this repository at the moment because not all extensions to this API are merged into Gerrit repository yet.

Maven Artifact

Releases are available with Maven:

<dependency>
    <groupId>com.urswolfer.gerrit.client.rest</groupId>
    <artifactId>gerrit-rest-java-client</artifactId>
    <version>0.9.7</version>
</dependency>

Android Support

Apache HttpClient causes problems on Android platform. There is a workaround by using HttpClient for Android. Android support builds are not officially released, but you should be able to create your own build by using the httpclient-android branch. You probably want to merge master branch into this branch before building it.

Dependencies

This library depends on Apache HttpClient, Gson and Guava.

Your Support

If you like this library, you can support it:

  • Star it: Star it at GitHub. GitHub account required.
  • Improve it: Report bugs or feature requests. Or even fix / implement them by yourself - everything is open source!
  • Donate: You can find donation-possibilities at the bottom of this file.

Donations

If you like this work, you can support it with this donation link. If you don't like Paypal (Paypal takes 2.9% plus $0.30 per transaction fee from your donation), please contact me. Please only use the link from github.com/uwolfer/gerrit-intellij-plugin to verify that it is correct.

Copyright and license

Copyright 2013 - 2018 Urs Wolfer

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

gerrit-rest-java-client's People

Contributors

anaidoo avatar aschi avatar cameleeck avatar dependabot[bot] avatar edwinkempin avatar efregnan avatar forrert avatar hongkailiu avatar irissmann avatar isotes avatar johannesc avatar junqiuhanzhong avatar keylorsdu avatar kphi avatar leonard84 avatar liudongmiao avatar lucamilanesio avatar magnayn avatar martinthink avatar pmoorewand avatar reda-alaoui avatar sschuberth avatar sstafford avatar stephanemartin avatar sydowma avatar timrcoulson avatar trygvis avatar uwolfer avatar vitalca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gerrit-rest-java-client's Issues

WorkInProgressInput class is missing

While working on the method SetWorkInProgress, I noticed that the class WorkInProgressInput is not contained in java/com/google/gerrit/extensions/api/changes.

However, my understanding is that this class is necessary for the method SetWorkInProgress to work with a message (the documentation is here).

I have already opened a discussion on the Gerrit google group about this, but I am opening a issue report here as well to keep track of this problem.

Incorrect credentials will still "authenticate" on an open Gerrit instance

Let's say you have a Gerrit instance that allows anonymous, unregistered users to access the REST interface, but doesn't permit anonymous cloning/fetching etc.
If you then try and authenticate with incorrect credentials, instead of failing, the client will not bother with the authentication step and neglect the "/a/" appendix. This works for cases where you want to retrieve data from the REST interface, no matter what. However, it means there is no way to test credentials on the aforementioned Gerrit instance.
I'm thinking that an option might be useful whereby the REST client will always try authenticated requests, regardless of the Gerrit servers authentication policy.
If I've missed this in the source code, apologies!

Incompatibility with Gerrit <= v2.14

When using the Java client with Gerrit v2.14 (or earlier) the ChangeApiRestClient.get() would cause Gerrit to fail with the following error: com.urswolfer.gerrit.client.rest.http.HttpStatusException: Request not successful. Message: Bad Request. Status-Code: 400. Content: "TRACKING_IDS" is not a valid value for "-o"..

This is causing the Gerrit Code Review plugin for Jenkins to fail (see reported Issue JENKINS-60364).

Gerrit Api for Changes return "null" for several attributes

Hi All,

I tried this snippet (based on the given example "Basic.groovy")

List changes = gerritApi.changes().query('is:open+project:syssw/jenkins+branch:ci_devel+label:verified=0').withLimit(2).get()

changes.each { ci ->
println "subject => ${ci.subject}"
println "project => ${ci.project}"
println "revisions => ${ci.revisions}"
println "currentRevision => ${ci.currentRevision}"
}

Output:
subject => my_subject for example
project => my_tes_project
_number => 43239
revisions => null
currentRevision => null

I think that the parsing of the json output is not accurate.
there are several json responses.

reference https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change-detail

also I noticed that "currentRevision" should be "current_revision".

XSRF_TOKEN

Hello,I have a very odd problem for help.Same user and password,one can connect,one not.
image
image
I use the Fiddler analysis the http information,I found the fail reason is missing XSRF_TOKEN cookie
image and I don't know why
Please help

How to get change detail??

Hi,

What will be the code for viewing detail of a particular change?
How to use o option for using detailed_labels??

Tried this :
gerritApi.changes.id(cid).get()

But got exception: -o web_links not supported

Please help me getting detail of a change using this library

Users of this library are causing DDoS against GerritHub.io

We start receiving a lot of authentication requests looping and generating traffic from multiple IPs to GerritHub.io.

I believe the problem is associated to the way the authentication is managed in the library.
See the culprit of the problem.

The problem is that the client assumes that a non-50x and non-401 is a successful authentication. However, when people are using GerritHub.io, the login would bring them to the OAuth handshake after having requested the authentication scope to apply.

The form-based authentication won't work at all from an API perspective. The library should detect this situation and fallback to the regular basic authentication of the REST-API, which would use the username/password generated in Gerrit rather than OAuth.

SocketException with multiple requests

Hi there, I'm developing a tool which collects metrics from gerrit and I'm using this library to get access to the gerrit rest api.
The root of my problem is that the endpoint "/changes//comments" is not working according to https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-comments
(I tested directly in the browser, I know this is not implemented in the current library version).

Then, in order to collect all comments from all patchs I have to query revision by revision:
For each change previously retrieved I perform a new request like bellow so the comments are available:

RevisionApi api = gerritApi.changes().id(changeid).revision(revid); return api.comments();

It have been working but not quite always, sometimes after some successful requests I got:

o.apache.http.impl.execchain.RetryExec: I/O exception (org.apache.http.NoHttpResponseException) caught when processing request to {}->http://gerrit:80: The target server failed to respond
o.apache.http.impl.execchain.RetryExec: Retrying request to {}->http://gerrit:80
o.apache.http.impl.execchain.RetryExec: I/O exception (java.net.SocketException) caught when processing request to {}->http://gerrit:80: Connection reset

I'm wondering that perhaps it might be a gerrit configuration which is preventing requests after some amount.

What do you think?
Regards
Carlos

use fileApi to send diffrequest get 404 fail

I use the following way to get diffInfo, the param file is "src/server/api/v1/router.py" like this, it will be encoded by URLEncoder to "src%2Fserver%2Fapi%2Fv1%2Frouter.py",then send this path to url as a http request ,the http.request in httpcontext is “{http.request=GET /a/changes/292672/revisions/34736b70222534bae851f0455fcf53ef6b731d72/files/cps/server/api/v1/router.py/diff HTTP/1.1”, and i get 404 fail say "not found server". I guess it may because the http.request in httpcontext should be “{http.request=GET /a/changes/292672/revisions/34736b70222534bae851f0455fcf53ef6b731d72/files/cps%2Fserver%2Fapi%2Fv1%2Frouter.py/diff HTTP/1.1”, because when the file param is "config_rc_v1.c",there is not "/" in it , the response is 200, and i get vaild diffInfo. So i submit the issue , hope you can help me, thank you very much!
image

image

image
image
image
image
image

Authentication failure when Gerrit server is unavailable at first request

It looks like a caching issue when Gerrit server is not available at first request. I can reproduce this issue in my setup with an Nginx reverse proxy using htaccess login.

When using the IntelliJ plugin, IntelliJ needs to be restarted after such a failure in order to get the plugin working.

Threadsafety of Library?

Hello!

I was interested in some information regarding the threadsafety of this library (the GerritApi object). I did some reading of the source and found some low level locking (in CookieStore for example), but I wanted to make sure that the library is considered threadsafe in its entirety. How will it handle 15-20 threads pounding the same GerritApi object?

Also as a sidenote, is it safe to have multiple GerritApi objects floating around in the wild (do they share any static non-threadsafe members?)

Thank you very much for your time, and for creating this library.

Liam.

Consider using testcontainers and the gerrit docker images for "real" tests of code.

Not really an issue as closer to a discussion point.
I maintain a similar project as part of testing a modified gerrit code base with my work.
As part of testing that client I've employed the TestContainers package and spin up real gerrit instances on docker as part of the verify step in maven.
I've noticed the RealServerTest class and have used it when working out the PR's I've sent in here, and I was wondering if an integration suite utilising gerrit docker is something this project would be interested in?
Source of current usage I am referring to is here, I use this project's client to prep system for testing the client I'm running.
https://github.com/WANdisco/gerrit-sshd-java-client/blob/main/src/test/java/integration/utils/TestBase.java

get labels for specific review

I can get the LabelInfo from a ChangeInfo, but this only gives you the last reviews for a merged change. I'd like to get the reviews for each revision in the patch set. I think I can get this information via:

GET /changes/{change-id}/revisions/{revision-id}/review

but I don't see any way to fetch it via the Java API. Is this something that hasn't yet been implemented?

Reduce number of Parser classes

While working to expand the functionalities supported by the API, I noticed that so far we have followed the paradigm of having one Parser class per data type to extract: e.g., one for CommentInfo entities, one for CommitInfo entities, and so on.

However, this adds a lot of load in terms of parameters passed to the constructor of some classes (for example, ChangeApiRestClient or RevisionApiRestClient).
I think it would good to do something about it.

I would propose to cluster together related methods in a "bigger" parser class: e.g., we could have a ReviewerParser class that groups together the classes AddReviewerResultParser, SuggesterReviewerInfoParser, and ReviewerInfoParser.

What do you think? I believe it would benefit the usability of the code to improve this.
Also, I am open to any suggestion on how to do this.

Thank you!

CommitApi file endpoint

Hey, it's currently possible to query the contents of a file in a commit (rather than all the files in that commit) via the Gerrit rest api, however there isn't a method for this exposed in the CommitApi java class. I was wondering if I wanted to add this to your project, would I first need to add a method for it to the main Gerrit repo, or would it be okay to just add here?

Possibility of getting a new release

Hello @uwolfer,
Just raising if it is possible to get a new release of the project?
I am releasing some internal code that utilises the recent pull requests.
No issues if there are no current plans to.
Many thanks.

failed to get gerrit changes

Request not successful. Message: Bad Request. Status-Code: 400. Content: "-o" is not a valid option.
i want to know how to resolve the error when click the commit changes

query fail with multi conditions

I created a new label:Autosubmit in my gerrit server. I need to use the label to do someting. But when I add the label to query, it will have some exceptions.

java.lang.IllegalArgumentException: Illegal character in query at index 62: http://aml-code-master.amlogic.com:8080/changes/?q=status:open (label:Code-Review=2 AND label:Autosubmit=1)&n=100&o=DETAILED_LABELS&o=DETAILED_ACCOUNTS
at java.net.URI.create(Unknown Source)
at org.apache.http.client.methods.HttpGet.(HttpGet.java:66)
at com.urswolfer.gerrit.client.rest.http.GerritRestClient.request(GerritRestClient.java:216)
at com.urswolfer.gerrit.client.rest.http.GerritRestClient.requestRest(GerritRestClient.java:180)
at com.urswolfer.gerrit.client.rest.http.GerritRestClient.requestRest(GerritRestClient.java:172)
at com.urswolfer.gerrit.client.rest.http.GerritRestClient.requestJson(GerritRestClient.java:149)
at com.urswolfer.gerrit.client.rest.http.GerritRestClient.getRequest(GerritRestClient.java:118)
at com.urswolfer.gerrit.client.rest.http.changes.ChangesRestClient.get(ChangesRestClient.java:114)
at com.urswolfer.gerrit.client.rest.http.changes.ChangesRestClient.access$0(ChangesRestClient.java:89)
at com.urswolfer.gerrit.client.rest.http.changes.ChangesRestClient$1.get(ChangesRestClient.java:79)
at com.aml.gerrit.MainEntry.run(MainEntry.java:73)
at com.aml.gerrit.MainEntry.main(MainEntry.java:39)
Caused by: java.net.URISyntaxException: Illegal character in query at index 62: http://aml-code-master.amlogic.com:8080/changes/?q=status:open (label:Code-Review=2 AND label:Autosubmit=1)&n=100&o=DETAILED_LABELS&o=DETAILED_ACCOUNTS
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.(Unknown Source)
... 12 more

Content: "--query2" is not a valid option

When I use the query method, it fails.

I found this code in GroupRestClient.java

if (!Strings.isNullOrEmpty(queryRequest.getQuery())) {
            // param is "query2", not "query".
            query = UrlUtils.appendToUrlQuery(query, "query2=" + queryRequest.getQuery());
        }

Why is query2 written here? If query2 is used, an error will be reported, and query will not be wrong. The version of gerrit I use is 3.3.1

not support HTTP digest auth?

if I want to use https and HTTP digest auth , I must over write GerritRestClient.java .
I suggest you can use HttpClientBuilderExtension.class support basic auth.

Support for plugin APIs

Many Gerrit plugins provide their own REST APIs. I was wondering if it would be appropriate to add support for Gerrit plugin APIs in this package?

My question is generally for any Gerrit plugin but my specific use case is for the verify-status plugin[1]. I would like to create a Jenkins plugin that can call the verify-status REST endpoints using this client.

[1] https://gerrit.googlesource.com/plugins/verify-status/+/master/src/main/resources/Documentation/rest-api-changes.md

Need to calculate review time for Gerrit

Hi,

Can anybody tell how can i calculate review time from this ?
I was planning to use /detail REST call but dint find any method for it. I need to have time at which reviewer gave +2 to the code.

Could anybody please tell me how to code for detail of changes or any other alternative to get review time?

Tests fail on Windows

I just realized mvn -B test failes on Windows with:

testParseSingleUserInfos(com.urswolfer.gerrit.client.rest.http.accounts.AccountsParserTest)  Time elapsed: 0.005 sec  <<< FAILURE!
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 3 path $
    at com.google.gson.JsonParser.parse(JsonParser.java:65)
    at com.urswolfer.gerrit.client.rest.http.common.AbstractParserTest.getJsonElement(AbstractParserTest.java:35)
    at com.urswolfer.gerrit.client.rest.http.accounts.AccountsParserTest.testParseSingleUserInfos(AccountsParserTest.java:70)
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 3 path $
    at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1574)
    at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1423)
    at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:546)
    at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
    at com.google.gson.JsonParser.parse(JsonParser.java:60)
    ... 36 more

So it seems this is because of the magic prefix ()]}') in Gerrit's responses. Interestingly, I couldn't find any code that handles this magic prefix. So comes the test pass on Linux if the magic prefix is not stripped before the JSON string is passed to gson?

Request a 0.8.9 release build

Can you produce a 0.8.9 release build? I need access to some of the fixes that have been introduced since the last 0.8.8 release in April 2016.

Thanks,
Shawn

Sortkey not working?

Hi,
I am aware of the gerrit limit of 500 changes per query. However, according to the APIs, the last change of the list should contain a sortkey to continue from that particular change.

When I run it, sortkey of the last element is null.

Here the code:

List<ChangeInfo> changes = gerritApi.changes().query(status).withOptions(ListChangesOption.ALL_FILES, ListChangesOption.ALL_REVISIONS, ListChangesOption.DETAILED_ACCOUNTS).get();
System.out.println("Size: " + changes.size());
ChangeInfo test = changes.get(changes.size() - 1);        
System.out.println("Key: " + test._sortkey);
System.out.println("More changes: " + test._moreChanges);

The output is:

Size: 500
Sortkey: null
More changes: true

What am I wrong?

How do I get comments to a file?

I can see in the REST API that a call is supposed to be made to URL /changes/{change-id}/detail but I don't see in the Java API source where a call is made to get details, but I do see the CommentInfo class in the jar (and the parser and unit test - nice mocking BTW), but I can't figure out how I'm supposed to get the CommentInfo from the Java API. Any help?

code-review +1 how to do it

sorry,man,My english is not very good,but i encountered some problems;
i want to do like ssh -p 29418 [email protected] gerrit review 17,1 --code-review +1

--code-review 1
but i dont know how to use this library to do it,thx

I'm sorry to bother you.

How to get Diff between patches

Hi, I am new to this API and I would like to extract some information about the diff between two patch sets (or between files in the patch sets).
I have seen that this project implements the classes DiffInfo and DiffWebLinkInfo, but I can't understand how can I link to them from the information that I obtain using the class GerritApi.

Could you please help me?

Thank you very much.

The client cannot retrieve file content if the file name contains "+"

Hello,

I am using v0.9.3, trying to retrieve files from an unmerged commit.
For all files with "+" in the names I get com.urswolfer.gerrit.client.rest.http.HttpStatusException: Request not successful. Message: Not Found. Status-Code: 404. Content: Not Found.

The client performs URL encoding for all file names in com.urswolfer.gerrit.client.rest.http.changes.FileApiRestClient#requestPath, and if I copy a URL of the file/content just before diving into Apache HttpClient and perform a GET request using curl it works as expected.

However, later in org.apache.http.impl.execchain.ProtocolExec#execute a method rewriteRequestURI() is executed, and properly encoded %2B became + again:

// Re-write request URI if needed
rewriteRequestURI(request, route, context.getRequestConfig().isNormalizeUri());

By default org.apache.http.client.config.RequestConfig#isNormalizeUri equals to true:

/**
 * Determines whether client should normalize URIs in requests or not.
 * <p>
 * Default: {@code true}
 * </p>
 *
 * @since 4.5.8
 */
public boolean isNormalizeUri() {
    return normalizeUri;
}

Is there a workaround?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.