nus-yam/ex-repair huggingface dataset:
Program: 21128
Project: 21128
Buggy source:
@Before public void setup(){
  MockitoAnnotations.initMocks(this);
  scanner=new StreamingBigtableResultScanner(channel,reader,cancellationToken);
}

Fixed version (ground truth):
@Before public void setup(){
  MockitoAnnotations.initMocks(this);
  scanner=new StreamingBigtableResultScanner(reader,cancellationToken);
}
Program: 21129
Project: 21129
Buggy source:
@Test public void testSetException() throws IOException, InterruptedException {
  IOException e=new IOException("String_Node_Str");
  scanner.setError(e);
  verify(reader,times(1)).add(eq(ResultQueueEntry.<ReadRowsResponse>newThrowable(e)));
  assertChannelReturned(1);
  scanner.close();
}

Fixed version (ground truth):
@Test public void testSetException() throws IOException, InterruptedException {
  IOException e=new IOException("String_Node_Str");
  scanner.setError(e);
  verify(reader,times(1)).add(eq(ResultQueueEntry.<ReadRowsResponse>newThrowable(e)));
  scanner.close();
}
Program: 21130
Project: 21130
Buggy source:
@Test public void testAddResult() throws IOException, InterruptedException {
  ReadRowsResponse response=ReadRowsResponse.getDefaultInstance();
  scanner.addResult(response);
  verify(reader,times(1)).add(eq(ResultQueueEntry.newResult(response)));
  assertChannelReturned(0);
  scanner.close();
}

Fixed version (ground truth):
@Test public void testAddResult() throws IOException, InterruptedException {
  ReadRowsResponse response=ReadRowsResponse.getDefaultInstance();
  scanner.addResult(response);
  verify(reader,times(1)).add(eq(ResultQueueEntry.newResult(response)));
  scanner.close();
}
Program: 21132
Project: 21132
Buggy source:
/** 
 * Sleep and/or determine if the backoff has timed out.
 * @param backoff
 * @return RetryState indicating the current state of the retry logic.
 * @throws IOExcetion in some cases from {@link BackOff#nextBackOffMillis()}
 */
protected RetryState getRetryState(BackOff backoff) throws IOException {
  long nextBackOffMillis=backoff.nextBackOffMillis();
  if (nextBackOffMillis == BackOff.STOP) {
    logger.warn("String_Node_Str" + this.retryOptions.getMaxElaspedBackoffMillis() + "String_Node_Str");
    return RetryState.RetriesExhausted;
  }
  try {
    sleeper.sleep(nextBackOffMillis);
    return RetryState.PerformRetry;
  }
 catch (  InterruptedException e) {
    logger.warn("String_Node_Str");
    Thread.interrupted();
    return RetryState.Interrupted;
  }
}

Fixed version (ground truth):
/** 
 * Sleep and/or determine if the backoff has timed out.
 * @param backoff
 * @return RetryState indicating the current state of the retry logic.
 * @throws IOException in some cases from {@link BackOff#nextBackOffMillis()}
 */
protected RetryState getRetryState(BackOff backoff) throws IOException {
  long nextBackOffMillis=backoff.nextBackOffMillis();
  if (nextBackOffMillis == BackOff.STOP) {
    logger.warn("String_Node_Str" + this.retryOptions.getMaxElaspedBackoffMillis() + "String_Node_Str");
    return RetryState.RetriesExhausted;
  }
  try {
    sleeper.sleep(nextBackOffMillis);
    return RetryState.PerformRetry;
  }
 catch (  InterruptedException e) {
    logger.warn("String_Node_Str");
    Thread.interrupted();
    return RetryState.Interrupted;
  }
}
Program: 21133
Project: 21133
Buggy source:
@VisibleForTesting BigtableDataGrpcClient(Channel channel,ExecutorService executorService,ScheduledExecutorService retryExecutorService,RetryOptions retryOptions,ClientCallService clientCallService){
  this.channel=channel;
  this.executorService=executorService;
  this.retryOptions=retryOptions;
  this.clientCallService=clientCallService;
  this.retryExecutorService=retryExecutorService;
  this.sampleRowKeysAsync=BigtableAsyncUtilities.createSampleRowKeyAsyncReader(this.channel,clientCallService);
  this.readRowsAsync=BigtableAsyncUtilities.createRowKeyAysncReader(this.channel,clientCallService);
}

Fixed version (ground truth):
@VisibleForTesting BigtableDataGrpcClient(ChannelPool channelPool,ExecutorService executorService,ScheduledExecutorService retryExecutorService,RetryOptions retryOptions,ClientCallService clientCallService){
  this.channelPool=channelPool;
  this.executorService=executorService;
  this.retryOptions=retryOptions;
  this.clientCallService=clientCallService;
  this.retryExecutorService=retryExecutorService;
  this.sampleRowKeysAsync=BigtableAsyncUtilities.createSampleRowKeyAsyncReader(this.channelPool,clientCallService);
  this.readRowsAsync=BigtableAsyncUtilities.createRowKeyAysncReader(this.channelPool,clientCallService);
}
Program: 21134
Project: 21134
Buggy source:
@Override public ListenableFuture<Row> readModifyWriteRowAsync(ReadModifyWriteRowRequest request){
  return clientCallService.listenableAsyncCall(channel.newCall(BigtableServiceGrpc.METHOD_READ_MODIFY_WRITE_ROW,CallOptions.DEFAULT),request);
}

Fixed version (ground truth):
@Override public ListenableFuture<Row> readModifyWriteRowAsync(ReadModifyWriteRowRequest request){
  return clientCallService.listenableAsyncCall(channelPool.newCall(BigtableServiceGrpc.METHOD_READ_MODIFY_WRITE_ROW,CallOptions.DEFAULT),request);
}
Program: 21135
Project: 21135
Buggy source:
private ResultScanner<Row> streamRows(ReadRowsRequest request){
  final ClientCall<ReadRowsRequest,ReadRowsResponse> readRowsCall=channel.newCall(BigtableServiceGrpc.METHOD_READ_ROWS,CallOptions.DEFAULT);
  CancellationToken cancellationToken=new CancellationToken();
  cancellationToken.addListener(new Runnable(){
    @Override public void run(){
      readRowsCall.cancel();
    }
  }
,executorService);
  StreamingBigtableResultScanner resultScanner=new StreamingBigtableResultScanner(retryOptions.getStreamingBufferSize(),retryOptions.getReadPartialRowTimeoutMillis(),cancellationToken);
  clientCallService.asyncServerStreamingCall(readRowsCall,request,new ReadRowsStreamObserver(resultScanner));
  return resultScanner;
}

Fixed version (ground truth):
private ResultScanner<Row> streamRows(ReadRowsRequest request){
  PooledChannel reservedChannel=channelPool.reserveChannel();
  final ClientCall<ReadRowsRequest,ReadRowsResponse> readRowsCall=reservedChannel.newCall(BigtableServiceGrpc.METHOD_READ_ROWS,CallOptions.DEFAULT);
  CancellationToken cancellationToken=new CancellationToken();
  cancellationToken.addListener(new Runnable(){
    @Override public void run(){
      readRowsCall.cancel();
    }
  }
,executorService);
  StreamingBigtableResultScanner resultScanner=new StreamingBigtableResultScanner(reservedChannel,retryOptions.getStreamingBufferSize(),retryOptions.getReadPartialRowTimeoutMillis(),cancellationToken);
  clientCallService.asyncServerStreamingCall(readRowsCall,request,new ReadRowsStreamObserver(resultScanner));
  return resultScanner;
}
Program: 21136
Project: 21136
Buggy source:
private <ReqT,RespT>ClientCall<ReqT,RespT> createRetryableCall(MethodDescriptor<ReqT,RespT> method,Predicate<ReqT> isRetryable,ReqT request){
  if (retryOptions.enableRetries() && isRetryable.apply(request)) {
    return new RetryingCall<ReqT,RespT>(channel,method,CallOptions.DEFAULT,retryExecutorService,retryOptions);
  }
 else {
    return channel.newCall(method,CallOptions.DEFAULT);
  }
}

Fixed version (ground truth):
private <ReqT,RespT>ClientCall<ReqT,RespT> createRetryableCall(MethodDescriptor<ReqT,RespT> method,Predicate<ReqT> isRetryable,ReqT request){
  if (retryOptions.enableRetries() && isRetryable.apply(request)) {
    return new RetryingCall<ReqT,RespT>(channelPool,method,CallOptions.DEFAULT,retryExecutorService,retryOptions);
  }
 else {
    return channelPool.newCall(method,CallOptions.DEFAULT);
  }
}
Program: 21137
Project: 21137
Buggy source:
@Override public ImmutableList<SampleRowKeysResponse> sampleRowKeys(SampleRowKeysRequest request){
  return ImmutableList.copyOf(clientCallService.blockingServerStreamingCall(channel.newCall(BigtableServiceGrpc.METHOD_SAMPLE_ROW_KEYS,CallOptions.DEFAULT),request));
}

Fixed version (ground truth):
@Override public ImmutableList<SampleRowKeysResponse> sampleRowKeys(SampleRowKeysRequest request){
  return ImmutableList.copyOf(clientCallService.blockingServerStreamingCall(channelPool.newCall(BigtableServiceGrpc.METHOD_SAMPLE_ROW_KEYS,CallOptions.DEFAULT),request));
}
Program: 21138
Project: 21138
Buggy source:
@Override public Row readModifyWriteRow(ReadModifyWriteRowRequest request){
  return clientCallService.blockingUnaryCall(channel.newCall(BigtableServiceGrpc.METHOD_READ_MODIFY_WRITE_ROW,CallOptions.DEFAULT),request);
}

Fixed version (ground truth):
@Override public Row readModifyWriteRow(ReadModifyWriteRowRequest request){
  return clientCallService.blockingUnaryCall(channelPool.newCall(BigtableServiceGrpc.METHOD_READ_MODIFY_WRITE_ROW,CallOptions.DEFAULT),request);
}
Program: 21139
Project: 21139
Buggy source:
private BigtableDataClient initializeDataClient() throws IOException {
  Channel channel=createChannel(options.getDataHost(),options.getChannelCount());
  RetryOptions retryOptions=options.getRetryOptions();
  return new BigtableDataGrpcClient(channel,batchPool,scheduledRetries,retryOptions);
}

Fixed version (ground truth):
private BigtableDataClient initializeDataClient() throws IOException {
  ChannelPool channel=createChannel(options.getDataHost(),options.getChannelCount());
  RetryOptions retryOptions=options.getRetryOptions();
  return new BigtableDataGrpcClient(channel,batchPool,scheduledRetries,retryOptions);
}
Program: 21140
Project: 21140
Buggy source:
@Override protected void checkedStart(ClientCall.Listener<ResponseT> responseListener,Metadata headers) throws Exception {
  for (  HeaderInterceptor interceptor : headerInterceptors) {
    interceptor.updateHeaders(headers);
  }
  delegate().start(responseListener,headers);
}

Fixed version (ground truth):
@Override protected void checkedStart(ClientCall.Listener<RespT> responseListener,Metadata headers) throws Exception {
  for (  HeaderInterceptor interceptor : headerInterceptors) {
    interceptor.updateHeaders(headers);
  }
  delegate().start(responseListener,headers);
}
Program: 21141
Project: 21141
Buggy source:
@Override public <RequestT,ResponseT>ClientCall<RequestT,ResponseT> newCall(MethodDescriptor<RequestT,ResponseT> methodDescriptor,CallOptions callOptions){
  int currentRequestNum=requestCount.getAndIncrement();
  int index=Math.abs(currentRequestNum % channels.length);
  ClientCall<RequestT,ResponseT> delegate=channels[index].newCall(methodDescriptor,callOptions);
  return new CheckedForwardingClientCall<RequestT,ResponseT>(delegate){
    @Override protected void checkedStart(    ClientCall.Listener<ResponseT> responseListener,    Metadata headers) throws Exception {
      for (      HeaderInterceptor interceptor : headerInterceptors) {
        interceptor.updateHeaders(headers);
      }
      delegate().start(responseListener,headers);
    }
  }
;
}

Fixed version (ground truth):
@Override public <ReqT,RespT>ClientCall<ReqT,RespT> newCall(MethodDescriptor<ReqT,RespT> methodDescriptor,CallOptions callOptions){
  return createWrappedCall(methodDescriptor,callOptions,getNextChannel());
}
Program: 21142
Project: 21142
Buggy source:
public void setError(Throwable error){
  add(ResultQueueEntry.<ReadRowsResponse>newThrowable(error));
}

Fixed version (ground truth):
public void setError(Throwable error){
  reservedChannel.returnToPool();
  add(ResultQueueEntry.<ReadRowsResponse>newThrowable(error));
}
Program: 21143
Project: 21143
Buggy source:
public StreamingBigtableResultScanner(int capacity,int readPartialRowTimeoutMillis,CancellationToken cancellationToken){
  Preconditions.checkArgument(cancellationToken != null,"String_Node_Str");
  Preconditions.checkArgument(capacity > 0,"String_Node_Str");
  this.cancellationToken=cancellationToken;
  this.resultQueue=new LinkedBlockingQueue<>(capacity);
  this.responseQueueReader=new ResponseQueueReader(resultQueue,readPartialRowTimeoutMillis);
}

Fixed version (ground truth):
public StreamingBigtableResultScanner(PooledChannel reservedChannel,int capacity,int readPartialRowTimeoutMillis,CancellationToken cancellationToken){
  Preconditions.checkArgument(cancellationToken != null,"String_Node_Str");
  Preconditions.checkArgument(capacity > 0,"String_Node_Str");
  this.reservedChannel=reservedChannel;
  this.cancellationToken=cancellationToken;
  this.resultQueue=new LinkedBlockingQueue<>(capacity);
  this.responseQueueReader=new ResponseQueueReader(resultQueue,readPartialRowTimeoutMillis);
}
Program: 21144
Project: 21144
Buggy source:
public void complete(){
  add(ResultQueueEntry.<ReadRowsResponse>newCompletionMarker());
}

Fixed version (ground truth):
public void complete(){
  reservedChannel.returnToPool();
  add(ResultQueueEntry.<ReadRowsResponse>newCompletionMarker());
}
Program: 21145
Project: 21145
Buggy source:
@Override public void close() throws IOException {
  cancellationToken.cancel();
}

Fixed version (ground truth):
@Override public void close() throws IOException {
  cancellationToken.cancel();
  reservedChannel.returnToPool();
}
Program: 21146
Project: 21146
Buggy source:
private static void validate(CloudBigtableConfiguration configuration,String tableId){
  checkNotNullOrEmpty(configuration.getProjectId(),"String_Node_Str");
  checkNotNullOrEmpty(configuration.getZoneId(),"String_Node_Str");
  checkNotNullOrEmpty(configuration.getClusterId(),"String_Node_Str");
  if (tableId != null) {
    checkNotNullOrEmpty(tableId,"String_Node_Str");
    if (BigtableSession.isAlpnConfigured()) {
      try (BigtableConnection conn=new BigtableConnection(configuration.toHBaseConfig());Admin admin=conn.getAdmin()){
        Preconditions.checkState(admin.tableExists(TableName.valueOf(tableId)));
      }
 catch (      IOException|IllegalArgumentException|ExceptionInInitializerError e) {
        LOG.error(String.format("String_Node_Str",e.getClass().getName(),e.getMessage()),e);
      }
    }
 else {
      LOG.info("String_Node_Str");
    }
  }
}

Fixed version (ground truth):
private static void validate(CloudBigtableConfiguration configuration,String tableId){
  checkNotNullOrEmpty(configuration.getProjectId(),"String_Node_Str");
  checkNotNullOrEmpty(configuration.getZoneId(),"String_Node_Str");
  checkNotNullOrEmpty(configuration.getClusterId(),"String_Node_Str");
  if (tableId != null) {
    checkNotNullOrEmpty(tableId,"String_Node_Str");
    if (BigtableSession.isAlpnProviderEnabled()) {
      try (BigtableConnection conn=new BigtableConnection(configuration.toHBaseConfig());Admin admin=conn.getAdmin()){
        Preconditions.checkState(admin.tableExists(TableName.valueOf(tableId)));
      }
 catch (      IOException|IllegalArgumentException|ExceptionInInitializerError e) {
        LOG.error(String.format("String_Node_Str",e.getClass().getName(),e.getMessage()),e);
      }
    }
 else {
      LOG.info("String_Node_Str");
    }
  }
}
Program: 21147
Project: 21147
Buggy source:
@AfterClass public static void shutdown(){
  connection.close();
}

Fixed version (ground truth):
@AfterClass public static void shutdown() throws IOException {
  connection.close();
}
Program: 21148
Project: 21148
Buggy source:
@Test public void testRefreshDoesntHang() throws Exception, TimeoutException {
  long start=HeaderCacheElement.TOKEN_STALENESS_MS * 10;
  setTime(start);
  final long expiration=start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1;
  final Object lock=new String("String_Node_Str");
  Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>(){
    @Override public AccessToken answer(    InvocationOnMock invocation) throws Throwable {
synchronized (lock) {
        lock.wait();
      }
      return new AccessToken("String_Node_Str",new Date(expiration));
    }
  }
);
  Callable<Void> syncRefreshCallable=new Callable<Void>(){
    @Override public Void call() throws Exception {
      underTest.syncRefresh();
      return null;
    }
  }
;
  underTest=new RefreshingOAuth2CredentialsInterceptor(executorService,credentials);
  Assert.assertEquals(CacheState.Expired,RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
  Future<Void> future=executorService.submit(syncRefreshCallable);
  Thread.yield();
synchronized (lock) {
    lock.notifyAll();
  }
  future.get(1,TimeUnit.SECONDS);
  Assert.assertEquals(CacheState.Stale,RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
  Assert.assertFalse(underTest.isRefreshing.get());
  underTest.asyncRefresh();
  underTest.asyncRefresh();
  underTest.asyncRefresh();
  future=executorService.submit(syncRefreshCallable);
  Thread.yield();
  Assert.assertTrue(underTest.isRefreshing.get());
synchronized (lock) {
    lock.notifyAll();
  }
  future.get(1,TimeUnit.SECONDS);
  Assert.assertFalse(underTest.isRefreshing.get());
}

Fixed version (ground truth):
@Test public void testRefreshDoesntHang() throws Exception, TimeoutException {
  long start=HeaderCacheElement.TOKEN_STALENESS_MS * 10;
  setTime(start);
  final long expiration=start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1;
  final Object lock=new String("String_Node_Str");
  Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>(){
    @Override public AccessToken answer(    InvocationOnMock invocation) throws Throwable {
synchronized (lock) {
        lock.wait();
      }
      return new AccessToken("String_Node_Str",new Date(expiration));
    }
  }
);
  Callable<Void> syncRefreshCallable=new Callable<Void>(){
    @Override public Void call() throws Exception {
      underTest.syncRefresh();
      return null;
    }
  }
;
  underTest=new RefreshingOAuth2CredentialsInterceptor(executorService,credentials);
  Assert.assertEquals(CacheState.Expired,RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
  syncCall(lock,syncRefreshCallable);
  Assert.assertEquals(CacheState.Stale,RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
  Assert.assertFalse(underTest.isRefreshing.get());
  underTest.asyncRefresh();
  underTest.asyncRefresh();
  underTest.asyncRefresh();
  syncCall(lock,syncRefreshCallable);
  Assert.assertFalse(underTest.isRefreshing.get());
}
Program: 21149
Project: 21149
Buggy source:
@Override public void onValue(T value){
  buffer.add(value);
}

Fixed version (ground truth):
@Override public void onValue(T value){
  buffer.add(value);
  call.request(1);
}
Program: 21150
Project: 21150
Buggy source:
public ReadRowsStreamObserver(StreamingBigtableResultScanner scanner){
  this.scanner=scanner;
}

Fixed version (ground truth):
public ReadRowsStreamObserver(StreamingBigtableResultScanner scanner,Call<ReadRowsRequest,ReadRowsResponse> call){
  this.scanner=scanner;
  this.call=call;
}
Program: 21151
Project: 21151
Buggy source:
/** 
 * Begin reading rows, optionally with a resumable scanner.
 */
private ResultScanner<Row> readRows(ReadRowsRequest request,boolean resumable){
  if (resumable) {
    return new ResumingStreamingResultScanner(retryOptions,request,new BigtableResultScannerFactory(){
      @Override public ResultScanner<Row> createScanner(      ReadRowsRequest request){
        return readRows(request,false);
      }
    }
);
  }
  final Call<ReadRowsRequest,ReadRowsResponse> readRowsCall=channel.newCall(BigtableServiceGrpc.CONFIG.readRows);
  CancellationToken cancellationToken=new CancellationToken();
  cancellationToken.addListener(new Runnable(){
    @Override public void run(){
      readRowsCall.cancel();
    }
  }
,executorService);
  StreamingBigtableResultScanner resultScanner=new StreamingBigtableResultScanner(retryOptions.getStreamingBufferSize(),retryOptions.getReadPartialRowTimeoutMillis(),cancellationToken);
  Calls.asyncServerStreamingCall(readRowsCall,request,new ReadRowsStreamObserver(resultScanner));
  return resultScanner;
}

Fixed version (ground truth):
/** 
 * Begin reading rows, optionally with a resumable scanner.
 */
private ResultScanner<Row> readRows(ReadRowsRequest request,boolean resumable){
  if (resumable) {
    return new ResumingStreamingResultScanner(retryOptions,request,new BigtableResultScannerFactory(){
      @Override public ResultScanner<Row> createScanner(      ReadRowsRequest request){
        return readRows(request,false);
      }
    }
);
  }
  final Call<ReadRowsRequest,ReadRowsResponse> readRowsCall=channel.newCall(BigtableServiceGrpc.CONFIG.readRows);
  CancellationToken cancellationToken=new CancellationToken();
  cancellationToken.addListener(new Runnable(){
    @Override public void run(){
      readRowsCall.cancel();
    }
  }
,executorService);
  StreamingBigtableResultScanner resultScanner=new StreamingBigtableResultScanner(retryOptions.getStreamingBufferSize(),retryOptions.getReadPartialRowTimeoutMillis(),cancellationToken);
  Calls.asyncServerStreamingCall(readRowsCall,request,new ReadRowsStreamObserver(resultScanner,readRowsCall));
  return resultScanner;
}
Program: 21152
Project: 21152
Buggy source:
@Override public ListenableFuture<ImmutableList<SampleRowKeysResponse>> sampleRowKeysAsync(SampleRowKeysRequest request){
  CollectingStreamObserver<SampleRowKeysResponse> responseBuffer=new CollectingStreamObserver<>();
  Calls.asyncServerStreamingCall(channel.newCall(BigtableServiceGrpc.CONFIG.sampleRowKeys),request,responseBuffer);
  return Futures.transform(responseBuffer.getResponseCompleteFuture(),new Function<List<SampleRowKeysResponse>,ImmutableList<SampleRowKeysResponse>>(){
    @Override public ImmutableList<SampleRowKeysResponse> apply(    List<SampleRowKeysResponse> sampleRowKeysResponses){
      return ImmutableList.copyOf(sampleRowKeysResponses);
    }
  }
);
}

Fixed version (ground truth):
@Override public ListenableFuture<ImmutableList<SampleRowKeysResponse>> sampleRowKeysAsync(SampleRowKeysRequest request){
  Call<SampleRowKeysRequest,SampleRowKeysResponse> call=channel.newCall(BigtableServiceGrpc.CONFIG.sampleRowKeys);
  CollectingStreamObserver<SampleRowKeysResponse> responseBuffer=new CollectingStreamObserver<>(call);
  Calls.asyncServerStreamingCall(call,request,responseBuffer);
  return Futures.transform(responseBuffer.getResponseCompleteFuture(),new Function<List<SampleRowKeysResponse>,ImmutableList<SampleRowKeysResponse>>(){
    @Override public ImmutableList<SampleRowKeysResponse> apply(    List<SampleRowKeysResponse> sampleRowKeysResponses){
      return ImmutableList.copyOf(sampleRowKeysResponses);
    }
  }
);
}
Program: 21153
Project: 21153
Buggy source:
@Override public ListenableFuture<List<Row>> readRowsAsync(final ReadRowsRequest request){
  final Call<ReadRowsRequest,ReadRowsResponse> readRowsCall=channel.newCall(BigtableServiceGrpc.CONFIG.readRows);
  CollectingStreamObserver<ReadRowsResponse> responseCollector=new CollectingStreamObserver<>();
  Calls.asyncServerStreamingCall(readRowsCall,request,responseCollector);
  return Futures.transform(responseCollector.getResponseCompleteFuture(),new Function<List<ReadRowsResponse>,List<Row>>(){
    @Override public List<Row> apply(    List<ReadRowsResponse> responses){
      List<Row> result=new ArrayList<>();
      Iterator<ReadRowsResponse> responseIterator=responses.iterator();
      while (responseIterator.hasNext()) {
        RowMerger currentRowMerger=new RowMerger();
        while (responseIterator.hasNext() && !currentRowMerger.isRowCommitted()) {
          currentRowMerger.addPartialRow(responseIterator.next());
        }
        result.add(currentRowMerger.buildRow());
      }
      return result;
    }
  }
);
}

Fixed version (ground truth):
@Override public ListenableFuture<List<Row>> readRowsAsync(final ReadRowsRequest request){
  final Call<ReadRowsRequest,ReadRowsResponse> readRowsCall=channel.newCall(BigtableServiceGrpc.CONFIG.readRows);
  CollectingStreamObserver<ReadRowsResponse> responseCollector=new CollectingStreamObserver<>(readRowsCall);
  Calls.asyncServerStreamingCall(readRowsCall,request,responseCollector);
  return Futures.transform(responseCollector.getResponseCompleteFuture(),new Function<List<ReadRowsResponse>,List<Row>>(){
    @Override public List<Row> apply(    List<ReadRowsResponse> responses){
      List<Row> result=new ArrayList<>();
      Iterator<ReadRowsResponse> responseIterator=responses.iterator();
      while (responseIterator.hasNext()) {
        RowMerger currentRowMerger=new RowMerger();
        while (responseIterator.hasNext() && !currentRowMerger.isRowCommitted()) {
          currentRowMerger.addPartialRow(responseIterator.next());
        }
        result.add(currentRowMerger.buildRow());
      }
      return result;
    }
  }
);
}
Program: 21154
Project: 21154
Buggy source:
public CacheState getCacheState(){
  long now=System.currentTimeMillis();
  if (now < staleTimeMs) {
    return CacheState.Good;
  }
 else   if (now < expiresTimeMs) {
    return CacheState.Stale;
  }
 else {
    return CacheState.Expired;
  }
}

Fixed version (ground truth):
@VisibleForTesting static CacheState getCacheState(HeaderCacheElement headerCache){
  return (headerCache == null) ? CacheState.Expired : headerCache.getCacheState();
}
Program: 21155
Project: 21155
Buggy source:
public void asyncRefresh(){
  if (!isRefreshing.get()) {
    executor.execute(new Runnable(){
      @Override public void run(){
        doRefresh();
      }
    }
);
  }
}

Fixed version (ground truth):
public void asyncRefresh(){
  executor.execute(new Runnable(){
    @Override public void run(){
      doRefresh();
    }
  }
);
}
Program: 21156
Project: 21156
Buggy source:
/** 
 * Perform a credentials refresh.
 */
private void doRefresh(){
  boolean requiresRefresh=false;
synchronized (isRefreshing) {
    if (!isRefreshing.get()) {
      isRefreshing.set(true);
      requiresRefresh=true;
      HeaderCacheElement headerCache=this.headerCache.get();
      CacheState state=(headerCache == null) ? CacheState.Expired : headerCache.getCacheState();
      requiresRefresh=state != CacheState.Good;
    }
  }
  if (!requiresRefresh) {
    return;
  }
  HeaderCacheElement cacheElement=null;
  try {
    AccessToken newToken=credentials.refreshAccessToken();
    if (newToken == null) {
      cacheElement=new HeaderCacheElement(new IOException("String_Node_Str" + credentials));
    }
 else {
      cacheElement=new HeaderCacheElement(newToken);
    }
  }
 catch (  IOException e) {
    cacheElement=new HeaderCacheElement(e);
  }
catch (  Exception e) {
    cacheElement=new HeaderCacheElement(new IOException("String_Node_Str",e));
  }
 finally {
synchronized (isRefreshing) {
      this.headerCache.set(cacheElement);
      isRefreshing.set(false);
      isRefreshing.notifyAll();
    }
  }
}

Fixed version (ground truth):
/** 
 * Perform a credentials refresh.
 */
@VisibleForTesting boolean doRefresh(){
  boolean requiresRefresh=false;
synchronized (isRefreshing) {
    if (!isRefreshing.get() && getCacheState(this.headerCache.get()) != CacheState.Good) {
      isRefreshing.set(true);
      requiresRefresh=true;
    }
  }
  if (!requiresRefresh) {
    return false;
  }
  HeaderCacheElement cacheElement=null;
  try {
    AccessToken newToken=credentials.refreshAccessToken();
    if (newToken == null) {
      cacheElement=new HeaderCacheElement(new IOException("String_Node_Str" + credentials));
    }
 else {
      cacheElement=new HeaderCacheElement(newToken);
    }
  }
 catch (  IOException e) {
    cacheElement=new HeaderCacheElement(e);
  }
catch (  Exception e) {
    cacheElement=new HeaderCacheElement(new IOException("String_Node_Str",e));
  }
 finally {
synchronized (isRefreshing) {
      headerCache.set(cacheElement);
      isRefreshing.set(false);
      isRefreshing.notifyAll();
    }
  }
  return true;
}
Program: 21157
Project: 21157
Buggy source:
public void syncRefresh() throws IOException {
synchronized (isRefreshing) {
    if (!isRefreshing.get()) {
      doRefresh();
    }
 else {
      while (isRefreshing.get()) {
        try {
          isRefreshing.wait(250);
        }
 catch (        InterruptedException e) {
          throw new IOException(e);
        }
      }
    }
  }
}

Fixed version (ground truth):
public void syncRefresh() throws IOException {
synchronized (isRefreshing) {
    if (!isRefreshing.get()) {
      doRefresh();
    }
 else {
      while (isRefreshing.get() && getCacheState(this.headerCache.get()) != CacheState.Good) {
        try {
          isRefreshing.wait(250);
        }
 catch (        InterruptedException e) {
          throw new IOException(e);
        }
      }
    }
  }
}
Program: 21158
Project: 21158
Buggy source:
/** 
 * Get the http credential header we need from a new oauth2 AccessToken.
 */
private String getHeader() throws IOException {
  HeaderCacheElement headerCache=getCachedHeader();
  CacheState state=(headerCache == null) ? CacheState.Expired : headerCache.getCacheState();
switch (state) {
case Good:
    break;
case Stale:
  asyncRefresh();
break;
case Expired:
syncRefresh();
headerCache=getCachedHeader();
break;
default :
throw new IllegalStateException("String_Node_Str" + state);
}
return headerCache.header;
}

Fixed version (ground truth):
/** 
 * Get the http credential header we need from a new oauth2 AccessToken.
 */
@VisibleForTesting String getHeader() throws IOException {
  HeaderCacheElement headerCache=getCachedHeader();
  CacheState state=getCacheState(headerCache);
switch (state) {
case Good:
    break;
case Stale:
  asyncRefresh();
break;
case Expired:
syncRefresh();
headerCache=getCachedHeader();
break;
default :
throw new IllegalStateException("String_Node_Str" + state);
}
return headerCache.header;
}
Program: 21159
Project: 21159
Buggy source:
@Override protected void after(){
  try (Admin admin=connection.getAdmin()){
    admin.disableTable(TABLE_NAME);
    admin.deleteTable(TABLE_NAME);
  }
 catch (  Exception e) {
    throw new RuntimeException("String_Node_Str",e);
  }
  try {
    connection.close();
  }
 catch (  IOException e) {
    throw new RuntimeException("String_Node_Str",e);
  }
  if (useMiniCluster()) {
    try {
      testingUtility.shutdownMiniCluster();
    }
 catch (    Exception e) {
      throw new RuntimeException("String_Node_Str",e);
    }
  }
}

Fixed version (ground truth):
@Override protected void after(){
  try (Admin admin=connection.getAdmin()){
    admin.disableTable(TABLE_NAME);
    admin.deleteTable(TABLE_NAME);
  }
 catch (  Exception e) {
    throw new RuntimeException("String_Node_Str",e);
  }
  try {
    connection.close();
  }
 catch (  IOException e) {
    throw new RuntimeException("String_Node_Str",e);
  }
  if (useMiniCluster()) {
    try {
      testingUtility.shutdownMiniCluster();
    }
 catch (    Exception e) {
      throw new RuntimeException("String_Node_Str",e);
    }
  }
  Assert.assertTrue(connection.isClosed());
}
Program: 21161
Project: 21161
Buggy source:
@Test @Category(KnownGap.class) public void testPageFilters() throws IOException {
  byte[][] rowKeys=dataHelper.randomData("String_Node_Str",100);
  byte[] qualA=dataHelper.randomData("String_Node_Str");
  byte[] value=Bytes.toBytes("String_Node_Str");
  Table table=getConnection().getTable(TABLE_NAME);
  for (  byte[] rowKey : rowKeys) {
    Put put=new Put(rowKey).addColumn(COLUMN_FAMILY,qualA,value);
    table.put(put);
  }
  Scan scan=new Scan(Bytes.toBytes("String_Node_Str"));
  PageFilter pageFilter=new PageFilter(20);
  scan.setFilter(pageFilter);
  try (ResultScanner scanner=table.getScanner(scan)){
    Assert.assertEquals(20,Iterators.size(scanner.iterator()));
  }
   FilterList filterList=new FilterList(Operator.MUST_PASS_ALL,new QualifierFilter(CompareOp.EQUAL,new BinaryComparator(qualA)),pageFilter);
  scan.setFilter(filterList);
  try (ResultScanner scanner=table.getScanner(scan)){
    Assert.assertEquals(20,Iterators.size(scanner.iterator()));
  }
 }

Fixed version (ground truth):
@Test public void testPageFilters() throws IOException {
  byte[][] rowKeys=dataHelper.randomData("String_Node_Str",100);
  byte[] qualA=dataHelper.randomData("String_Node_Str");
  byte[] value=Bytes.toBytes("String_Node_Str");
  Table table=getConnection().getTable(TABLE_NAME);
  for (  byte[] rowKey : rowKeys) {
    Put put=new Put(rowKey).addColumn(COLUMN_FAMILY,qualA,value);
    table.put(put);
  }
  Scan scan=new Scan(Bytes.toBytes("String_Node_Str"));
  PageFilter pageFilter=new PageFilter(20);
  scan.setFilter(pageFilter);
  try (ResultScanner scanner=table.getScanner(scan)){
    Assert.assertEquals(20,Iterators.size(scanner.iterator()));
  }
   FilterList filterList=new FilterList(Operator.MUST_PASS_ALL,new QualifierFilter(CompareOp.EQUAL,new BinaryComparator(qualA)),pageFilter);
  scan.setFilter(filterList);
  try (ResultScanner scanner=table.getScanner(scan)){
    Assert.assertEquals(20,Iterators.size(scanner.iterator()));
  }
 }
Program: 21162
Project: 21162
Buggy source:
@Override public RowFilter adapt(FilterAdapterContext context,FilterList filter) throws IOException {
  try (ContextCloseable ignored=context.beginFilterList(filter)){
    List<RowFilter> childFilters=collectChildFilters(context,filter);
    if (childFilters.isEmpty()) {
      return null;
    }
    if (filter.getOperator() == Operator.MUST_PASS_ALL) {
      return RowFilter.newBuilder().setChain(Chain.newBuilder().addAllFilters(childFilters)).build();
    }
 else {
      return RowFilter.newBuilder().setInterleave(Interleave.newBuilder().addAllFilters(childFilters)).build();
    }
  }
 }

Fixed version (ground truth):
@Override public RowFilter adapt(FilterAdapterContext context,FilterList filter) throws IOException {
  try (ContextCloseable ignored=context.beginFilterList(filter)){
    List<RowFilter> childFilters=collectChildFilters(context,filter);
    if (childFilters.isEmpty()) {
      return null;
    }
 else     if (childFilters.size() == 1) {
      return childFilters.get(0);
    }
 else     if (filter.getOperator() == Operator.MUST_PASS_ALL) {
      return RowFilter.newBuilder().setChain(Chain.newBuilder().addAllFilters(childFilters)).build();
    }
 else {
      return RowFilter.newBuilder().setInterleave(Interleave.newBuilder().addAllFilters(childFilters)).build();
    }
  }
 }
Program: 21163
Project: 21163
Buggy source:
@SuppressWarnings("String_Node_Str") @Override public SslContext create(){
  try {
    return GrpcSslContexts.forClient().build();
  }
 catch (  SSLException e) {
    throw new IllegalStateException("String_Node_Str",e);
  }
}

Fixed version (ground truth):
@SuppressWarnings("String_Node_Str") @Override public SslContext create(){
  try {
    return SslContext.newClientContext();
  }
 catch (  SSLException e) {
    throw new IllegalStateException("String_Node_Str",e);
  }
}
Program: 21165
Project: 21165
Buggy source:
@Override public CloseableChannel create(){
  return createCloseableChannel(transportOptions,executor);
}

Fixed version (ground truth):
@Override public CloseableChannel create(){
  CloseableChannel channel=createCloseableChannel(transportOptions,executor);
  return new InflightCheckingChannel(channel);
}
Program: 21166
Project: 21166
Buggy source:
private static CloseableChannel createRefreshingChannel(final TransportOptions transportOptions,final ExecutorService executor,long timeoutMs){
  if (timeoutMs > 0) {
    return new ReconnectingChannel(timeoutMs,executor,new ReconnectingChannel.Factory(){
      @Override public CloseableChannel create(){
        return createCloseableChannel(transportOptions,executor);
      }
    }
);
  }
 else {
    return createCloseableChannel(transportOptions,executor);
  }
}

Fixed version (ground truth):
private static CloseableChannel createRefreshingChannel(final TransportOptions transportOptions,final ExecutorService executor,long timeoutMs){
  if (timeoutMs > 0) {
    return new ReconnectingChannel(timeoutMs,executor,new ReconnectingChannel.Factory(){
      @Override public CloseableChannel create(){
        CloseableChannel channel=createCloseableChannel(transportOptions,executor);
        return new InflightCheckingChannel(channel);
      }
    }
);
  }
 else {
    return createCloseableChannel(transportOptions,executor);
  }
}
Program: 21167
Project: 21167
Buggy source:
@Test public void testBufferSizeFlush() throws Exception {
  int maxSize=1024;
  try (BufferedMutator mutator=connection.getBufferedMutator(new BufferedMutatorParams(TABLE_NAME).writeBufferSize(maxSize))){
    Put put=getPut();
    mutator.mutate(put);
    Assert.assertEquals(put.heapSize(),mutator.getWriteBufferSize());
    Put largePut=new Put(dataHelper.randomData("String_Node_Str"));
    largePut.addColumn(COLUMN_FAMILY,qualifier,Bytes.toBytes(RandomStringUtils.randomAlphanumeric(maxSize * 2)));
    long heapSize=largePut.heapSize();
    Assert.assertTrue("String_Node_Str" + heapSize,heapSize > maxSize);
    mutator.mutate(largePut);
    Assert.assertEquals(0,mutator.getWriteBufferSize());
  }
 }

Fixed version (ground truth):
@Test public void testBufferSizeFlush() throws Exception {
  int maxSize=1024;
  BufferedMutatorParams params=new BufferedMutatorParams(TABLE_NAME).writeBufferSize(maxSize);
  try (BufferedMutator mutator=connection.getBufferedMutator(params)){
    Assert.assertTrue(0 == mutator.getWriteBufferSize() || maxSize == mutator.getWriteBufferSize());
    Put put=getPut();
    mutator.mutate(put);
    Assert.assertTrue(mutator.getWriteBufferSize() > 0);
    Put largePut=new Put(dataHelper.randomData("String_Node_Str"));
    largePut.addColumn(COLUMN_FAMILY,qualifier,Bytes.toBytes(RandomStringUtils.randomAlphanumeric(maxSize * 2)));
    long heapSize=largePut.heapSize();
    Assert.assertTrue("String_Node_Str" + heapSize,heapSize > maxSize);
    mutator.mutate(largePut);
    Assert.assertTrue(0 == mutator.getWriteBufferSize() || maxSize == mutator.getWriteBufferSize());
  }
 }
Program: 21168
Project: 21168
Buggy source:
AuthorityType detectAuthorityType(){
  if (authorityUrl == null) {
    throw new NullPointerException("String_Node_Str");
  }
  final String path=authorityUrl.getPath().substring(1);
  if (StringHelper.isBlank(path)) {
    throw new IllegalArgumentException(AuthenticationErrorMessage.AUTHORITY_URI_INVALID_PATH);
  }
  final String firstPath=path.substring(0,path.indexOf("String_Node_Str"));
  final AuthorityType authorityType=IsAdfsAuthority(firstPath) ? AuthorityType.ADFS : AuthorityType.AAD;
  return authorityType;
}

Fixed version (ground truth):
AuthorityType detectAuthorityType(){
  if (authorityUrl == null) {
    throw new NullPointerException("String_Node_Str");
  }
  final String path=authorityUrl.getPath().substring(1);
  if (StringHelper.isBlank(path)) {
    throw new IllegalArgumentException(AuthenticationErrorMessage.AUTHORITY_URI_INVALID_PATH);
  }
  final String firstPath=path.substring(0,path.indexOf("String_Node_Str"));
  final AuthorityType authorityType=isAdfsAuthority(firstPath) ? AuthorityType.ADFS : AuthorityType.AAD;
  return authorityType;
}
Program: 21170
Project: 21170
Buggy source:
boolean doDynamicInstanceDiscovery(final Map<String,String> headers) throws Exception {
  final String json=HttpHelper.executeHttpGet(log,instanceDiscoveryEndpoint,headers);
  final InstanceDiscoveryResponse discoveryResponse=JsonHelper.convertJsonToObject(json,InstanceDiscoveryResponse.class);
  return !StringHelper.isBlank(discoveryResponse.getTenantDiscoveryEndpoint());
}

Fixed version (ground truth):
boolean doDynamicInstanceDiscovery(final Map<String,String> headers) throws Exception {
  final String json=HttpHelper.executeHttpGet(log,instanceDiscoveryEndpoint,headers,proxy);
  final InstanceDiscoveryResponse discoveryResponse=JsonHelper.convertJsonToObject(json,InstanceDiscoveryResponse.class);
  return !StringHelper.isBlank(discoveryResponse.getTenantDiscoveryEndpoint());
}
Program: 21171
Project: 21171
Buggy source:
AuthenticationAuthority(final URL authorityUrl,final boolean validateAuthority){
  this.authorityUrl=authorityUrl;
  this.authorityType=detectAuthorityType();
  this.validateAuthority=validateAuthority;
  validateAuthorityUrl();
  setupAuthorityProperties();
}

Fixed version (ground truth):
AuthenticationAuthority(final URL authorityUrl,final boolean validateAuthority,final Proxy proxy){
  this.authorityUrl=authorityUrl;
  this.authorityType=detectAuthorityType();
  this.validateAuthority=validateAuthority;
  this.proxy=proxy;
  validateAuthorityUrl();
  setupAuthorityProperties();
}
Program: 21172
Project: 21172
Buggy source:
static BindingPolicy getWsTrustEndpointFromMexEndpoint(String metadataEndpoint) throws Exception {
  String mexResponse=HttpHelper.executeHttpGet(log,metadataEndpoint);
  return getWsTrustEndpointFromMexResponse(mexResponse);
}

Fixed version (ground truth):
static BindingPolicy getWsTrustEndpointFromMexEndpoint(String metadataEndpoint,Proxy proxy) throws Exception {
  String mexResponse=HttpHelper.executeHttpGet(log,metadataEndpoint,proxy);
  return getWsTrustEndpointFromMexResponse(mexResponse);
}
Program: 21175
Project: 21175
Buggy source:
/** 
 * Replace an string like: <ul> <li>replaceEmptyLines("bla\n\nbla", "123")   =>   "bla\n123\nbla"</li> <li>replaceEmptyLines("bla\r\n\r\nbla", "123")   =>   "bla\r\n123\r\nbla"</li> </ul>
 * @param source        source String
 * @param replaceString replace String without double new line
 * @return
 */
protected static String replaceEmptyLines(String source,String replaceString){
  if (source != null) {
    for (    String newlineChars : Arrays.asList("String_Node_Str","String_Node_Str")) {
      String doubleNewLine=newlineChars + newlineChars;
      if (replaceString.contains(doubleNewLine) || StringUtils.isEmpty(replaceString)) {
        throw new InvalidParameterException("String_Node_Str" + doubleNewLine + "String_Node_Str");
      }
      while (source.contains(doubleNewLine)) {
        source=source.replace(doubleNewLine,newlineChars + replaceString + newlineChars);
      }
    }
  }
  return source;
}

Fixed version (ground truth):
/** 
 * Replace an string like: <ul> <li>replaceEmptyLines("bla\n\nbla", "123")   =   "bla\n123\nbla"</li> <li>replaceEmptyLines("bla\r\n\r\nbla", "123")   =   "bla\r\n123\r\nbla"</li> </ul>
 * @param source        source String
 * @param replaceString replace String without double new line
 * @return
 */
protected static String replaceEmptyLines(String source,String replaceString){
  if (source != null) {
    for (    String newlineChars : Arrays.asList("String_Node_Str","String_Node_Str")) {
      String doubleNewLine=newlineChars + newlineChars;
      if (replaceString.contains(doubleNewLine) || StringUtils.isEmpty(replaceString)) {
        throw new InvalidParameterException("String_Node_Str" + doubleNewLine + "String_Node_Str");
      }
      while (source.contains(doubleNewLine)) {
        source=source.replace(doubleNewLine,newlineChars + replaceString + newlineChars);
      }
    }
  }
  return source;
}
Program: 21180
Project: 21180
Buggy source:
private boolean checkForDuplicate(Bookmark userData){
  boolean dup=false;
  if (this.userResPairs.contains(userData.getUserID() + "String_Node_Str" + userData.getWikiID())) {
    dup=true;
  }
  this.userResPairs.add(userData.getUserID() + "String_Node_Str" + userData.getWikiID());
  return dup;
}

Fixed version (ground truth):
private boolean checkForDuplicate(Bookmark userData){
  boolean dup=false;
  if (this.userResPairs.contains(userData.getUserID() + "String_Node_Str" + userData.getResourceID())) {
    dup=true;
  }
  this.userResPairs.add(userData.getUserID() + "String_Node_Str" + userData.getResourceID());
  return dup;
}
Program: 21181
Project: 21181
Buggy source:
public Map<Integer,List<Integer>> getResourcesOfTestUsers(int trainSize){
  Map<Integer,List<Integer>> resourcesMap=new HashMap<Integer,List<Integer>>();
  if (trainSize == -1) {
    trainSize=0;
  }
  for (int i=trainSize; i < getBookmarks().size(); i++) {
    Bookmark data=getBookmarks().get(i);
    int userID=data.getUserID();
    List<Integer> resources=resourcesMap.get(userID);
    if (resources == null) {
      resources=new ArrayList<Integer>();
    }
    resources.add(data.getWikiID());
    resourcesMap.put(userID,resources);
  }
  return resourcesMap;
}

Fixed version (ground truth):
public Map<Integer,List<Integer>> getResourcesOfTestUsers(int trainSize){
  Map<Integer,List<Integer>> resourcesMap=new HashMap<Integer,List<Integer>>();
  if (trainSize == -1) {
    trainSize=0;
  }
  for (int i=trainSize; i < getBookmarks().size(); i++) {
    Bookmark data=getBookmarks().get(i);
    int userID=data.getUserID();
    List<Integer> resources=resourcesMap.get(userID);
    if (resources == null) {
      resources=new ArrayList<Integer>();
    }
    resources.add(data.getResourceID());
    resourcesMap.put(userID,resources);
  }
  return resourcesMap;
}
Program: 21182
Project: 21182
Buggy source:
public boolean writeFile(String filename){
  try {
    FileWriter writer=new FileWriter(new File("String_Node_Str" + filename + "String_Node_Str"));
    BufferedWriter bw=new BufferedWriter(writer);
    for (int i=0; i < this.results.size(); i++) {
      int j=0;
      String resultString="String_Node_Str";
      int[] userResults=this.results.get(i);
      Bookmark userData=this.reader.getTestLines().get(i);
      List<Integer> userCats=userData.getTags();
      resultString+=(userData.getUserID() + (userData.getWikiID() == -1 ? "String_Node_Str" : "String_Node_Str" + userData.getWikiID()) + "String_Node_Str");
      for (      int c : userCats) {
        resultString+=(c + "String_Node_Str");
      }
      if (userCats.size() > 0) {
        resultString=resultString.substring(0,resultString.length() - 2);
      }
      resultString+="String_Node_Str";
      j=0;
      for (      int c : userResults) {
        if (j++ < OUTPUT_LIMIT) {
          resultString+=(c + "String_Node_Str");
        }
 else {
          break;
        }
      }
      if (userResults.length > 0) {
        resultString=resultString.substring(0,resultString.length() - 2);
      }
      resultString+="String_Node_Str";
      bw.write(resultString);
    }
    bw.flush();
    bw.close();
    return true;
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return false;
}

Fixed version (ground truth):
public boolean writeFile(String filename){
  try {
    FileWriter writer=new FileWriter(new File("String_Node_Str" + filename + "String_Node_Str"));
    BufferedWriter bw=new BufferedWriter(writer);
    for (int i=0; i < this.results.size(); i++) {
      int j=0;
      String resultString="String_Node_Str";
      int[] userResults=this.results.get(i);
      Bookmark userData=this.reader.getTestLines().get(i);
      List<Integer> userCats=userData.getTags();
      resultString+=(userData.getUserID() + (userData.getResourceID() == -1 ? "String_Node_Str" : "String_Node_Str" + userData.getResourceID()) + "String_Node_Str");
      for (      int c : userCats) {
        resultString+=(c + "String_Node_Str");
      }
      if (userCats.size() > 0) {
        resultString=resultString.substring(0,resultString.length() - 2);
      }
      resultString+="String_Node_Str";
      j=0;
      for (      int c : userResults) {
        if (j++ < OUTPUT_LIMIT) {
          resultString+=(c + "String_Node_Str");
        }
 else {
          break;
        }
      }
      if (userResults.length > 0) {
        resultString=resultString.substring(0,resultString.length() - 2);
      }
      resultString+="String_Node_Str";
      bw.write(resultString);
    }
    bw.flush();
    bw.close();
    return true;
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return false;
}