JGit - Get all commits (PlotCommitList) that affected a file/path - filter

Hy i am trying to get all the commits that include a specific directory or file of my repository.
I tried the folowing code :
public PlotCommitList getPlotCommits(String path){
System.out.println(path);
PlotCommitList<PlotLane> plotCommitList = new PlotCommitList<PlotLane>();
PlotWalk revWalk = new PlotWalk(repository);
try {
ObjectId rootId = repository.resolve("HEAD");
if (rootId != null) {
RevCommit root = revWalk.parseCommit(rootId);
revWalk.markStart(root);
revWalk.setTreeFilter(PathFilter.create(path));
plotCommitList.source(revWalk);
plotCommitList.fillTo(Integer.MAX_VALUE);
return plotCommitList;
}
} catch (AmbiguousObjectException ex) {
Logger.getLogger(GitRepository.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GitRepository.class.getName()).log(Level.SEVERE, null, ex);
}
return plotCommitList;
}
I don't get just the commits that affected that file. I get some "subLists" of the entire list but not just those commits that affected that file.
Maybe TreeFilter doesn't work how i think? I should use other way to get those commits?
I saw the log command has a path filter but i didn't tried it yet because it returns a RevCommit list and for my PlotCommitList i need a revwalk to use as a source. And also i think i cannot cast RevCommit to PlotCommit.
A guy had the same problem here (1st Answer with fileA and fileB issue) : Link - Click Here

You need to combine the PathFilter with an ANY_DIFF filter:
revWalk.setTreeFilter(
AndTreeFilter.create(PathFilter.create(path), TreeFilter.ANY_DIFF));
With only PathFilter I think what happens is that all commits are selected where the specified tree exists (e.g. all commits starting from the initial commit of that file).
Also see the API docs of setTreeFilter or how the LogCommand does it.

Related

Unable to save screenshots in the designated path or attach the screen shot to extentreports in MAC

I have tried many ways to take screenshot on test case failure but nothing works. unable to take a screenshot and attach it to extentreport in MAC os while using selenium.
public void onTestFailure(ITestResult tr)
{
logger=extent.createTest(tr.getName()); // create new entry in the report
logger.log(Status.FAIL,MarkupHelper.createLabel(tr.getName(),ExtentColor.RED)); // send the passed information to the report with GREEN color highlighted
String screenshotPath="./Stest-output/"+tr.getName()+".png";
TakesScreenshot ts = (TakesScreenshot)driver;
File img =ts.getScreenshotAs(OutputType.FILE);
File destination =new File(screenshotPath);
try {
FileUtils.copyFile(img,destination);
logger.addScreenCaptureFromPath(screenshotPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(img != null)
{
System.out.println("Screenshot is below:"+tr.getName());
try {
logger.info("Screenshot is below:" + logger.addScreenCaptureFromPath(screenshotPath));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
throws null pointer exception when trying to copy the image from source to destination.
Have all the methods available in stack overflow.
You are unable to attach screenshot into extent report html because you forget to call flush() method that appends the report HTML file with all the tests result/screenshots. There must be at least one ended test for anything to be appended to the report.
Note: If flush() is called before any of the ended tests, no information will be appended to report.
#AfterTest
public void tearDown() {
extent.flush();

Implementing Jump Hosts with SSHJ

Somebody asked for this and there is a pull-request which contains code that somehow was rewritten before it got merged and somebody managed to code a solution based on the pull-request. However, there is no example for the final version in that library.
Therefore, that doesn't really help me with my limited understanding of ssh and all. Basically there are two scenarios I want to solve:
common SSH-session via some jump-hosts:
user1#jump1.com
user2#jump2.com
user3#jump3.com
admin#server.com
ending in an ssh-session where the connecting user is free to work around in that ssh-shell at server.com, i.e. what a normal ssh admin#server.com-command would do in the shell on jump3.com.
like the above but ending in a port forwarding to server.com:80
That is possible with ssh's ProxyCommand, but I want to code this with SSHJ. And that's where I fail to figure out how to do this.
What I have now is
SSHClient hop1 = new SSHClient();
try {
Path knownHosts = rootConfig.getKnownHosts();
if (knownHosts != null) {
hop1.loadKnownHosts(knownHosts.toFile());
} else {
hop1.loadKnownHosts();
}
Path authenticationFile = hop1Config.getAuthenticationFile();
if (authenticationFile != null) {
KeyProvider keyProvider = hop1.loadKeys(authenticationFile.toString(), (String) null);
hop1.authPublickey(hop1Config.getUser(), keyProvider);
} else {
hop1.authPassword(hop1Config.getUser(), hop1Config.getPassword());
}
// I found these methods:
hop1.getConnection();
hop1.getSocket();
// and now what?
} catch (IOException e) {
logger.error("Failed to open ssh-connection to {}", hop1Config, e);
}
I noticed class LocalPortForwarder.DirectTCPIPChannel, but I don't know with what values I should instantiate it or how to use it with the rest afterwards.

How to create a permanent directory for my files with spring boot

I am working with spring boot and spring content. I want to store all my pictures and videos in one directory but my code continues to create different dir every time I rerun the application
I have such bean and when I run the app again it shows null pointer because the dir already exists but I want it to create it just once and every file is stored there
every time i run this tries to create the dir again
#Bean
File filesystemRoot() {
try {
return Files.createDirectory(Paths.get("/tmp/photo_video_myram")).toFile();
} catch (IOException io) {}
return null;
}
#Bean
FileSystemResourceLoader fileSystemResourceLoader() {
return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
}
One solution, would be to check if the directory exists:
#Bean
File filesystemRoot() {
File tmpDir = new File("tmp/photo_video_myram");
if (!tmpDir.isDirectory()) {
try {
return Files.createDirectory(tmpDir.toPath()).toFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return tmpDir;
}
You can use isDirectory() method first to check if the directory already exists. In case it does not exist, then create a new one.
Meanwhile there is another way to achieve this, when you use Spring Boot and accordingly spring-content-fs-boot-starter.
According to the documentation at https://paulcwarren.github.io/spring-content/refs/release/fs-index.html#_spring_boot_configuration it should be sufficient to add
spring.content.fs.filesystemRoot=/tmp/photo_video_myram
to your application.properties file.

How to use integrationFlows for new files?

I was following a tutorial on how to listen to a folder with spring integration and SseEmitter. I have this code now:
#Bean
IntegrationFlow inboundFlow ( #Value("${input-dir:file:C:\\Users\\kader\\Desktop\\Scaned\\}") File in){
return IntegrationFlows.from(Files.inboundAdapter(in).autoCreateDirectory(true),
poller -> poller.poller(spec -> spec.fixedRate(1000L)))
.transform(File.class, File::getAbsolutePath)
.handle(String.class, (path, map) -> {
sses.forEach((sse) -> {
try {
String p = path;
sse.send(SseEmitter.event().name("spring").data(p));
}
catch (IOException e) {
throw new RuntimeException(e);
}
});
return null ;
})
.get();
}
and it works but it sends all the files in the specified directory including the files that already exist, is there any way to make it ignore them and send the new files only???
Well, actually since you don't configure any filters on the Files.inboundAdapter(), there is a logic like this:
// no filters are provided
else if (Boolean.FALSE.equals(this.preventDuplicates)) {
filtersNeeded.add(new AcceptAllFileListFilter<File>());
}
else { // preventDuplicates is either TRUE or NULL
filtersNeeded.add(new AcceptOnceFileListFilter<File>());
}
Therefore an AcceptOnceFileListFilter is applied and no any already polled files are not going to be picked up on the subsequent poll tasks.
However you really may talk about something like "after application restart", so yes, in this case all the files are going to be pulled.
I believe you need to study what is the FileListFilter and use an appropriate for your use-case: https://docs.spring.io/spring-integration/docs/current/reference/html/files.html#file-reading

Spring Integration and returning schema validation errors

We are using Spring Integration to process a JSON payload passed into a RESTful endpoint. As part of this flow we are using a filter to validate the JSON:
.filter(schemaValidationFilter, s -> s
.discardFlow(f -> f
.handle(message -> {
throw new SchemaValidationException(message);
}))
)
This works great. However, if the validation fails we want to capture the parsing error and return that to the user so they can act on the error. Here is the overridden accept method in the SchemaValidationFilter class:
#Override
public boolean accept(Message<?> message) {
Assert.notNull(message);
Assert.isTrue(message.getHeaders().containsKey(TYPE_NAME));
String historyType = (String)message.getHeaders().get(TYPE_NAME);
JSONObject payload = (JSONObject) message.getPayload();
String jsonString = payload.toJSONString();
try {
ProcessingReport report = schemaValidator.validate(historyType, payload);
return report.isSuccess();
} catch (IOException | ProcessingException e) {
throw new MessagingException(message, e);
}
}
What we have done is in the catch block we throw a MessageException which seems to solve the problem. However this seems to break what a filter should do (simply return a true or false).
Is there a best practice for passing the error details from the filter to the client? Is the filter the right solution for this use case?
Thanks for your help!
John
I'd say you go correct way. Please, refer to the XmlValidatingMessageSelector, so your JsonValidatingMessageSelector should be similar and must follow the same design.
Since we have a throwExceptionOnRejection option we always can be sure that throwing Exception instead of just true/false is correct behavior.
What Gary says is good, too, but according to the existing logic in that MessageSelector impl we can go ahead with the same and continue to use .filter(), but, of course, already without .discardFlow(), because we won't send invalid message to the discardChannel.
When your JsonValidatingMessageSelector is ready, feel free to contribute it back to the Framework!
It's probably more correct to do the validation in a <service-activator/>...
public Message<?> validate(Message<?> message) {
...
try {
ProcessingReport report = schemaValidator.validate(historyType, payload);
return message;
}
catch (IOException | ProcessingException e) {
throw new MessagingException(message, e);
}
}
...since you're never really filtering.

Resources