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;
}
}
Related
I made two RestController apis. On response of second api I wanted first api's response (which is a json response), so I tried to use HttpServletResponse.redirect. I also set required content type to it. But on second api response I got Unsupported Media Type Content type 'null' not supported.
first API
#GetMapping(value="checkStatus/{msisdn}",consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CoreResponseHandler> fetchOcsByDate2(#PathVariable(value="msisdn",required=true)String msisdn){
long l_time_start = System.currentTimeMillis();
List<Object[]> list = repository.getSingleCallDetail(msisdn);
if(list==null || list.size()==0) {
System.out.println("NO RECORD FOUND");
}
JSONObject objMain = new JSONObject();
for(Object[] objArr: list) {
JSONObject obj = new JSONObject();
String msisdn_ = objArr[0]==null?null:objArr[0].toString();
String songId = objArr[1]==null?null:objArr[1].toString();
String songName = objArr[2]==null?null:objArr[2].toString();
String status = objArr[3]==null?null:objArr[3].toString();
String lang = objArr[4]==null?null:objArr[4].toString();
String startDate = objArr[5]==null?null:objArr[5].toString();
objMain.put("status", status);
objMain.put("language", lang);
obj.put("id", songId);
obj.put("msisdn", msisdn);
obj.put("songName", songName);
objMain.put("subscription", obj);
}
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
if(list!=null && list.size()>0) {
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.OK, ResponseStatusEnum.SUCCESSFUL, ApplicationResponse.SUCCESSFUL, objMain,l_diff+" ms"),HttpStatus.OK);
}
if(list==null || list.size()==0) {
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.NOT_FOUND, ResponseStatusEnum.FAILED, ApplicationResponse.Failed, "not found",l_diff+" ms"),HttpStatus.NOT_FOUND);
}
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed," > Bad request",l_diff+" ms"),HttpStatus.BAD_REQUEST);
}
no problem in output. ran smooth
second API
#GetMapping(value="verifyOtp/{msisdn}/{otp}",consumes=MediaType.APPLICATION_JSON_VALUE)
public void verifyOtp(#PathVariable(value="msisdn",required=true)String msisdn,
#PathVariable(value="otp",required=true)String otp,HttpServletResponse response) throws Exception{
long l_time_start = System.currentTimeMillis();
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
List<Object[]> list = repository.verifyOtp(msisdn,otp);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if(list!=null && list.size()>0) {
for(Object[] obj:list) {
String strDate = obj[3]==null?null:obj[3].toString();
Date dtDb = sdf.parse(strDate);
Date dtNow = new Date();
String strDtNow = sdf.format(dtNow);
dtNow = sdf.parse(strDtNow);
long ldtDb = dtDb.getTime();
long ldtNow = dtNow.getTime();
if(ldtDb>ldtNow) {
System.out.println("success within time");
int ii = repository.updateIsActive(msisdn);
response.setContentType("application/json");
response.sendRedirect("http://localhost:9393/crbt/api/subscriber/ivr/checkStatus/"+msisdn);
}
else {
System.out.println("failure time over!");
}
}
}
else {
}
}
second Api Response in postman
What I expected was first API's response. But its giving me some 415 content type error
How can I get first API's success json response from second api's response.. I even tried org.springframework.http.HttpHeaders but couldn't get desired output. What changes I had to do in order to get first Api's response in my second api response.
I have a strange feeling answering your questions, because I dislike the solution I'll provided. But it might help, so I'll give a try.
Basically, your Controller are just Spring beans, which means you can do is having a dependency, and second controller will call first controller. This will also change your method verifyOtp to make it change the return type.
Something like that:
...
#Autowired
private FirstController firstController;
...
#GetMapping(value="verifyOtp/{msisdn}/{otp}",consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CoreResponseHandler> verifyOtp(#PathVariable(value="msisdn",required=true)String msisdn,
#PathVariable(value="otp",required=true)String otp,HttpServletResponse response) throws Exception{
long l_time_start = System.currentTimeMillis();
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
List<Object[]> list = repository.verifyOtp(msisdn,otp);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if(list!=null && list.size()>0) {
for(Object[] obj:list) {
String strDate = obj[3]==null?null:obj[3].toString();
Date dtDb = sdf.parse(strDate);
Date dtNow = new Date();
String strDtNow = sdf.format(dtNow);
dtNow = sdf.parse(strDtNow);
long ldtDb = dtDb.getTime();
long ldtNow = dtNow.getTime();
if(ldtDb>ldtNow) {
System.out.println("success within time");
int ii = repository.updateIsActive(msisdn);
return firstController.fetchOcsByDate2(msidn);
}
else {
System.out.println("failure time over!");
return null;
}
}
}
else {
return null;
}
}
I think you are trying to achieve something uncommon, and to avoid having this dependency between controller, consider:
Change your use case. Make the second controller returning a HttpStatus.OK, and make the client do the next call to the first controller
Create a service in charge of loading the msidn, which will avoid duplicate code, and keep you in a more standard position to make our evolutions.
The issue occurred due to GetMapping .
#GetMapping(value="checkStatus/{msisdn}",consumes=MediaType.APPLICATION_JSON_VALUE)
replace with below in first Api:
#GetMapping(value="checkStatus/{msisdn}")
I am facing an issue when i try to query the queue using createquery api to fetch the queue element.
I am getting an error at the while statement stating the error below as
errorjava.lang.illegalstateexception :unread block data
i dont know why i am getting this error. I can able to use the fetchcount() api to get the count of workitem in the queue but the hasnext() api is not working nor next().
Is there any reason why this statement is not getting executed. is this related to any java issue. Can any one help
The code is
VWSession session = new VWSession();
session.setBootstrapCEURI(Ceuri);
session.logon(cename, fnPassword, connectionPoint);
VWQueue queue = session.getQueue(queue));
int queryFlag = VWQueue.QUERY_NO_OPTIONS;
int fetchType = VWFetchType.FETCH_TYPE_STEP_ELEMENT;
VWQueueQuery queueQuery = queue.createQuery(null,null, null,queryFlag, null, null, fetchType);
while (queueQuery.hasNext()) {
queueElement = (VWStepElement) queueQuery.next();
}
In you main (calling) method, do this :
VWSession vwsession = new VWSession();
vwsession.setBootstrapCEURI("http://servername:9080/wsi/FNCEWS40MTOM/");
vwsession.logon("userid", "password", "ConnPTName");
IteratePEWorkItems queueTest = new IteratePEWorkItems();
queueTest.testQueueElements(vwsession);
Later on create below metioned helper method:
public void testQueueElements(VWSession vwsession) {
System.out.println("Inside getListOfWorkitems: : ");
VWRoster roster = vwsession.getRoster("DefaultRoster");
int fetchType = VWFetchType.FETCH_TYPE_STEP_ELEMENT;
int queryFlags = VWQueue.QUERY_READ_UNWRITABLE;
try {
dispatchWorkItems(roster, fetchType, queryFlags, vwsession);
} catch (Exception exception) {
log.error(exception.getMessage());
}
}
public void dispatchWorkItems(VWRoster roster, int fetchType, int queryFlags, VWSession vwsession) {
String filter = "SLA_Date>=:A";
// get value and replace with 1234567890 as shown in process administrator
Object[] subVars = { 1234567890 };
VWRosterQuery rosterQuery = roster.createQuery(null, null, null,
VWRoster.QUERY_MIN_VALUES_INCLUSIVE | VWRoster.QUERY_MAX_VALUES_INCLUSIVE, filter, subVars,
VWFetchType.FETCH_TYPE_WORKOBJECT);
int i = 0;
// Iterate work items here...
while (rosterQuery.hasNext() == true) {
VWWorkObject workObject = (VWWorkObject) rosterQuery.next();
try {
i++;
System.out.println(" Subject: " + workObject.getFieldValue("F_Subject") + " Count: " + i);
} catch (Exception exception) {
exception.printStackTrace();
log.error(exception);
}
}
}
Try it and share the 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'm trying insert nodes in neo4j using embedded neo4j in java, but I obtain this error, i'm using neo4j 3.1.1 and netbeans 7
Exception in thread "main" java.lang.NoSuchMethodError: org.neo4j.helpers.collection.Iterables.toList(Ljava/lang/Iterable;)Ljava/util/List;
at org.neo4j.graphdb.factory.GraphDatabaseFactory.<init>(GraphDatabaseFactory.java:49)
at twitter4j.EmbeddeNeo4j.createDb(EmbeddeNeo4j.java:41)
I don't know if the problem in variable DB_PATH = "D:\\Neo4j CE 3.1.1\\graph database"
what should the variable DB_PATH be contained?
the code is :
void createDb() {
clearDb();
// start DB
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
registerShutdownHook(graphDb);
// start Transaction
Transaction tx = graphDb.beginTx();
try {
// adding data
firstNode = graphDb.createNode();
firstNode.setProperty("message", "Hello, ");
secondNode = graphDb.createNode();
secondNode.setProperty("message", "World!");
relationship = firstNode.createRelationshipTo(secondNode, RelTypes.KNOWS);
relationship.setProperty("message", "brave Neo4j ");
// reading data
System.out.println(firstNode.getProperty("message"));
System.out.println(relationship.getProperty("message"));
System.out.println(secondNode.getProperty("message"));
greeting = (String) firstNode.getProperty("message") + (String) relationship.getProperty("message") + (String) secondNode.getProperty("message");
Iterator<Relationship> it = firstNode.getRelationships().iterator();
while(it.hasNext()) {
Relationship r = it.next();
Node[] nodes = r.getNodes();
System.out.println(nodes[0].getProperty("message") + " " + r.getProperty("message") + " " + nodes[1].getProperty("message"));
}
tx.success();
} finally {
tx.terminate();
}
}
private void clearDb() {
try {
FileUtils.deleteRecursively(new File(DB_PATH));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I had essentially this same problem; it was caused by the presence of older versions of Neo4J in the CLASSPATH along with the new one I was trying to use. (I learned along the way that my IDE doesn't clean out old targets before building new ones, which is why the older versions were there.)
Make sure that you've flushed out all older versions of the relevant .jars.
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());
}