nus-yam/ex-repair huggingface dataset:
Program: 91438
Project: 91438
Buggy source:
protected IResourceMappingMerger createMerger() throws CoreException {
  final ModelProvider provider=ModelProvider.getModelProviderDescriptor(SampleModelProvider.SAMPLE_PROVIDER_ID).getModelProvider();
  return (ResourceMappingMerger)Platform.getAdapterManager().getAdapter(provider,IResourceMappingMerger.class);
}

Fixed version (ground truth):
protected IResourceMappingMerger createMerger() throws CoreException {
  final ModelProvider provider=ModelProvider.getModelProviderDescriptor(SampleModelProvider.SAMPLE_PROVIDER_ID).getModelProvider();
  return Utils.getAdapter(provider,IResourceMappingMerger.class);
}
Program: 91439
Project: 91439
Buggy source:
private ResourceMapping getMappingAdapter(IResource resource){
  return (ResourceMapping)resource.getAdapter(ResourceMapping.class);
}

Fixed version (ground truth):
private ResourceMapping getMappingAdapter(IResource resource){
  return Utils.getAdapter(resource,ResourceMapping.class);
}
Program: 91440
Project: 91440
Buggy source:
private void assertProjectInWorkingSet(String workingSetName,String projectName){
  IWorkingSetManager workingSetManager=PlatformUI.getWorkbench().getWorkingSetManager();
  IWorkingSet workingSet=workingSetManager.getWorkingSet(workingSetName);
  IAdaptable[] elements=workingSet.getElements();
  assertEquals("String_Node_Str",1,elements.length);
  IProject project=(IProject)elements[0].getAdapter(IProject.class);
  assertEquals("String_Node_Str",projectName,project.getName());
}

Fixed version (ground truth):
private void assertProjectInWorkingSet(String workingSetName,String projectName){
  IWorkingSetManager workingSetManager=PlatformUI.getWorkbench().getWorkingSetManager();
  IWorkingSet workingSet=workingSetManager.getWorkingSet(workingSetName);
  IAdaptable[] elements=workingSet.getElements();
  assertEquals("String_Node_Str",1,elements.length);
  IProject project=Utils.getAdapter(elements[0],IProject.class);
  assertEquals("String_Node_Str",projectName,project.getName());
}
Program: 91441
Project: 91441
Buggy source:
/** 
 * Adapt object to given target class type
 * @param object
 * @param target
 * @param < V > type of target
 * @return adapted
 */
@SuppressWarnings("String_Node_Str") public static <V>V adapt(Object object,Class<V> target){
  if (object == null)   return null;
  if (target.isInstance(object))   return (V)object;
  if (object instanceof IAdaptable)   return (V)((IAdaptable)object).getAdapter(target);
  return null;
}

Fixed version (ground truth):
/** 
 * Adapt object to given target class type
 * @param object
 * @param target
 * @param < V > type of target
 * @return adapted
 */
@SuppressWarnings("String_Node_Str") public static <V>V adapt(Object object,Class<V> target){
  if (object == null)   return null;
  if (target.isInstance(object))   return (V)object;
  if (object instanceof IAdaptable)   return Utils.getAdapter(((IAdaptable)object),target);
  return null;
}
Program: 91442
Project: 91442
Buggy source:
private RevCommit getRevCommit(IFileRevision revision){
  if (revision instanceof CommitFileRevision)   return ((CommitFileRevision)revision).getRevCommit();
 else   if (revision instanceof IAdaptable) {
    final IResourceVariant variant=(IResourceVariant)((IAdaptable)revision).getAdapter(IResourceVariant.class);
    if (variant instanceof GitRemoteResource) {
      final RevCommit commit=((GitRemoteResource)variant).getCommitId();
      try {
        return walk.parseCommit(commit);
      }
 catch (      IOException e) {
        Activator.logError(NLS.bind(CoreText.GitFileHistory_invalidCommit,commit.getName(),resource.getName()),e);
      }
    }
  }
  return null;
}

Fixed version (ground truth):
private RevCommit getRevCommit(IFileRevision revision){
  if (revision instanceof CommitFileRevision)   return ((CommitFileRevision)revision).getRevCommit();
 else   if (revision instanceof IAdaptable) {
    final IResourceVariant variant=Utils.getAdapter(((IAdaptable)revision),IResourceVariant.class);
    if (variant instanceof GitRemoteResource) {
      final RevCommit commit=((GitRemoteResource)variant).getCommitId();
      try {
        return walk.parseCommit(commit);
      }
 catch (      IOException e) {
        Activator.logError(NLS.bind(CoreText.GitFileHistory_invalidCommit,commit.getName(),resource.getName()),e);
      }
    }
  }
  return null;
}
Program: 91443
Project: 91443
Buggy source:
private String getGitPath(IFileRevision revision){
  if (revision instanceof CommitFileRevision)   return ((CommitFileRevision)revision).getGitPath();
 else   if (revision instanceof IAdaptable) {
    final IResourceVariant variant=(IResourceVariant)((IAdaptable)revision).getAdapter(IResourceVariant.class);
    if (variant instanceof GitRemoteResource)     return ((GitRemoteResource)variant).getPath();
  }
  return null;
}

Fixed version (ground truth):
private String getGitPath(IFileRevision revision){
  if (revision instanceof CommitFileRevision)   return ((CommitFileRevision)revision).getGitPath();
 else   if (revision instanceof IAdaptable) {
    final IResourceVariant variant=Utils.getAdapter(((IAdaptable)revision),IResourceVariant.class);
    if (variant instanceof GitRemoteResource)     return ((GitRemoteResource)variant).getPath();
  }
  return null;
}
Program: 91444
Project: 91444
Buggy source:
private void map(final RepositoryMapping m){
  final IResource r;
  final File git;
  final IResource dotGit;
  IContainer c=null;
  m.clear();
  r=getProject().findMember(m.getContainerPath());
  if (r instanceof IContainer) {
    c=(IContainer)r;
  }
 else   if (r != null) {
    c=(IContainer)r.getAdapter(IContainer.class);
  }
  if (c == null) {
    logAndUnmapGoneMappedResource(m);
    return;
  }
  m.setContainer(c);
  git=m.getGitDirAbsolutePath().toFile();
  if (!git.isDirectory() || !new File(git,"String_Node_Str").isFile()) {
    logAndUnmapGoneMappedResource(m);
    return;
  }
  try {
    m.setRepository(Activator.getDefault().getRepositoryCache().lookupRepository(git));
  }
 catch (  IOException ioe) {
    logAndUnmapGoneMappedResource(m);
    return;
  }
  m.fireRepositoryChanged();
  trace("String_Node_Str" + c + "String_Node_Str"+ m.getRepository());
  try {
    c.setSessionProperty(MAPPING_KEY,m);
  }
 catch (  CoreException err) {
    Activator.logError(CoreText.GitProjectData_failedToCacheRepoMapping,err);
  }
  dotGit=c.findMember(Constants.DOT_GIT);
  if (dotGit != null && dotGit.getLocation().toFile().equals(git)) {
    protect(dotGit);
  }
}

Fixed version (ground truth):
private void map(final RepositoryMapping m){
  final IResource r;
  final File git;
  final IResource dotGit;
  IContainer c=null;
  m.clear();
  r=getProject().findMember(m.getContainerPath());
  if (r instanceof IContainer) {
    c=(IContainer)r;
  }
 else   if (r != null) {
    c=Utils.getAdapter(r,IContainer.class);
  }
  if (c == null) {
    logAndUnmapGoneMappedResource(m);
    return;
  }
  m.setContainer(c);
  git=m.getGitDirAbsolutePath().toFile();
  if (!git.isDirectory() || !new File(git,"String_Node_Str").isFile()) {
    logAndUnmapGoneMappedResource(m);
    return;
  }
  try {
    m.setRepository(Activator.getDefault().getRepositoryCache().lookupRepository(git));
  }
 catch (  IOException ioe) {
    logAndUnmapGoneMappedResource(m);
    return;
  }
  m.fireRepositoryChanged();
  trace("String_Node_Str" + c + "String_Node_Str"+ m.getRepository());
  try {
    c.setSessionProperty(MAPPING_KEY,m);
  }
 catch (  CoreException err) {
    Activator.logError(CoreText.GitProjectData_failedToCacheRepoMapping,err);
  }
  dotGit=c.findMember(Constants.DOT_GIT);
  if (dotGit != null && dotGit.getLocation().toFile().equals(git)) {
    protect(dotGit);
  }
}
Program: 91445
Project: 91445
Buggy source:
/** 
 * Look up best active binding's keystroke for the given command
 * @param commandId The identifier of the command for which the best active binding's keystroke should be retrieved; must not be null.
 * @return {@code KeyStroke} for the best active binding for the specifiedcommandId or  {@code null} if no binding is defined or if thebinding service returns a  {@code TriggerSequence} containing morethan one  {@code Trigger}.
 */
public static KeyStroke getKeystrokeOfBestActiveBindingFor(String commandId){
  IBindingService bindingService=(IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
  TriggerSequence ts=bindingService.getBestActiveBindingFor(commandId);
  if (ts == null)   return null;
  Trigger[] triggers=ts.getTriggers();
  if (triggers.length == 1 && triggers[0] instanceof KeyStroke)   return (KeyStroke)triggers[0];
 else   return null;
}

Fixed version (ground truth):
/** 
 * Look up best active binding's keystroke for the given command
 * @param commandId The identifier of the command for which the best active binding's keystroke should be retrieved; must not be null.
 * @return {@code KeyStroke} for the best active binding for the specifiedcommandId or  {@code null} if no binding is defined or if thebinding service returns a  {@code TriggerSequence} containing morethan one  {@code Trigger}.
 */
public static KeyStroke getKeystrokeOfBestActiveBindingFor(String commandId){
  IBindingService bindingService=CommonUtils.getAdapter(PlatformUI.getWorkbench(),IBindingService.class);
  TriggerSequence ts=bindingService.getBestActiveBindingFor(commandId);
  if (ts == null)   return null;
  Trigger[] triggers=ts.getTriggers();
  if (triggers.length == 1 && triggers[0] instanceof KeyStroke)   return (KeyStroke)triggers[0];
 else   return null;
}
Program: 91446
Project: 91446
Buggy source:
private static String getShowInMenuLabel(){
  IBindingService bindingService=(IBindingService)PlatformUI.getWorkbench().getAdapter(IBindingService.class);
  if (bindingService != null) {
    String keyBinding=bindingService.getBestActiveBindingFormattedFor(IWorkbenchCommandConstants.NAVIGATE_SHOW_IN_QUICK_MENU);
    if (keyBinding != null)     return UIText.UIUtils_ShowInMenuLabel + '\t' + keyBinding;
  }
  return UIText.UIUtils_ShowInMenuLabel;
}

Fixed version (ground truth):
private static String getShowInMenuLabel(){
  IBindingService bindingService=CommonUtils.getAdapter(PlatformUI.getWorkbench(),IBindingService.class);
  if (bindingService != null) {
    String keyBinding=bindingService.getBestActiveBindingFormattedFor(IWorkbenchCommandConstants.NAVIGATE_SHOW_IN_QUICK_MENU);
    if (keyBinding != null)     return UIText.UIUtils_ShowInMenuLabel + '\t' + keyBinding;
  }
  return UIText.UIUtils_ShowInMenuLabel;
}
Program: 91447
Project: 91447
Buggy source:
/** 
 * @param element
 * @param adapterType
 * @return the adapted element, or null
 */
public static <T>T getAdapter(Object element,Class<T> adapterType){
  if (adapterType.isInstance(element)) {
    return adapterType.cast(element);
  }
  if (element instanceof IAdaptable) {
    Object adapted=((IAdaptable)element).getAdapter(adapterType);
    if (adapterType.isInstance(adapted)) {
      return adapterType.cast(adapted);
    }
  }
  Object adapted=Platform.getAdapterManager().getAdapter(element,adapterType);
  if (adapterType.isInstance(adapted)) {
    return adapterType.cast(adapted);
  }
  return null;
}

Fixed version (ground truth):
/** 
 * Returns the adapter corresponding to the given adapter class. <p> Workaround for "Unnecessary cast" errors, see bug 460685. Can be removed when EGit depends on Eclipse 4.5 or higher.
 * @param adaptable the adaptable
 * @param adapterClass the adapter class to look up
 * @return a object of the given class, or <code>null</code> if this objectdoes not have an adapter for the given class
 */
@SuppressWarnings("String_Node_Str") public static <T>T getAdapter(IAdaptable adaptable,Class<T> adapterClass){
  Object adapter=adaptable.getAdapter(adapterClass);
  return (T)adapter;
}
Program: 91448
Project: 91448
Buggy source:
/** 
 * @param element
 * @param adapterType
 * @param load
 * @return the adapted element, or null
 */
private static Object getAdapter(Object element,Class adapterType,boolean load){
  if (adapterType.isInstance(element))   return element;
  if (element instanceof IAdaptable) {
    Object adapted=((IAdaptable)element).getAdapter(adapterType);
    if (adapterType.isInstance(adapted))     return adapted;
  }
  if (load) {
    Object adapted=Platform.getAdapterManager().loadAdapter(element,adapterType.getName());
    if (adapterType.isInstance(adapted))     return adapted;
  }
 else {
    Object adapted=Platform.getAdapterManager().getAdapter(element,adapterType);
    if (adapterType.isInstance(adapted))     return adapted;
  }
  return null;
}

Fixed version (ground truth):
/** 
 * @param element
 * @param adapterType
 * @param load
 * @return the adapted element, or null
 */
private static Object getAdapter(Object element,Class adapterType,boolean load){
  if (adapterType.isInstance(element))   return element;
  if (element instanceof IAdaptable) {
    Object adapted=CommonUtils.getAdapter(((IAdaptable)element),adapterType);
    if (adapterType.isInstance(adapted))     return adapted;
  }
  if (load) {
    Object adapted=Platform.getAdapterManager().loadAdapter(element,adapterType.getName());
    if (adapterType.isInstance(adapted))     return adapted;
  }
 else {
    Object adapted=Platform.getAdapterManager().getAdapter(element,adapterType);
    if (adapterType.isInstance(adapted))     return adapted;
  }
  return null;
}
Program: 91449
Project: 91449
Buggy source:
@Override public Image getImage(Object element){
  if (element instanceof Repository)   return RepositoryTreeNodeType.REPO.getIcon();
  if (element instanceof RefNode)   return getRefIcon(((RefNode)element).getObject());
  if (element instanceof Ref)   return getRefIcon((Ref)element);
  if (element instanceof GitModelBlob || element instanceof GitModelTree) {
    Object adapter=((IAdaptable)element).getAdapter(IResource.class);
    return getWorkbenchLabelProvider().getImage(adapter);
  }
  if (element instanceof GitModelCommit || element instanceof GitModelCache || element instanceof GitModelWorkingTree|| element instanceof RepositoryCommit)   return getChangesetIcon();
  if (element instanceof GitModelRepository)   return getImage(((GitModelRepository)element).getRepository());
  if (element instanceof ProjectRecord)   return PlatformUI.getWorkbench().getSharedImages().getImage(SharedImages.IMG_OBJ_PROJECT);
  return super.getImage(element);
}

Fixed version (ground truth):
@Override public Image getImage(Object element){
  if (element instanceof Repository)   return RepositoryTreeNodeType.REPO.getIcon();
  if (element instanceof RefNode)   return getRefIcon(((RefNode)element).getObject());
  if (element instanceof Ref)   return getRefIcon((Ref)element);
  if (element instanceof GitModelBlob || element instanceof GitModelTree) {
    Object adapter=CommonUtils.getAdapter(((IAdaptable)element),IResource.class);
    return getWorkbenchLabelProvider().getImage(adapter);
  }
  if (element instanceof GitModelCommit || element instanceof GitModelCache || element instanceof GitModelWorkingTree|| element instanceof RepositoryCommit)   return getChangesetIcon();
  if (element instanceof GitModelRepository)   return getImage(((GitModelRepository)element).getRepository());
  if (element instanceof ProjectRecord)   return PlatformUI.getWorkbench().getSharedImages().getImage(SharedImages.IMG_OBJ_PROJECT);
  return super.getImage(element);
}
Program: 91450
Project: 91450
Buggy source:
private boolean isTextFileBufferInWorkDir(Saveable saveable){
  IDocument document=(IDocument)saveable.getAdapter(IDocument.class);
  if (document == null)   return true;
  ITextFileBuffer textFileBuffer=FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
  if (textFileBuffer != null)   return isInWorkDir(textFileBuffer.getLocation());
  return false;
}

Fixed version (ground truth):
private boolean isTextFileBufferInWorkDir(Saveable saveable){
  IDocument document=CommonUtils.getAdapter(saveable,IDocument.class);
  if (document == null)   return true;
  ITextFileBuffer textFileBuffer=FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
  if (textFileBuffer != null)   return isInWorkDir(textFileBuffer.getLocation());
  return false;
}
Program: 91451
Project: 91451
Buggy source:
/** 
 * Get the currently selected repositories. All selected projects must map to a repository.
 * @return repositories for selection, or an empty array
 */
protected Repository[] getRepositories(){
  IProject[] selectedProjects=getProjectsForSelectedResources();
  if (selectedProjects.length > 0)   return getRepositoriesFor(selectedProjects);
  IStructuredSelection selection=getSelection();
  if (!selection.isEmpty()) {
    Set<Repository> repos=new LinkedHashSet<Repository>();
    for (    Object o : selection.toArray())     if (o instanceof Repository)     repos.add((Repository)o);
 else     if (o instanceof PlatformObject) {
      Repository repo=(Repository)((PlatformObject)o).getAdapter(Repository.class);
      if (repo != null)       repos.add(repo);
    }
    return repos.toArray(new Repository[repos.size()]);
  }
  return new Repository[0];
}

Fixed version (ground truth):
/** 
 * Get the currently selected repositories. All selected projects must map to a repository.
 * @return repositories for selection, or an empty array
 */
protected Repository[] getRepositories(){
  IProject[] selectedProjects=getProjectsForSelectedResources();
  if (selectedProjects.length > 0)   return getRepositoriesFor(selectedProjects);
  IStructuredSelection selection=getSelection();
  if (!selection.isEmpty()) {
    Set<Repository> repos=new LinkedHashSet<Repository>();
    for (    Object o : selection.toArray())     if (o instanceof Repository)     repos.add((Repository)o);
 else     if (o instanceof PlatformObject) {
      Repository repo=CommonUtils.getAdapter(((PlatformObject)o),Repository.class);
      if (repo != null)       repos.add(repo);
    }
    return repos.toArray(new Repository[repos.size()]);
  }
  return new Repository[0];
}
Program: 91452
Project: 91452
Buggy source:
private IResource getSelection(){
  ISelection sel=srv.getSelection();
  if (!(sel instanceof IStructuredSelection))   return null;
  Object selected=((IStructuredSelection)sel).getFirstElement();
  if (selected instanceof IAdaptable)   return (IResource)((IAdaptable)selected).getAdapter(IResource.class);
  if (selected instanceof IResource)   return (IResource)selected;
  return null;
}

Fixed version (ground truth):
private IResource getSelection(){
  ISelection sel=srv.getSelection();
  if (!(sel instanceof IStructuredSelection))   return null;
  Object selected=((IStructuredSelection)sel).getFirstElement();
  if (selected instanceof IAdaptable)   return CommonUtils.getAdapter(((IAdaptable)selected),IResource.class);
  if (selected instanceof IResource)   return (IResource)selected;
  return null;
}
Program: 91453
Project: 91453
Buggy source:
public static StagingViewTester openStagingView() throws Exception {
  Activator.getDefault().getPreferenceStore().setValue(UIPreferences.STAGING_VIEW_FILENAME_MODE,false);
  SWTBotView view=TestUtil.showView(StagingView.VIEW_ID);
  TestUtil.joinJobs(org.eclipse.egit.core.JobFamilies.INDEX_DIFF_CACHE_UPDATE);
  return new StagingViewTester(view);
}

Fixed version (ground truth):
public static StagingViewTester openStagingView() throws Exception {
  Activator.getDefault().getPreferenceStore().setValue(UIPreferences.STAGING_VIEW_FILENAME_MODE,false);
  SWTBotView view=TestUtil.showView(StagingView.VIEW_ID);
  TestUtil.joinJobs(org.eclipse.egit.core.JobFamilies.INDEX_DIFF_CACHE_UPDATE);
  TestUtil.processUIEvents();
  return new StagingViewTester(view);
}
Program: 91454
Project: 91454
Buggy source:
public void stageFile(String path){
  SWTBotTree unstagedTree=stagingView.bot().tree(0);
  TestUtil.getNode(unstagedTree.getAllItems(),path).select();
  JobJoiner jobJoiner=JobJoiner.startListening(org.eclipse.egit.core.JobFamilies.INDEX_DIFF_CACHE_UPDATE,30,TimeUnit.SECONDS);
  ContextMenuHelper.clickContextMenu(unstagedTree,UIText.StagingView_StageItemMenuLabel);
  jobJoiner.join();
}

Fixed version (ground truth):
public void stageFile(String path){
  SWTBotTree unstagedTree=stagingView.bot().tree(0);
  TestUtil.waitUntilTreeHasNodeContainsText(stagingView.bot(),unstagedTree,path,10000);
  TestUtil.getNode(unstagedTree.getAllItems(),path).select();
  JobJoiner jobJoiner=JobJoiner.startListening(org.eclipse.egit.core.JobFamilies.INDEX_DIFF_CACHE_UPDATE,30,TimeUnit.SECONDS);
  ContextMenuHelper.clickContextMenu(unstagedTree,UIText.StagingView_StageItemMenuLabel);
  jobJoiner.join();
}
Program: 91455
Project: 91455
Buggy source:
public static SWTBotView showView(final String viewId){
  Display.getDefault().syncExec(new Runnable(){
    public void run(){
      IWorkbenchWindow workbenchWindow=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      IWorkbenchPage workbenchPage=workbenchWindow.getActivePage();
      try {
        workbenchPage.showView(viewId);
      }
 catch (      PartInitException e) {
        throw new RuntimeException("String_Node_Str" + viewId + "String_Node_Str",e);
      }
    }
  }
);
  SWTWorkbenchBot bot=new SWTWorkbenchBot();
  SWTBotView viewbot=bot.viewById(viewId);
  assertNotNull("String_Node_Str" + viewId + "String_Node_Str",viewbot);
  return viewbot;
}

Fixed version (ground truth):
public static SWTBotView showView(final String viewId){
  Display.getDefault().syncExec(new Runnable(){
    public void run(){
      IWorkbenchWindow workbenchWindow=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      IWorkbenchPage workbenchPage=workbenchWindow.getActivePage();
      try {
        workbenchPage.showView(viewId);
        processUIEvents();
      }
 catch (      PartInitException e) {
        throw new RuntimeException("String_Node_Str" + viewId + "String_Node_Str",e);
      }
    }
  }
);
  SWTWorkbenchBot bot=new SWTWorkbenchBot();
  SWTBotView viewbot=bot.viewById(viewId);
  assertNotNull("String_Node_Str" + viewId + "String_Node_Str",viewbot);
  return viewbot;
}
Program: 91456
Project: 91456
Buggy source:
protected static void setTestFileContent(String newContent) throws Exception {
  IProject prj=ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1);
  if (!prj.isAccessible())   throw new IllegalStateException("String_Node_Str");
  IFile file=prj.getFile(new Path("String_Node_Str"));
  file.setContents(new ByteArrayInputStream(newContent.getBytes(prj.getDefaultCharset())),0,null);
}

Fixed version (ground truth):
protected static void setTestFileContent(String newContent) throws Exception {
  IProject prj=ResourcesPlugin.getWorkspace().getRoot().getProject(PROJ1);
  if (!prj.isAccessible())   throw new IllegalStateException("String_Node_Str");
  IFile file=prj.getFile(new Path("String_Node_Str"));
  file.refreshLocal(0,null);
  file.setContents(new ByteArrayInputStream(newContent.getBytes(prj.getDefaultCharset())),0,null);
}
Program: 91457
Project: 91457
Buggy source:
public void run(){
  if (text.isDisposed())   return;
  setDocument(new Document(job.getFormatResult().getCommitInfo()));
  List<StyleRange> styleRangeList=new ArrayList<StyleRange>();
  for (  StyleRange styleRange : job.getFormatResult().getStyleRange())   styleRangeList.add(styleRange);
  StyleRange[] hyperlinkDetectorStyleRanges=UIUtils.getHyperlinkDetectorStyleRanges(CommitMessageViewer.this,fHyperlinkDetectors);
  for (  StyleRange styleRange : hyperlinkDetectorStyleRanges)   styleRangeList.add(styleRange);
  StyleRange[] styleRanges=new StyleRange[styleRangeList.size()];
  styleRangeList.toArray(styleRanges);
  Arrays.sort(styleRanges,new Comparator<StyleRange>(){
    public int compare(    StyleRange o1,    StyleRange o2){
      if (o2.start > o1.start)       return -1;
      if (o1.start > o2.start)       return 1;
      return 0;
    }
  }
);
  text.setStyleRanges(styleRanges);
}

Fixed version (ground truth):
public void run(){
  applyFormatJobResultInUI(job.getFormatResult());
}
Program: 91458
Project: 91458
Buggy source:
void addDoneListenerToFormatJob(){
  formatJob.addJobChangeListener(new JobChangeAdapter(){
    public void done(    IJobChangeEvent event){
      if (!event.getResult().isOK())       return;
      final StyledText text=getTextWidget();
      if (text == null || text.isDisposed())       return;
      final FormatJob job=(FormatJob)event.getJob();
      text.getDisplay().asyncExec(new Runnable(){
        public void run(){
          if (text.isDisposed())           return;
          setDocument(new Document(job.getFormatResult().getCommitInfo()));
          List<StyleRange> styleRangeList=new ArrayList<StyleRange>();
          for (          StyleRange styleRange : job.getFormatResult().getStyleRange())           styleRangeList.add(styleRange);
          StyleRange[] hyperlinkDetectorStyleRanges=UIUtils.getHyperlinkDetectorStyleRanges(CommitMessageViewer.this,fHyperlinkDetectors);
          for (          StyleRange styleRange : hyperlinkDetectorStyleRanges)           styleRangeList.add(styleRange);
          StyleRange[] styleRanges=new StyleRange[styleRangeList.size()];
          styleRangeList.toArray(styleRanges);
          Arrays.sort(styleRanges,new Comparator<StyleRange>(){
            public int compare(            StyleRange o1,            StyleRange o2){
              if (o2.start > o1.start)               return -1;
              if (o1.start > o2.start)               return 1;
              return 0;
            }
          }
);
          text.setStyleRanges(styleRanges);
        }
      }
);
    }
  }
);
}

Fixed version (ground truth):
void addDoneListenerToFormatJob(){
  formatJob.addJobChangeListener(new JobChangeAdapter(){
    public void done(    IJobChangeEvent event){
      if (!event.getResult().isOK())       return;
      final StyledText text=getTextWidget();
      if (text == null || text.isDisposed())       return;
      final FormatJob job=(FormatJob)event.getJob();
      text.getDisplay().asyncExec(new Runnable(){
        public void run(){
          applyFormatJobResultInUI(job.getFormatResult());
        }
      }
);
    }
  }
);
}
Program: 91459
Project: 91459
Buggy source:
public void done(IJobChangeEvent event){
  if (!event.getResult().isOK())   return;
  final StyledText text=getTextWidget();
  if (text == null || text.isDisposed())   return;
  final FormatJob job=(FormatJob)event.getJob();
  text.getDisplay().asyncExec(new Runnable(){
    public void run(){
      if (text.isDisposed())       return;
      setDocument(new Document(job.getFormatResult().getCommitInfo()));
      List<StyleRange> styleRangeList=new ArrayList<StyleRange>();
      for (      StyleRange styleRange : job.getFormatResult().getStyleRange())       styleRangeList.add(styleRange);
      StyleRange[] hyperlinkDetectorStyleRanges=UIUtils.getHyperlinkDetectorStyleRanges(CommitMessageViewer.this,fHyperlinkDetectors);
      for (      StyleRange styleRange : hyperlinkDetectorStyleRanges)       styleRangeList.add(styleRange);
      StyleRange[] styleRanges=new StyleRange[styleRangeList.size()];
      styleRangeList.toArray(styleRanges);
      Arrays.sort(styleRanges,new Comparator<StyleRange>(){
        public int compare(        StyleRange o1,        StyleRange o2){
          if (o2.start > o1.start)           return -1;
          if (o1.start > o2.start)           return 1;
          return 0;
        }
      }
);
      text.setStyleRanges(styleRanges);
    }
  }
);
}

Fixed version (ground truth):
public void done(IJobChangeEvent event){
  if (!event.getResult().isOK())   return;
  final StyledText text=getTextWidget();
  if (text == null || text.isDisposed())   return;
  final FormatJob job=(FormatJob)event.getJob();
  text.getDisplay().asyncExec(new Runnable(){
    public void run(){
      applyFormatJobResultInUI(job.getFormatResult());
    }
  }
);
}
Program: 91460
Project: 91460
Buggy source:
/** 
 * verifies that repository contains exactly the given files with the given content. Usage example:<br> <code> assertRepositoryContainsFiles(repository, "foo/a.txt", "content of A", "foo/b.txt", "content of B") </code>
 * @param repository
 * @param args
 * @throws Exception
 */
public void assertRepositoryContainsFilesWithContent(Repository repository,String... args) throws Exception {
  HashMap<String,String> expectedfiles=mkmap(args);
  TreeWalk treeWalk=new TreeWalk(repository);
  treeWalk.addTree(repository.resolve("String_Node_Str"));
  treeWalk.setRecursive(true);
  while (treeWalk.next()) {
    String path=treeWalk.getPathString();
    assertTrue(expectedfiles.containsKey(path));
    ObjectId objectId=treeWalk.getObjectId(0);
    byte[] expectedContent=expectedfiles.get(path).getBytes("String_Node_Str");
    byte[] repoContent=treeWalk.getObjectReader().open(objectId).getBytes();
    if (!Arrays.equals(repoContent,expectedContent)) {
      fail("String_Node_Str" + path + "String_Node_Str"+ new String(repoContent,"String_Node_Str")+ "String_Node_Str"+ new String(expectedContent));
    }
    expectedfiles.remove(path);
  }
  if (expectedfiles.size() > 0) {
    StringBuilder message=new StringBuilder("String_Node_Str");
    for (    String path : expectedfiles.keySet()) {
      message.append(path);
      message.append("String_Node_Str");
    }
    fail(message.toString());
  }
}

Fixed version (ground truth):
/** 
 * verifies that repository contains exactly the given files with the given content. Usage example:<br> <code> assertRepositoryContainsFiles(repository, "foo/a.txt", "content of A", "foo/b.txt", "content of B") </code>
 * @param repository
 * @param args
 * @throws Exception
 */
public void assertRepositoryContainsFilesWithContent(Repository repository,String... args) throws Exception {
  HashMap<String,String> expectedfiles=mkmap(args);
  TreeWalk treeWalk=new TreeWalk(repository);
  treeWalk.addTree(repository.resolve("String_Node_Str"));
  treeWalk.setRecursive(true);
  while (treeWalk.next()) {
    String path=treeWalk.getPathString();
    assertTrue(expectedfiles.containsKey(path));
    ObjectId objectId=treeWalk.getObjectId(0);
    byte[] expectedContent=expectedfiles.get(path).getBytes("String_Node_Str");
    byte[] repoContent=treeWalk.getObjectReader().open(objectId).getBytes();
    if (!Arrays.equals(repoContent,expectedContent)) {
      fail("String_Node_Str" + path + "String_Node_Str"+ new String(repoContent,"String_Node_Str")+ "String_Node_Str"+ new String(expectedContent,"String_Node_Str"));
    }
    expectedfiles.remove(path);
  }
  if (expectedfiles.size() > 0) {
    StringBuilder message=new StringBuilder("String_Node_Str");
    for (    String path : expectedfiles.keySet()) {
      message.append(path);
      message.append("String_Node_Str");
    }
    fail(message.toString());
  }
}
Program: 91462
Project: 91462
Buggy source:
private void updateGitIgnore(File gitIgnore,String entry) throws CoreException {
  try {
    String ignoreLine=entry;
    if (!gitIgnore.exists())     if (!gitIgnore.createNewFile()) {
      String error=NLS.bind(CoreText.IgnoreOperation_creatingFailed,gitIgnore.getAbsolutePath());
      throw new CoreException(Activator.error(error,null));
    }
 else     ignoreLine=getEntry(gitIgnore,ignoreLine);
    FileOutputStream os=new FileOutputStream(gitIgnore,true);
    try {
      os.write(ignoreLine.getBytes());
    }
  finally {
      os.close();
    }
  }
 catch (  IOException e) {
    String error=NLS.bind(CoreText.IgnoreOperation_updatingFailed,gitIgnore.getAbsolutePath());
    throw new CoreException(Activator.error(error,e));
  }
}

Fixed version (ground truth):
private void updateGitIgnore(File gitIgnore,String entry) throws CoreException {
  try {
    String ignoreLine=entry;
    if (!gitIgnore.exists())     if (!gitIgnore.createNewFile()) {
      String error=NLS.bind(CoreText.IgnoreOperation_creatingFailed,gitIgnore.getAbsolutePath());
      throw new CoreException(Activator.error(error,null));
    }
 else     ignoreLine=getEntry(gitIgnore,ignoreLine);
    FileOutputStream os=new FileOutputStream(gitIgnore,true);
    try {
      os.write(ignoreLine.getBytes("String_Node_Str"));
    }
  finally {
      os.close();
    }
  }
 catch (  IOException e) {
    String error=NLS.bind(CoreText.IgnoreOperation_updatingFailed,gitIgnore.getAbsolutePath());
    throw new CoreException(Activator.error(error,e));
  }
}
Program: 91463
Project: 91463
Buggy source:
/** 
 * verifies that repository contains exactly the given files with the given content. Usage example:<br> <code> assertRepositoryContainsFiles(repository, "foo/a.txt", "content of A", "foo/b.txt", "content of B") </code>
 * @param repository
 * @param args
 * @throws Exception
 */
public static void assertRepositoryContainsFilesWithContent(Repository repository,String... args) throws Exception {
  HashMap<String,String> expectedfiles=mkmap(args);
  TreeWalk treeWalk=new TreeWalk(repository);
  treeWalk.addTree(repository.resolve("String_Node_Str"));
  treeWalk.setRecursive(true);
  while (treeWalk.next()) {
    String path=treeWalk.getPathString();
    assertTrue(expectedfiles.containsKey(path));
    ObjectId objectId=treeWalk.getObjectId(0);
    byte[] expectedContent=expectedfiles.get(path).getBytes("String_Node_Str");
    byte[] repoContent=treeWalk.getObjectReader().open(objectId).getBytes();
    if (!Arrays.equals(repoContent,expectedContent))     fail("String_Node_Str" + path + "String_Node_Str"+ new String(repoContent,"String_Node_Str")+ "String_Node_Str"+ new String(expectedContent));
    expectedfiles.remove(path);
  }
  if (expectedfiles.size() > 0) {
    StringBuilder message=new StringBuilder("String_Node_Str");
    for (    String path : expectedfiles.keySet()) {
      message.append(path);
      message.append("String_Node_Str");
    }
    fail(message.toString());
  }
}

Fixed version (ground truth):
/** 
 * verifies that repository contains exactly the given files with the given content. Usage example:<br> <code> assertRepositoryContainsFiles(repository, "foo/a.txt", "content of A", "foo/b.txt", "content of B") </code>
 * @param repository
 * @param args
 * @throws Exception
 */
public static void assertRepositoryContainsFilesWithContent(Repository repository,String... args) throws Exception {
  HashMap<String,String> expectedfiles=mkmap(args);
  TreeWalk treeWalk=new TreeWalk(repository);
  treeWalk.addTree(repository.resolve("String_Node_Str"));
  treeWalk.setRecursive(true);
  while (treeWalk.next()) {
    String path=treeWalk.getPathString();
    assertTrue(expectedfiles.containsKey(path));
    ObjectId objectId=treeWalk.getObjectId(0);
    byte[] expectedContent=expectedfiles.get(path).getBytes("String_Node_Str");
    byte[] repoContent=treeWalk.getObjectReader().open(objectId).getBytes();
    if (!Arrays.equals(repoContent,expectedContent))     fail("String_Node_Str" + path + "String_Node_Str"+ new String(repoContent,"String_Node_Str")+ "String_Node_Str"+ new String(expectedContent,"String_Node_Str"));
    expectedfiles.remove(path);
  }
  if (expectedfiles.size() > 0) {
    StringBuilder message=new StringBuilder("String_Node_Str");
    for (    String path : expectedfiles.keySet()) {
      message.append(path);
      message.append("String_Node_Str");
    }
    fail(message.toString());
  }
}
Program: 91465
Project: 91465
Buggy source:
private void writeToFile(final String fileName,String content) throws IOException {
  Writer output=new BufferedWriter(new FileWriter(fileName));
  try {
    output.write(content);
  }
  finally {
    output.close();
  }
}

Fixed version (ground truth):
private void writeToFile(final String fileName,String content) throws IOException {
  Writer output=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),RawParseUtils.UTF8_CHARSET));
  try {
    output.write(content);
  }
  finally {
    output.close();
  }
}
Program: 91467
Project: 91467
Buggy source:
@Override public synchronized void write(byte[] b,int off,int len){
  super.write(b,off,len);
  if (currentEncoding[0] == null)   d.append(toString());
 else   try {
    d.append(toString(currentEncoding[0]));
  }
 catch (  UnsupportedEncodingException e) {
    d.append(toString());
  }
  reset();
}

Fixed version (ground truth):
@Override public synchronized void write(byte[] b,int off,int len){
  super.write(b,off,len);
  try {
    if (currentEncoding[0] == null)     d.append(toString("String_Node_Str"));
 else     d.append(toString(currentEncoding[0]));
  }
 catch (  UnsupportedEncodingException e) {
    d.append(toString());
  }
  reset();
}
Program: 91468
Project: 91468
Buggy source:
private void writeToFile(final File file,String content) throws IOException {
  Writer output=new BufferedWriter(new FileWriter(file));
  try {
    output.write(content);
  }
  finally {
    output.close();
  }
}

Fixed version (ground truth):
private void writeToFile(final File file,String content) throws IOException {
  Writer output=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),RawParseUtils.UTF8_CHARSET));
  try {
    output.write(content);
  }
  finally {
    output.close();
  }
}
Program: 91469
Project: 91469
Buggy source:
/** 
 * {@inheritDoc} 
 */
@Override public boolean isDirty(){
  return fDirty || (sharedDocumentAdapter != null && sharedDocumentAdapter.hasBufferedContents());
}

Fixed version (ground truth):
/** 
 * {@inheritDoc} 
 */
@Override public synchronized boolean isDirty(){
  return fDirty || (sharedDocumentAdapter != null && sharedDocumentAdapter.hasBufferedContents());
}
Program: 91471
Project: 91471
Buggy source:
@Override protected Control createMessageArea(Composite composite){
  Composite main=new Composite(composite,SWT.NONE);
  main.setLayout(new GridLayout(2,false));
  GridDataFactory.fillDefaults().indent(0,0).grab(true,true).applyTo(main);
  super.createMessageArea(main);
  StyledText text=new StyledText(main,SWT.FULL_SELECTION | SWT.WRAP);
  text.setEnabled(false);
  text.setBackground(main.getBackground());
  String messageText=NLS.bind(UIText.CloneFailureDialog_checkList,cause);
  int newLinesCount=messageText.split("String_Node_Str").length;
  Bullet bullet=createBullet(main);
  text.setText(messageText);
  text.setLineBullet(newLinesCount - 4,2,bullet);
  return main;
}

Fixed version (ground truth):
@Override protected Control createMessageArea(Composite composite){
  Composite main=new Composite(composite,SWT.NONE);
  main.setLayout(new GridLayout(2,false));
  GridDataFactory.fillDefaults().indent(0,0).grab(true,true).applyTo(main);
  super.createMessageArea(main);
  StyledText text=new StyledText(main,SWT.FULL_SELECTION | SWT.WRAP);
  text.setEnabled(false);
  text.setBackground(main.getBackground());
  String messageText=NLS.bind(UIText.CloneFailureDialog_checkList,uri.toString());
  int bullets=2;
  if (!uri.getPath().endsWith("String_Node_Str")) {
    messageText=messageText + UIText.CloneFailureDialog_checkList_git;
    bullets+=1;
  }
  if ("String_Node_Str".equals(uri.getScheme())) {
    messageText=messageText + UIText.CloneFailureDialog_checkList_ssh;
    bullets+=1;
  }
 else   if ("String_Node_Str".equals(uri.getScheme())) {
    messageText=messageText + UIText.CloneFailureDialog_checkList_https;
    bullets+=1;
  }
  int newLinesCount=messageText.split("String_Node_Str").length;
  Bullet bullet=createBullet(main);
  text.setText(messageText);
  text.setLineBullet(newLinesCount - bullets,bullets,bullet);
  return main;
}
Program: 91472
Project: 91472
Buggy source:
/** 
 * Creates and shows custom error dialog for failed ls-remotes operation
 * @param parentShell
 * @param cause full failure cause message
 */
public static void show(Shell parentShell,String cause){
  SourceBranchFailureDialog dialog=new SourceBranchFailureDialog(parentShell,cause);
  dialog.setShellStyle(dialog.getShellStyle() | SWT.SHEET | SWT.RESIZE);
  dialog.open();
}

Fixed version (ground truth):
/** 
 * Creates and shows custom error dialog for failed ls-remotes operation
 * @param parentShell
 * @param uri the uri of the remote repository
 */
public static void show(Shell parentShell,URIish uri){
  SourceBranchFailureDialog dialog=new SourceBranchFailureDialog(parentShell,uri);
  dialog.setShellStyle(dialog.getShellStyle() | SWT.SHEET | SWT.RESIZE);
  dialog.open();
}
Program: 91473
Project: 91473
Buggy source:
private SourceBranchFailureDialog(Shell parentShell,String cause){
  super(parentShell,UIText.CloneFailureDialog_tile,null,null,MessageDialog.ERROR,new String[]{IDialogConstants.OK_LABEL},0);
  this.cause=cause;
}

Fixed version (ground truth):
private SourceBranchFailureDialog(Shell parentShell,URIish uri){
  super(parentShell,UIText.CloneFailureDialog_tile,null,null,MessageDialog.ERROR,new String[]{IDialogConstants.OK_LABEL},0);
  this.uri=uri;
}
Program: 91474
Project: 91474
Buggy source:
private IgnoreOperation executeIgnore(IPath... paths) throws Exception {
  IgnoreOperation operation=new IgnoreOperation(Arrays.asList(paths));
  operation.execute(new NullProgressMonitor());
  return operation;
}

Fixed version (ground truth):
private IgnoreOperation executeIgnore(IPath... paths) throws Exception {
  final IgnoreOperation operation=new IgnoreOperation(Arrays.asList(paths));
  Job job=new Job("String_Node_Str"){
    @Override protected IStatus run(    IProgressMonitor monitor){
      try {
        operation.execute(monitor);
      }
 catch (      CoreException e) {
        return e.getStatus();
      }
      return Status.OK_STATUS;
    }
  }
;
  job.setRule(operation.getSchedulingRule());
  job.schedule();
  job.join();
  if (!job.getResult().isOK())   fail("String_Node_Str" + job.getResult());
  return operation;
}
Program: 91475
Project: 91475
Buggy source:
private void addIgnore(IProgressMonitor monitor,IPath path) throws UnsupportedEncodingException, CoreException, IOException {
  IPath parent=path.removeLastSegments(1);
  IWorkspaceRoot root=ResourcesPlugin.getWorkspace().getRoot();
  IContainer container=root.getContainerForLocation(parent);
  String entry="String_Node_Str" + path.lastSegment() + "String_Node_Str";
  if (container == null || container instanceof IWorkspaceRoot) {
    Repository repository=RepositoryMapping.getMapping(path).getRepository();
    IPath gitIgnorePath=parent.append(Constants.GITIGNORE_FILENAME);
    IPath repoPath=new Path(repository.getWorkTree().getAbsolutePath());
    if (!repoPath.isPrefixOf(gitIgnorePath)) {
      String message=NLS.bind(CoreText.IgnoreOperation_parentOutsideRepo,path.toOSString(),repoPath.toOSString());
      IStatus status=Activator.error(message,null);
      throw new CoreException(status);
    }
    File gitIgnore=new File(gitIgnorePath.toOSString());
    updateGitIgnore(gitIgnore,entry);
    gitignoreOutsideWSChanged=true;
  }
 else {
    IFile gitignore=container.getFile(new Path(Constants.GITIGNORE_FILENAME));
    entry=getEntry(gitignore.getLocation().toFile(),entry);
    IProgressMonitor subMonitor=new SubProgressMonitor(monitor,1);
    ByteArrayInputStream entryBytes=asStream(entry);
    if (gitignore.exists())     gitignore.appendContents(entryBytes,true,true,subMonitor);
 else     gitignore.create(entryBytes,true,subMonitor);
  }
}

Fixed version (ground truth):
private void addIgnore(IProgressMonitor monitor,IPath path) throws UnsupportedEncodingException, CoreException, IOException {
  IPath parent=path.removeLastSegments(1);
  IResource resource=ResourceUtil.getResourceForLocation(path);
  IContainer container=null;
  if (resource != null)   container=resource.getParent();
  String entry="String_Node_Str" + path.lastSegment() + "String_Node_Str";
  if (container == null || container instanceof IWorkspaceRoot) {
    Repository repository=RepositoryMapping.getMapping(path).getRepository();
    IPath gitIgnorePath=parent.append(Constants.GITIGNORE_FILENAME);
    IPath repoPath=new Path(repository.getWorkTree().getAbsolutePath());
    if (!repoPath.isPrefixOf(gitIgnorePath)) {
      String message=NLS.bind(CoreText.IgnoreOperation_parentOutsideRepo,path.toOSString(),repoPath.toOSString());
      IStatus status=Activator.error(message,null);
      throw new CoreException(status);
    }
    File gitIgnore=new File(gitIgnorePath.toOSString());
    updateGitIgnore(gitIgnore,entry);
    gitignoreOutsideWSChanged=true;
  }
 else {
    IFile gitignore=container.getFile(new Path(Constants.GITIGNORE_FILENAME));
    entry=getEntry(gitignore.getLocation().toFile(),entry);
    IProgressMonitor subMonitor=new SubProgressMonitor(monitor,1);
    ByteArrayInputStream entryBytes=asStream(entry);
    if (gitignore.exists())     gitignore.appendContents(entryBytes,true,true,subMonitor);
 else     gitignore.create(entryBytes,true,subMonitor);
  }
}
Program: 91476
Project: 91476
Buggy source:
private IgnoreOperation executeIgnore(IPath... paths) throws Exception {
  IgnoreOperation operation=new IgnoreOperation(Arrays.asList(paths));
  operation.execute(new NullProgressMonitor());
  return operation;
}

Fixed version (ground truth):
private IgnoreOperation executeIgnore(IPath... paths) throws Exception {
  final IgnoreOperation operation=new IgnoreOperation(Arrays.asList(paths));
  Job job=new Job("String_Node_Str"){
    @Override protected IStatus run(    IProgressMonitor monitor){
      try {
        operation.execute(monitor);
      }
 catch (      CoreException e) {
        return e.getStatus();
      }
      return Status.OK_STATUS;
    }
  }
;
  job.setRule(operation.getSchedulingRule());
  job.schedule();
  job.join();
  if (!job.getResult().isOK())   fail("String_Node_Str" + job.getResult());
  return operation;
}
Program: 91477
Project: 91477
Buggy source:
private void addIgnore(IProgressMonitor monitor,IPath path) throws UnsupportedEncodingException, CoreException, IOException {
  IPath parent=path.removeLastSegments(1);
  IWorkspaceRoot root=ResourcesPlugin.getWorkspace().getRoot();
  IContainer container=root.getContainerForLocation(parent);
  String entry="String_Node_Str" + path.lastSegment() + "String_Node_Str";
  if (container == null || container instanceof IWorkspaceRoot) {
    Repository repository=RepositoryMapping.getMapping(path).getRepository();
    IPath gitIgnorePath=parent.append(Constants.GITIGNORE_FILENAME);
    IPath repoPath=new Path(repository.getWorkTree().getAbsolutePath());
    if (!repoPath.isPrefixOf(gitIgnorePath)) {
      String message=NLS.bind(CoreText.IgnoreOperation_parentOutsideRepo,path.toOSString(),repoPath.toOSString());
      IStatus status=Activator.error(message,null);
      throw new CoreException(status);
    }
    File gitIgnore=new File(gitIgnorePath.toOSString());
    updateGitIgnore(gitIgnore,entry);
    gitignoreOutsideWSChanged=true;
  }
 else {
    IFile gitignore=container.getFile(new Path(Constants.GITIGNORE_FILENAME));
    entry=getEntry(gitignore.getLocation().toFile(),entry);
    IProgressMonitor subMonitor=new SubProgressMonitor(monitor,1);
    ByteArrayInputStream entryBytes=asStream(entry);
    if (gitignore.exists())     gitignore.appendContents(entryBytes,true,true,subMonitor);
 else     gitignore.create(entryBytes,true,subMonitor);
  }
}

Fixed version (ground truth):
private void addIgnore(IProgressMonitor monitor,IPath path) throws UnsupportedEncodingException, CoreException, IOException {
  IPath parent=path.removeLastSegments(1);
  IResource resource=ResourceUtil.getResourceForLocation(path);
  IContainer container=null;
  if (resource != null)   container=resource.getParent();
  String entry="String_Node_Str" + path.lastSegment() + "String_Node_Str";
  if (container == null || container instanceof IWorkspaceRoot) {
    Repository repository=RepositoryMapping.getMapping(path).getRepository();
    IPath gitIgnorePath=parent.append(Constants.GITIGNORE_FILENAME);
    IPath repoPath=new Path(repository.getWorkTree().getAbsolutePath());
    if (!repoPath.isPrefixOf(gitIgnorePath)) {
      String message=NLS.bind(CoreText.IgnoreOperation_parentOutsideRepo,path.toOSString(),repoPath.toOSString());
      IStatus status=Activator.error(message,null);
      throw new CoreException(status);
    }
    File gitIgnore=new File(gitIgnorePath.toOSString());
    updateGitIgnore(gitIgnore,entry);
    gitignoreOutsideWSChanged=true;
  }
 else {
    IFile gitignore=container.getFile(new Path(Constants.GITIGNORE_FILENAME));
    entry=getEntry(gitignore.getLocation().toFile(),entry);
    IProgressMonitor subMonitor=new SubProgressMonitor(monitor,1);
    ByteArrayInputStream entryBytes=asStream(entry);
    if (gitignore.exists())     gitignore.appendContents(entryBytes,true,true,subMonitor);
 else     gitignore.create(entryBytes,true,subMonitor);
  }
}