I use this code to get all commits from Guthub. I would like to get the commits only from today.
public void listCommits(String user_name, String password) throws IOException
{
GitHubClient client = new GitHubClient();
client.setCredentials(user_name, password);
RepositoryService service = new RepositoryService(client);
List<Repository> repositories = service.getRepositories();
for (int i = 0; i < repositories.size(); i++)
{
Repository get = repositories.get(i);
System.out.println("Repository Name: " + get.getName());
CommitService commitService = new CommitService(client);
for (RepositoryCommit commit : commitService.getCommits(get))
{
System.out.println("Repository commit: " + commit.getCommit().getMessage());
System.out.println("Repository commit date : " + commit.getCommit().getCommitter().getDate());
}
}
}
Is there any way to get the commits only from today?
Always good to know which library are you using.
Github API has "since" and "until" parameters:
https://developer.github.com/v3/repos/commits/
Also those arguments are available in the Kohsuke's library:
https://github.com/kohsuke/github-api/blob/master/src/main/java/org/kohsuke/github/GHCommitQueryBuilder.java
Using "since" and "until" parameters will save you from requesting unneeded data and making too many requests to the server.
The library is also available in Maven central:
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>github-api</artifactId>
<version>1.77</version>
</dependency>
Here's the sample code that worked for me:
Properties props = new Properties();
props.setProperty("login", "somebody#somewhere.com");
props.setProperty("password", "YourGithubPassword");
GitHub gitHub = GitHubBuilder.fromProperties(props).build();
GHRepository repository = gitHub.getRepository("your/repo");
Calendar cal = Calendar.getInstance();
cal.set(2014, 0, 4);
Date since = cal.getTime();
cal.set(2014, 0, 14);
Date until = cal.getTime();
GHCommitQueryBuilder queryBuilder = repository.queryCommits().since(since).until(until);
PagedIterable<GHCommit> commits = queryBuilder.list();
Iterator<GHCommit> iterator = commits.iterator();
while (iterator.hasNext()) {
GHCommit commit = iterator.next();
System.out.println("Commit: " + commit.getSHA1() + ", info: " + commit.getCommitShortInfo().getMessage() + ", author: " + commit.getAuthor());
}
Related
I'm trying to use JGit to pull a log of commits done by developers using a Github security token. I tried googling a lot, but the documentation is scarce on this. The code that I am currently tinkering with looks like this:
public class GitIntegration {
public GitIntegration() {
}
public Iterable<RevCommit> getCommits() throws IOException, InvalidRefNameException, GitAPIException {
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.setMustExist( true );
repositoryBuilder.setGitDir( new File ("https://oauth2:xyzxyzTOKENxyzxyz#github.com/myuser/myrepo.git"));
Repository repository = repositoryBuilder.build();
try (Git git = new Git(repository)) {
Iterable<RevCommit> commits = git.log().all().call();
int count = 0;
for (RevCommit commit : commits) {
System.out.println("LogCommit: " + commit);
count++;
}
System.out.println(count);
return commits;
}
}
}
But I am getting the following error:
java.nio.file.InvalidPathException: Illegal char <:> at index 5:
https:\oauth2:xyzxyzTOKENxyzxyz#github.com\myuser\myrepo.git\config
sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
It doesn't work to throw git syntax in the File constructor like that at all. Does anyone know of a way to authenticate with tokens and then be able to use the git.log() method?
Thanks!
After digging around a bit, I decided to go with the Kohsuke github library instead. When doing that it was quite straightforward. Posting basic code example for reference. (Please note that this if for Enterprise Git. If you are doing it for "normal" Git, look into the Kohsuke documentation, you will need to use another method instead of connectToEnterpriseWithOAuth.)
import org.kohsuke.github.*;
public class GitIntegration {
public GitIntegration() {
}
public String getCommits(String repo) {
String retval = "";
try {
GitHub gitHub = GitHub.connectToEnterpriseWithOAuth("https://git.our.company.com/api/v3", "my.email#ourcompany.com", "xyzxyzTokenxyzxyz");
GHMyself me = gitHub.getMyself();
GHRepository repository = gitHub.getRepository("Gituser/"+repo);
Calendar cal = Calendar.getInstance();
cal.set(2020, 10, 4);
Date since = cal.getTime();
GHCommitQueryBuilder queryBuilder = repository.queryCommits().since(since).until(new Date());
PagedIterable<GHCommit> commits = queryBuilder.list();
Iterator<GHCommit> iterator = commits.iterator();
while (iterator.hasNext()) {
GHCommit commit = iterator.next();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
GHUser user = commit.getAuthor();
String name = "";
if(user != null) name = user.getName();
String message = commit.getCommitShortInfo().getMessage();
retval = retval.concat(message + " | " + name + " | " + sdf.format(commit.getCommitDate()) + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
retval = e.getCause().getMessage();
e.printStackTrace();
}
return retval;
}
}
I want to execute MQL (metric query language) using below library.
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-monitoring</artifactId>
<version>v3-rev540-1.25.0</version>
</dependency>
Here is my code snippet. which will create monitoring client and will try to collect data from GCP monitoring.
public void queryTimeSeriesData() throws IOException {
// create monitoring
Monitoring m = createAuthorizedMonitoringClient();
QueryTimeSeriesRequest req = new QueryTimeSeriesRequest();
String query = "fetch consumed_api\n" +
"| metric 'serviceruntime.googleapis.com/api/request_count'\n" +
"| align rate(2m)\n" +
"| every 2m\n" +
"| group_by [metric.response_code],\n" +
" [value_request_count_max: max(value.request_count)]";
req.setQuery(query);
HashMap<String, Object> queryTransformationSpec = new HashMap<String, Object>();
HashMap<String, Object> timingState = new HashMap<String, Object>();
HashMap<String, Object> absoluteWindow = new HashMap<String, Object>();
absoluteWindow.put("startTime", "2020-09-03T12:40:00.000Z");
absoluteWindow.put("endTime", "2020-09-03T13:41:00.000Z");
timingState.put("absoluteWindow", absoluteWindow);
timingState.put("graphPeriod", "60s");
timingState.put("queryPeriod", "60s");
queryTransformationSpec.put("timingState", timingState);
req.set("queryTransformationSpec", queryTransformationSpec);
req.set("reportPeriodicStats", false);
req.set("reportQueryPlan", false);
QueryTimeSeriesResponse res = m.projects().timeSeries().query("projects/MY_PROJECT_NAME", req).execute();
System.out.println(res);
}
Above code is working fine but its not returning data of given startTime and endTime ,
It always returns latest datapoint available. is there any problem with my code ?
Found way to execute MQL query with given time range. The
new working code is the following:
public void queryTimeSeriesData() throws IOException {
// create monitoring
Monitoring m = createAuthorizedMonitoringClient();
QueryTimeSeriesRequest req = new QueryTimeSeriesRequest();
String query = "fetch consumed_api\n" +
"| metric 'serviceruntime.googleapis.com/api/request_count'\n" +
"| align rate(5m)\n" +
"| every 5m\n" +
"| group_by [metric.response_code],\n" +
" [value_request_count_max: max(value.request_count)]" +
"| within d'2020/09/03-12:40:00', d'2020/09/03-12:50:00'\n";
req.setQuery(query);
QueryTimeSeriesResponse res = m.projects().timeSeries().query("projects/MY_PROJECT_NAME", req).execute();
System.out.println(res);
}
Included query start time and end time in query itself by using within operator. As per google docs for MQL queries:
within - Specifies the time range of the query output.
I need list of commits from a date extracted from last Jenkins Build and get a list of merge commits since that date.
I've coded so far to obtain list of merge commits. Just need a solution to extract these commits between specified dates.
Reference code:
public static void main(String[] args)throws IOException , GitAPIException{
ArrayList<String> CommitIds=new ArrayList<String>();
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.setMustExist( true );
repositoryBuilder.setGitDir(new File("/path/to/repo"));
Repository repo = repositoryBuilder.build();
Git git = Git.open( new File( "/path/to/repo" ) );
RevWalk walk = new RevWalk(repo);
git.checkout().setName("branch").call();
String branchName=repo.getBranch();
System.out.println(branchName);
Iterable<RevCommit> commits = git.log().all().call();
RevCommit masterHead = walk.parseCommit( repo.resolve( "refs/heads/master" ));
for (RevCommit commit : commits) {
boolean foundInThisBranch = false;
RevCommit otherHead = walk.parseCommit(repo.resolve(
commit.getName()));
for (Map.Entry<String, Ref> e : repo.getAllRefs().entrySet()) {
if (e.getKey().startsWith(Constants.R_HEADS)) {
if (walk.isMergedInto(otherHead, walk.parseCommit(
e.getValue().getObjectId()))) {
String foundInBranch = e.getValue().getName();
if (branchName.equals(foundInBranch)) {
foundInThisBranch = true;
break;
}
}
}
}
if (foundInThisBranch)
{
CommitIds.add(commit.getName());
}
}
System.out.println(CommitIds);
}
You can use LogCommand#setRevFilter(RevFilter) with CommitTimeRevFilter#between(Date,Date), e. g.:
ObjectId masterId = git.getRepository().exactRef("refs/heads/master").getObjectId();
Date since = new SimpleDateFormat("yyyy-MM-dd").parse("2017-08-01");
Date until = new SimpleDateFormat("yyyy-MM-dd").parse("2017-08-10");
RevFilter between = CommitTimeRevFilter.between(since, until);
for (RevCommit commit : git.log().add(masterId).setRevFilter(between).call()) {
System.out.println( "* "
+ commit.getId().getName()
+ " "
+ commit.getShortMessage());
}
I was using facebook FQL query to fetch sharecount for multiple URLS using this code without needing any access token.
https://graph.facebook.com/fql?q=";
"SELECT url, total_count,share_count FROM link_stat WHERE url in (";
private void callFB(List validUrlList,Map> dataMap,long timeStamp,Double calibrationFactor){
try {
StringBuilder urlString = new StringBuilder();
System.out.println("List Size " + validUrlList.size());
for (int i = 0; i < (validUrlList.size() - 1); i++) {
urlString.append("\"" + validUrlList.get(i) + "\",");
}
urlString.append("\""
+ validUrlList.get(validUrlList.size() - 1) + "\"");
String out = getConnection(fbURL+URLEncoder.encode(
queryPrefix
+ urlString.toString() + ")", "utf-8"));
dataMap = getSocialPopularity(validUrlList.toArray(), dataMap);
getJSON(out, dataMap, timeStamp,calibrationFactor);
} catch (Exception e) {
e.printStackTrace();
}
}
But as now Facebook has depreciated it i am planning to use
https://graph.facebook.com/v2.5/?ids=http://timesofindia.indiatimes.com/life-style/relationships/soul-curry/An-NRI-bride-who-was-tortured-to-hell/articleshow/50012721.cms&access_token=abc
But i could not find any code to make batch request in the same also i am using pageaccesstoken so what could be the rate limit for same.
Could you please help me to find teh batch request using java for this new version.
You will always be subject to rate limiting... If you're using the /?ids= endpoint, there's already a "batch" functionality built-in.
See
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5#multirequests
https://developers.facebook.com/docs/graph-api/advanced/rate-limiting
How to get the Date/time for an Event I retrieve ?
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("username#gmail.com", "pwd");
URL feedUrl = new URL("https://www.google.com/calendar/feeds/username#gmail.com/public/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setFullTextQuery("Query");
CalendarEventFeed myResultsFeed = myService.query(myQuery,
CalendarEventFeed.class);
for (int i=0; i < myResultsFeed.getEntries().size(); i++)
{
CalendarEventEntry firstMatchEntry = (CalendarEventEntry) myResultsFeed.getEntries().get(i);
String myEntryTitle = firstMatchEntry.getTitle().getPlainText();
System.out.println(myEntryTitle + " " + firstMatchEntry.getPlainTextContent());
System.out.println(""+firstMatchEntry.getAuthors().get(0).getEmail());
System.out.println(""+firstMatchEntry.getPublished());
System.out.println(""+firstMatchEntry.getHtmlLink().getHref());
System.out.println(""+firstMatchEntry.getStatus().getValue());
}
I couldn't find a way to get any more useful info from a CalendarEventEntry.
LE: problem solved; after seeing this:
http://code.google.com/apis/calendar/data/1.0/developers_guide_php.html#RetrievingEvents
I got to this:
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getStartTime());
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getEndTime());
Good thing the examples are different depending on language.
Problem solved; after seeing this:
http://code.google.com/apis/calendar/data/1.0/developers_guide_php.html#RetrievingEvents
I got to this:
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getStartTime());
System.out.println("start time = "+firstMatchEntry.getTimes().get(0).getEndTime());