File diff against the last commit with JGit - java

I am trying to use JGit to get the differences of a file from the last commit to the most recent uncommitted changes. How can I do this with JGit? (using the command line would be the output of git diff HEAD)
Following several discussions (link1, link2) I come with a piece of code that is able to find the files that are uncommited, but it I cannot get the difference of the files
Repository db = new FileRepository("/path/to/git");
Git git = new Git(db);
AbstractTreeIterator oldTreeParser = this.prepareTreeParser(db, Constants.HEAD);
List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).call();
for (DiffEntry entry : diff) {
System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
DiffFormatter formatter = new DiffFormatter(System.out);
formatter.setRepository(db);
formatter.format(entry);
}
UPDATE
This issue was a long time ago. My existing for does display the uncommitted code. The current code that I am using for prepareTreeParser, in the context of displaying the difference, is:
public void gitDiff() throws Exception {
Repository db = new FileRepository("/path/to/git" + DEFAULT_GIT);
Git git = new Git(db);
ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter formatter = new DiffFormatter( out );
formatter.setRepository(git.getRepository());
AbstractTreeIterator commitTreeIterator = prepareTreeParser(git.getRepository(), Constants.HEAD);
FileTreeIterator workTreeIterator = new FileTreeIterator( git.getRepository() );
List<DiffEntry> diffEntries = formatter.scan( commitTreeIterator, workTreeIterator );
for( DiffEntry entry : diffEntries ) {
System.out.println("DIFF Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
formatter.format(entry);
String diffText = out.toString("UTF-8");
System.out.println(diffText);
out.reset();
}
git.close();
db.close();
// This code is untested. It is slighting different for the code I am using in production,
// but it should be very easy to adapt it for your needs
}
private static AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws Exception {
Ref head = repository.getRef(ref);
RevWalk walk = new RevWalk(repository);
RevCommit commit = walk.parseCommit(head.getObjectId());
RevTree tree = walk.parseTree(commit.getTree().getId());
CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
ObjectReader oldReader = repository.newObjectReader();
try {
oldTreeParser.reset(oldReader, tree.getId());
} finally {
oldReader.release();
}
return oldTreeParser;
}

The following setup works for me:
DiffFormatter formatter = new DiffFormatter( System.out );
formatter.setRepository( git.getRepository() );
AbstractTreeIterator commitTreeIterator = prepareTreeParser( git.getRepository(), Constants.HEAD );
FileTreeIterator workTreeIterator = new FileTreeIterator( git.getRepository() );
List<DiffEntry> diffEntries = formatter.scan( commitTreeIterator, workTreeIterator );
for( DiffEntry entry : diffEntries ) {
System.out.println( "Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId() );
formatter.format( entry );
}
The uncommitted changes are made accessible trough the FileTreeIterator. Using formatter.scan() instead of the DiffCommand has the advantage that the formatter is set up properly to handle the FileTreeIterator. Otherwise you will get MissingObjectExceptions as the formatter tries to locate changes from the work tree in the repository.

Related

how to calculate statistical significance using WEKA Java API?

I'm attempting to calculate the statistical significance of classifiers using WEKA Java API. I was reading the documentation and see that I need to use calculateStatistics from PairedCorrectedTTester I'm not sure how to use it.
Any ideas?
public static void main(String[] args) throws Exception {
ZeroR zr = new ZeroR();
Bagging bg = new Bagging();
Experiment exp = new Experiment();
exp.setPropertyArray(new Classifier[0]);
exp.setUsePropertyIterator(true);
SplitEvaluator se = null;
Classifier sec = null;
se = new ClassifierSplitEvaluator();
sec = ((ClassifierSplitEvaluator) se).getClassifier();
CrossValidationResultProducer cvrp = new CrossValidationResultProducer();
cvrp.setNumFolds(10);
cvrp.setSplitEvaluator(se);
PropertyNode[] propertyPath = new PropertyNode[2];
propertyPath[0] = new PropertyNode(
se,
new PropertyDescriptor("splitEvaluator", CrossValidationResultProducer.class), CrossValidationResultProducer.class
);
propertyPath[1] = new PropertyNode(
sec,
new PropertyDescriptor("classifier",
se.getClass()),
se.getClass()
);
exp.setResultProducer(cvrp);
exp.setPropertyPath(propertyPath);
// set classifiers here
exp.setPropertyArray(new Classifier[]{zr, bg});
DefaultListModel model = new DefaultListModel();
File file = new File("dataset arff file");
model.addElement(file);
exp.setDatasets(model);
InstancesResultListener irl = new InstancesResultListener();
irl.setOutputFile(new File("output.csv"));
exp.setResultListener(irl);
exp.initialize();
exp.runExperiment();
exp.postProcess();
PairedCorrectedTTester tester = new PairedCorrectedTTester();
Instances result = new Instances(new BufferedReader(new FileReader(irl.getOutputFile())));
tester.setInstances(result);
tester.setSortColumn(-1);
tester.setRunColumn(result.attribute("Key_Run").index());
tester.setFoldColumn(result.attribute("Key_Fold").index());
tester.setResultsetKeyColumns(
new Range(
""
+ (result.attribute("Key_Dataset").index() + 1)));
tester.setDatasetKeyColumns(
new Range(
""
+ (result.attribute("Key_Scheme").index() + 1)
+ ","
+ (result.attribute("Key_Scheme_options").index() + 1)
+ ","
+ (result.attribute("Key_Scheme_version_ID").index() + 1)));
tester.setResultMatrix(new ResultMatrixPlainText());
tester.setDisplayedResultsets(null);
tester.setSignificanceLevel(0.05);
tester.setShowStdDevs(true);
tester.multiResultsetFull(0, result.attribute("Percent_correct").index());
System.out.println("\nResult:");
ResultMatrix matrix = tester.getResultMatrix();
System.out.println(matrix.toStringMatrix());
}
Results from code above:
results
What I want is similar to the WEKA GUI (circled in red):
Statistical Significance using WEKA GUI
Resources Used:
https://waikato.github.io/weka-wiki/experimenter/using_the_experiment_api/
http://sce.carleton.ca/~mehrfard/repository/Case_Studies_(No_instrumentation)/Weka/doc/weka/experiment/PairedCorrectedTTester.html
You have to swap the key columns for dataset and resultset if you want to statistically evaluate classifiers on datasets (rather than datasets on classifiers):
tester.setDatasetKeyColumns(
new Range(
""
+ (result.attribute("Key_Dataset").index() + 1)));
tester.setResultsetKeyColumns(
new Range(
""
+ (result.attribute("Key_Scheme").index() + 1)
+ ","
+ (result.attribute("Key_Scheme_options").index() + 1)
+ ","
+ (result.attribute("Key_Scheme_version_ID").index() + 1)));
That will give you something like this when using the UCI dataset anneal:
Result:
Dataset (1) rules.ZeroR '' | (2) meta.Baggin
--------------------------------------------------------------
anneal (100) 76.17(0.55) | 98.73(1.12) v
--------------------------------------------------------------
(v/ /*) | (1/0/0)

How to get the changed File list from GJIT API for each commit separate

I am struggling to get the changed File list for Each commit using Jgit from Github repository. please find my sample code and output for your references. We are expecting for each commit we want to know what are files are modified or added or deleted.
File gitWorkDir = new File("D:/Eka_App/Log_Audit");
Git git = Git.open(gitWorkDir);
Repository repo = git.getRepository();
String path = "Database";
Iterator<RevCommit> revCommits = git.log().addPath(path).call()
.iterator();
while (revCommits.hasNext()) {
RevCommit commit = revCommits.next();
System.out.println("commit descr: " + commit.getShortMessage()
+ ", Commit id : " + commit.getId() + ",Commit time: "
+ commit.getCommitTime() + ", Auther: "
+ commit.getAuthorIdent());
RevTree tree = commit.getTree();
TreeWalk treeWalk = new TreeWalk(repo);
treeWalk.addTree(tree); // option 1
treeWalk.setRecursive(false);
treeWalk.setPostOrderTraversal(false);
while (treeWalk.next()) {
if (treeWalk.getPathString().contains("Database")) {
if (treeWalk.isSubtree()) {
// System.out.println("dir: " +
// treeWalk.getPathString());
treeWalk.enterSubtree();
} else {
System.out.println("file: " + treeWalk.getPathString());
}
}
}
}

Drools FromNodeLeftTuple cannot be cast to ReactiveFromNodeLeftTuple

I was wondering if someone could give me advice. I am getting an exception below when trying to modify a property of a reactive model object from Java code.
java.lang.ClassCastException: org.drools.core.reteoo.FromNodeLeftTuple cannot be cast to org.drools.core.reteoo.ReactiveFromNodeLeftTuple
at org.drools.core.phreak.ReactiveObjectUtil.notifyModification(ReactiveObjectUtil.java:47)
at org.drools.core.phreak.ReactiveObjectUtil.notifyModification(ReactiveObjectUtil.java:42)
at org.drools.core.phreak.AbstractReactiveObject.notifyModification(AbstractReactiveObject.java:41)
at org.drools.compiler.oopath.model.Person.setAge(Person.java:50)
at org.drools.compiler.oopath.OOPathReactiveTests.testSetter2Rules(OOPathReactiveTests.java:127)
I created the following tests to reproduce the problem, the code can be inserted into org.drools.compiler.oopath.OOPathReactiveTests in drools-compiler module in 7.1.0-SNAPSHOT.
It does not happen when there is only 1 rule (see testSetter1Rule()), it happens with more rules (testSetter2Rules()).
public class OOPathReactiveTests {
#Test
public void testSetter1Rule() {
String header =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n\n";
String drl1 =
"rule R1 when\n" +
" Man( $m: /wife[age == 25] )\n" +
"then\n" +
" list.add($m.getName());\n" +
"end\n\n";
final KieSession ksession = new KieHelper()
.addContent( header + drl1, ResourceType.DRL )
.build()
.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Man bob = new Man("John", 25);
bob.setWife( new Woman("Jane", 25) );
ksession.insert( bob );
ksession.fireAllRules();
bob.getWife().setAge(26);
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder("Jane");
}
#Test
public void testSetter2Rules() {
String header =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n\n";
String drl1 =
"rule R1 when\n" +
" Man( $m: /wife[age == 25] )\n" +
"then\n" +
" list.add($m.getName());\n" +
"end\n\n";
String drl2 =
"rule R2 when\n" +
" Man( $m: /wife[age == 26] )\n" +
"then\n" +
" list.add($m.getName());\n" +
"end\n\n";
final KieSession ksession = new KieHelper()
.addContent( header + drl1 + drl2, ResourceType.DRL )
.build()
.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
final Man bob = new Man("John", 25);
bob.setWife( new Woman("Jane", 25) );
ksession.insert( bob );
ksession.fireAllRules();
bob.getWife().setAge(26);
ksession.fireAllRules();
Assertions.assertThat(list).containsExactlyInAnyOrder("Jane", "Jane");
}
Jane's leftTuples in the moment of the exception are:
leftTuples = {HashSet#3461} size = 2
0 = {FromNodeLeftTuple#3463} "[fact 0:1:1288815068:1288815068:1:DEFAULT:NON_TRAIT:org.drools.compiler.oopath.model.Man:John]"
1 = {ReactiveFromNodeLeftTuple#3469} "[fact 0:1:1288815068:1288815068:1:DEFAULT:NON_TRAIT:org.drools.compiler.oopath.model.Man:John]"
I wonder if this is a bug or I am using it wrong way.
Thank you very much.
Peter
After posting the problem to https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!forum/drools-usage
it has been fixed very quickly by drools developers in https://issues.jboss.org/browse/DROOLS-1589

Java EWS findappointments dates acting weird, either returns to much or nothing

I'm not sure how the start and end date work with the whole find appointments. I am getting all the rooms for a public group, then getting the rooms for the group, then getting the appointments within a date range.
But the ranges act weird, I know there are appointments on 12-19 to 12-16, but if I set the start date range to 2013-10-10 and the end date to 2013-12-28, I get nothing.
If I set the end date to 2014-01-28, I get tons of stuff that is in the range previously mentioned. Why is that?
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials( "username", "pw");
service.setCredentials( credentials );
service.setUrl( new URI("my mail url") );
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
System.out.println("messages: " + inbox.getTotalCount());
CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
//Get all new appts?
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("YYYY-mm-dd");
Date startDate1 = formatter.parse("2013-11-25");
Date endDate1 = formatter.parse("2014-01-28 ");
EmailAddressCollection myRoomLists = service.getRoomLists();
for (EmailAddress item : myRoomLists)
{
System.out.println("Room Email========"+ item.toString());
NameResolutionCollection nameResolutions = service.resolveName(
item.getName(),
ResolveNameSearchLocation.DirectoryOnly,
true);
for (NameResolution nameResolution : nameResolutions)
{
ExpandGroupResults groupResults;
//System.out.println(nameResolution.getMailbox().getAddress());
try {
groupResults = service.expandGroup(nameResolution.getMailbox().getAddress());
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
groupResults=null;
System.out.println("NO INFO FOR "+nameResolution.getMailbox().getAddress());
}
if (groupResults!=null){
for (EmailAddress member : groupResults.getMembers())
{
if (member.getAddress().indexOf("rm.Cary")>-1){
System.out.println(member.getName() + " <" + member.getAddress() + ">");
FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(member.getAddress()));
try {
FindItemsResults<Appointment> aps = service.findAppointments(folderid, new CalendarView(startDate1,endDate1));
for (Item items : aps.getItems())
{
Appointment appt = (Appointment)items;
System.out.println("SUBJECT===== " + appt.getSubject());
System.out.println("Location======== " + appt.getLocation());
System.out.println("Start Time========" + appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Start time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Is recurring========"+appt.getIsRecurring());
System.out.println("Duration========"+appt.getDuration().toString());
System.out.println("Organizer========"+appt.getOrganizer());
System.out.println("Required Attendees========"+appt.getRequiredAttendees().getCount());
System.out.println("Optional Attendees========"+appt.getOptionalAttendees().getCount());
System.out.println("");
}
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
System.out.println(e.getMessage());
}
}
}
}
}
}
System.out.println("End");
Change it to:
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("yyyy-MM-dd");

How Get Spooled File list separately from it's format - Java ( JT400 )

I get Spooled list to java using jt400. but i want to get Advanced Spooled file( *.TIFF image formatted Spooled files) list and normal Spooled (Can read Text) file list separately. Anyone know how to do that ?
Thanks in Advance!
try{
AS400 server = new AS400();
System.out.println(" Now receiving all spooled files Synchronously");
SpooledFileList splfList = new SpooledFileList( server );
// set filters, all users, on all queues
splfList.setUserFilter("user");
splfList.setQueueFilter("/QSYS.LIB/%ALL%.LIB/%ALL%.OUTQ");
// open list, openSynchronously() returns when the list is completed.
splfList.openSynchronously();
// Enumeration enum = splfList.getObjects();
Enumeration enumx = splfList.getObjects();
while(enumx.hasMoreElements())
{
SpooledFile splf = (SpooledFile)enumx.nextElement();
if ( splf != null )
{
String Name = splf.getName();
int Number = splf.getNumber();
String jobname = splf.getJobName();
String jobuser = splf.getJobUser();
String jobnumber = splf.getJobNumber();
// strSpooledNumber = splf.getStringAttribute(SpooledFile.)
System.out.println(" spooled file = Name :" + Name + " number : " + Number + " JobName : " + jobname + " job user : " + jobuser + " job Number : " + jobnumber);
}
}
// clean up after we are done with the list
splfList.close();
}
catch( Exception e )
{
e.printStackTrace();
}
The existing class doesn't have a filter on printer device type, although you could add one using getUserFilter as an example.
Once you have the full list of spooled files, you could split them yourself into two groups. Try String prtdevtype = splf.getStringAttribute(ATTR_PRTDEVTYPE);
From this you can tell if you have a text spooled file (*SCS) or one with graphics in it (*IPDS, *AFPDS).

Categories

Resources