Error when trying to read modified files in a PreRecive hhok

Hi,
I need to write a Pre Recieve Hook for bitbucket, if the files are located under a certain folder i nead to read the file’s content.
When I try to read the file i get a NoSuchPathException
This is the code :

 @Override
    public boolean onReceive(RepositoryHookContext context, Collection<RefChange> refChanges, HookResponse hookResponse)
    {
        final Repository repo = context.getRepository();
        for (final RefChange refChange : refChanges) {
            if (refChange.getType() != RefChangeType.DELETE) {
                System.out.println(String.format("Starting to work on refChange of the ref: %s, the from hash is: %s, the toHash is:%s",
                        refChange.getRef().getDisplayId(), refChange.getFromHash(), refChange.getToHash()));
                final CommitsBetweenRequest request = new CommitsBetweenRequest.Builder(repo)
                        .exclude(refChange.getFromHash())
                        .include(refChange.getToHash())
                        .build();

                commitService.streamCommitsBetween(request, new CommitCallback() {
                    public boolean onCommit(final Commit commit) throws IOException {
                        System.out.println(String.format("The commit %s contains the following files: ", commit.getId()));
                        final ChangesRequest changesreq = new ChangesRequest.Builder(repo, commit.getId()).build();
                        commitService.streamChanges(changesreq, new ChangeCallback() {
                            public boolean onChange(Change change) throws IOException {
                                System.out.println("        " + change.getPath().toString());
                                if (isRelevantChange(change)) {
                                    String filePath = change.getPath().toString();
                                    System.out.println(String.format("%s is a relevant file! printing it!", filePath));
                                    //final ByteArrayOutputStream os = new ByteArrayOutputStream();
                                    contentService.streamFile(repo, commit.getId(), filePath, new PageRequestImpl(0,99999), false, new AbstractFileContentCallback(){
                                        public boolean onLine(int lineNumber, String line, boolean truncated) throws IOException {
                                            System.out.println(line);
                                            return true;
                                        }
                                    });
                                }
                                return true;
                            }
                        });
                        return true;
                    }
                });
            }
        }
        return false;
    }

I also tried to stream the changes like this:

 final ChangesRequest changesreq = new ChangesRequest.Builder(repo, refChange.getToHash()).sinceId(refChange.getFromHash()).build();

                commitService.streamChanges(changesreq, new ChangeCallback() {
                    public boolean onChange(Change change) throws IOException {
                        System.out.println(change.getPath());
                        if (change.getType() != ChangeType.DELETE && change.getType() != ChangeType.COPY) {
                            System.out.println("Starting to work on change");
                            System.out.println("The source path is: " + change.getSrcPath());
                            System.out.println("The destination path is: " + change.getPath());
                            if (isRelevantChange(change)) {
                                String filePath = change.getPath().toString();
                                System.out.println(String.format("The change to the file %s is relevant for the hook", change.getPath()));
                                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                                contentService.streamFile(repo, changesreq.getUntilId(), filePath, new TypeAwareOutputSupplier() {
                                    public OutputStream getStream(String arg0) throws IOException {
                                        return os;
                                    }
                                });
                                System.out.println(String.format("@@@@@@@@@@Printing the content of %s @@@@@@@@@@",filePath));
                                System.out.println(new String(os.toByteArray(), "UTF-8"));
                            }
                        }
                        return true;
                    }
                });

In both cases I get the same PathNotFoundException

[INFO] 2018-04-11 17:15:25,817 WARN  [threadpool:thread-2] admin @8BA8AFx1035x4x0 fe80:0:0:0:3d62:f6e7:d795:f8cc%9 "POST /scm/project_1/rep_1.git/git-receive-pack HTTP/1.1" c.a.s.i.h.r.DefaultRepositoryHookService [PROJECT_1/rep_1[1]] Error calling com.atlassian.stash.internal.plugin.legacy.CompositeRepositoryHook.preUpdate (walkme.dbchanges-plugin:db-changes-pre-hook)
[INFO] com.atlassian.bitbucket.content.NoSuchPathException: The path "DbChanges/Audit/147/v147.2__create_white_list_users_table.sql" does not exist at revision "9a5f4f03174e4376f6f577d9e81d6466c8b7fb73"
[INFO]  at com.atlassian.bitbucket.scm.git.command.GitCommandExitHandler.newNoSuchPathException(GitCommandExitHandler.java:190)
[INFO]  at com.atlassian.bitbucket.scm.git.command.GitCommandExitHandler.evaluateStdErr(GitCommandExitHandler.java:91)
[INFO]  at com.atlassian.bitbucket.scm.git.command.GitCommandExitHandler.onError(GitCommandExitHandler.java:197)
[INFO]  at com.atlassian.bitbucket.scm.DefaultCommandExitHandler.onExit(DefaultCommandExitHandler.java:31)
[INFO]  at com.atlassian.bitbucket.scm.BaseCommand.callExitHandler(BaseCommand.java:146)
[INFO]  at com.atlassian.bitbucket.scm.BaseCommand$CommandFuture.internalGet(BaseCommand.java:280)
[INFO]  at com.atlassian.bitbucket.scm.BaseCommand$CommandFuture.get(BaseCommand.java:244)
[INFO]  at com.atlassian.bitbucket.scm.BaseCommand.call(BaseCommand.java:83)
[INFO]  at com.atlassian.stash.internal.content.DefaultContentService.streamFile(DefaultContentService.java:214)
[INFO]  at com.atlassian.plugin.util.ContextClassLoaderSettingInvocationHandler.invoke(ContextClassLoaderSettingInvocationHandler.java:26)
[INFO]  at org.eclipse.gemini.blueprint.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:56)
[INFO]  at org.eclipse.gemini.blueprint.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:60)
[INFO]  at org.eclipse.gemini.blueprint.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:70)
[INFO]  at org.eclipse.gemini.blueprint.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:53)
[INFO]  at org.eclipse.gemini.blueprint.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:57)
[INFO]  at walkme.hook.DbChangesPreHook$1$1.onChange(DbChangesPreHook.java:66)
[INFO]  at com.atlassian.stash.internal.scm.git.command.diff.CallbackDiffTreeOutputHandler.processReader(CallbackDiffTreeOutputHandler.java:183)
[INFO]  at com.atlassian.bitbucket.io.LineReaderOutputHandler.process(LineReaderOutputHandler.java:42)
[INFO]  at com.atlassian.bitbucket.scm.SummarizingProcessHandler$DelegatingInputStreamHandler.process(SummarizingProcessHandler.java:184)
[INFO]  at com.atlassian.bitbucket.scm.SummarizingProcessHandler$DelegatingInputStreamHandler.process(SummarizingProcessHandler.java:166)
[INFO]  at com.atlassian.bitbucket.scm.SummarizingProcessHandler.processOutput(SummarizingProcessHandler.java:90)
[INFO]  at com.atlassian.utils.process.ExternalProcessImpl$StdoutHandler.handle(ExternalProcessImpl.java:794)
[INFO]  at com.atlassian.utils.process.ExternalProcessImpl$HandlerLatchedRunnable.doTask(ExternalProcessImpl.java:731)
[INFO]  at com.atlassian.utils.process.LatchedRunnable.run(LatchedRunnable.java:158)
[INFO]  at com.atlassian.utils.process.ExternalProcessImpl$AsynchronousHandlerLatchedRunnable.run(ExternalProcessImpl.java:700)
[INFO]  at com.atlassian.stash.internal.concurrent.DefaultTransferableStateManager$StateTransferringRunnable.run(DefaultTransferableStateManager.java:166)
[INFO]  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[INFO]  at java.lang.Thread.run(Thread.java:745)
[INFO]  ... 60 frames trimmed

I dont know what to do any more, how is that possible that the file is not found in the commit if i get the path of the file from it?

Thank you for help

Hi, this is a late solution but I think I know what the issue in case this is still relevant,

because you always reject your push with return false at the end of onReceive, at the next push you will do the rejected commits (from the rejected push) will be sent with the new commits in the next git push command.

because of that i’ll assume that in one of the commits you made a change to a file and tried to push it (then rejected).
second you deleted that file

at this every push you will do will still contain the initial commit that contain change you tried to push and rejected.
there for you are trying to read a file that is no longer exists in your repository.

hopefully it makes sense.

what you need to do is just return true from the onReceive method when the rest of the code is commented out and then try again…

Good Luck!