nus-yam/ex-repair huggingface dataset:
Program: 5041
Project: 5041
Buggy source:
/** 
 * The default handler for QueryRequests received in ManagedConnection.loopForMessages().  This implementation updates stats, does the broadcast, and generates a response. You can customize behavior in three ways: 1. Override. You can assume that duplicate messages (messages with the same GUID that arrived via different paths) have already been filtered.  If you want stats updated, you'll have to call super.handleQueryRequest. 2. Override broadcastQueryRequest.  This allows you to use the default handling framework and just customize request routing. 3. Implement respondToQueryRequest.  This allows you to use the default handling framework and just customize responses.
 */
public void handleQueryRequest(QueryRequest queryRequest,ManagedConnection receivingConnection){
  _numQueryRequests++;
  if ((receivingConnection.getNumMessagesReceived() <= 2) && (queryRequest.getHops() <= 1) && (queryRequest.getQuery().equals("String_Node_Str"))) {
    receivingConnection.setKillable(false);
  }
  if (queryRequest.getTTL() > 0)   broadcastQueryRequest(queryRequest,receivingConnection,_manager);
  respondToQueryRequest(queryRequest,_acceptor,_clientGUID);
}

Fixed version (ground truth):
/** 
 * The default handler for QueryRequests received in ManagedConnection.loopForMessages().  This implementation updates stats, does the broadcast, and generates a response. You can customize behavior in three ways: 1. Override. You can assume that duplicate messages (messages with the same GUID that arrived via different paths) have already been filtered.  If you want stats updated, you'll have to call super.handleQueryRequest. 2. Override broadcastQueryRequest.  This allows you to use the default handling framework and just customize request routing. 3. Implement respondToQueryRequest.  This allows you to use the default handling framework and just customize responses.
 */
public void handleQueryRequest(QueryRequest queryRequest,ManagedConnection receivingConnection){
  _numQueryRequests++;
  if ((receivingConnection.getNumMessagesReceived() <= 2) && (queryRequest.getHops() <= 1) && (queryRequest.getQuery().equals(FileManager.INDEXING_QUERY))) {
    receivingConnection.setKillable(false);
  }
  if (queryRequest.getTTL() > 0)   broadcastQueryRequest(queryRequest,receivingConnection,_manager);
  respondToQueryRequest(queryRequest,_acceptor,_clientGUID);
}
Program: 5042
Project: 5042
Buggy source:
/** 
 * Removes and returns the RemoteFileDesc with the smallest estimated remaining download time in filesLeft.  
 * @requires !filesLeft.isEmpty()
 * @modifies filesLeft
 */
public RemoteFileDesc removeBest(List filesLeft){
  RemoteFileDesc ret=null;
  long lowestTime=Integer.MAX_VALUE;
  for (Iterator iter=filesLeft.iterator(); iter.hasNext(); ) {
    RemoteFileDesc rfd=(RemoteFileDesc)iter.next();
    File incompleteFile=incompleteFileManager.getFile(rfd);
    long amountLeft=rfd.getSize() - incompleteFile.length();
    long speed=rfd.getSpeed() / 8;
    long estimatedTime=amountLeft / speed;
    if (estimatedTime < lowestTime) {
      lowestTime=estimatedTime;
      ret=rfd;
    }
  }
  Assert.that(ret != null,"String_Node_Str");
  filesLeft.remove(ret);
  return ret;
}

Fixed version (ground truth):
/** 
 * Removes and returns the RemoteFileDesc with the smallest estimated remaining download time in filesLeft.  
 * @requires !filesLeft.isEmpty()
 * @modifies filesLeft
 */
public RemoteFileDesc removeBest(List filesLeft){
  RemoteFileDesc ret=null;
  long lowestTime=Integer.MAX_VALUE;
  for (Iterator iter=filesLeft.iterator(); iter.hasNext(); ) {
    RemoteFileDesc rfd=(RemoteFileDesc)iter.next();
    File incompleteFile=incompleteFileManager.getFile(rfd);
    long amountLeft=rfd.getSize() - incompleteFile.length();
    long speed=rfd.getSpeed() / 8;
    long estimatedTime=999999999;
    if (speed != 0)     estimatedTime=amountLeft / speed;
    if (estimatedTime < lowestTime) {
      lowestTime=estimatedTime;
      ret=rfd;
    }
  }
  Assert.that(ret != null,"String_Node_Str");
  filesLeft.remove(ret);
  return ret;
}
Program: 5043
Project: 5043
Buggy source:
/** 
 * Create an incoming connection.  This method starts the message loop, so it will block for a long time.  Make sure the thread that calls this method is suitable doing a connection message loop. If there are already too many connections in the manager, this method will launch a RejectConnection to send pongs for other hosts.
 */
void acceptConnection(Socket socket){
  if (getNumInConnections() < getNumConnections()) {
    ManagedConnection connection=new ManagedConnection(socket,_router,this);
    try {
      initializeExternallyGeneratedConnection(connection);
      _router.sendPingRequest(new PingRequest(_settings.getTTL()),connection);
      connection.loopForMessages();
    }
 catch (    IOException e) {
    }
catch (    Exception e) {
      _callback.error(ActivityCallback.ERROR_20,e);
    }
  }
 else {
    if (Utilities.isWindows()) {
      new RejectConnection(socket,_catcher);
    }
 else {
      try {
        socket.close();
      }
 catch (      IOException ioe) {
      }
    }
  }
}

Fixed version (ground truth):
/** 
 * Create an incoming connection.  This method starts the message loop, so it will block for a long time.  Make sure the thread that calls this method is suitable doing a connection message loop. If there are already too many connections in the manager, this method will launch a RejectConnection to send pongs for other hosts.
 */
void acceptConnection(Socket socket){
  boolean allowConnection=false;
synchronized (_incomingConnectionsLock) {
    if (_incomingConnections < _keepAlive) {
      _incomingConnections++;
      allowConnection=true;
    }
  }
  if (allowConnection) {
    ManagedConnection connection=new ManagedConnection(socket,_router,this);
    try {
      initializeExternallyGeneratedConnection(connection);
      _router.sendPingRequest(new PingRequest(_settings.getTTL()),connection);
      connection.loopForMessages();
    }
 catch (    IOException e) {
    }
catch (    Exception e) {
      _callback.error(ActivityCallback.ERROR_20,e);
    }
 finally {
synchronized (_incomingConnectionsLock) {
        _incomingConnections--;
      }
    }
  }
 else {
    if (Utilities.isWindows()) {
      new RejectConnection(socket,_catcher);
    }
 else {
      try {
        socket.close();
      }
 catch (      IOException ioe) {
      }
    }
  }
}
Program: 5045
Project: 5045
Buggy source:
private VersionUpdate(){
  _settings=SettingsManager.instance();
  _latest=_settings.getLastVersionChecked();
  _timedOut=false;
}

Fixed version (ground truth):
private VersionUpdate(){
  _settings=SettingsManager.instance();
  _latest=_settings.getLastVersionChecked();
}
Program: 5048
Project: 5048
Buggy source:
/** 
 * Removes downloader entirely from the list of current downloads. Notifies callback of the change in status.
 * @requires downloader active or queued
 * @modifies this, callback
 */
public synchronized void remove(ManagedDownloader downloader,boolean success){
  boolean activated=active.remove(downloader);
  if (!activated)   waiting.remove(downloader);
 else   notify();
  callback.removeDownload(downloader);
}

Fixed version (ground truth):
/** 
 * Removes downloader entirely from the list of current downloads. Notifies callback of the change in status.
 * @modifies this, callback
 */
public synchronized void remove(ManagedDownloader downloader,boolean success){
  active.remove(downloader);
  waiting.remove(downloader);
  notify();
  callback.removeDownload(downloader);
}
Program: 5049
Project: 5049
Buggy source:
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 * @exception CantConnectException couldn't connect to the host.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    SettingsManager sm=SettingsManager.instance();
    String incompleteDir;
    incompleteDir=sm.getIncompleteDirectory();
    if (incompleteDir == "String_Node_Str")     throw new NullIncompleteDirectoryException();
    File incompleteFile=new File(incompleteDir,_filename);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
      _amountRead=_initialReadingPoint;
    }
  }
  connect(host,port,file,index,timeout);
}

Fixed version (ground truth):
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 * @exception CantConnectException couldn't connect to the host.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    File incompleteFile=new TemporaryFile(_filename,guid);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
      _amountRead=_initialReadingPoint;
    }
  }
  connect(host,port,file,index,timeout);
}
Program: 5050
Project: 5050
Buggy source:
private void doDownload() throws IOException {
  SettingsManager settings=SettingsManager.instance();
  String download_dir=settings.getSaveDirectory();
  String incomplete_dir=settings.getIncompleteDirectory();
  File incomplete_file=new File(incomplete_dir,_filename);
  String path_to_incomplete=incomplete_file.getAbsolutePath();
  File complete_file=new File(download_dir,_filename);
  String path_to_complete=complete_file.getAbsolutePath();
  File shared=new File(download_dir);
  String shared_path=shared.getCanonicalPath();
  File parent_of_shared=new File(complete_file.getParent());
  String path_to_parent=parent_of_shared.getCanonicalPath();
  if (!path_to_parent.equals(shared_path)) {
    throw new InvalidPathException();
  }
  if (complete_file.exists()) {
    try {
      complete_file.delete();
    }
 catch (    SecurityException e) {
      throw new IOException("String_Node_Str");
    }
  }
  boolean append=false;
  if (_initialReadingPoint > 0)   append=true;
  _fos=new FileOutputStream(path_to_incomplete,append);
  int c=-1;
  byte[] buf=new byte[1024];
  while (true) {
    if (_amountRead == _fileSize)     break;
    if (_amountRead > _fileSize)     throw new FileTooLargeException();
    c=_byteReader.read(buf);
    if (c == -1)     break;
    _fos.write(buf,0,c);
    _amountRead+=c;
  }
  _byteReader.close();
  _fos.close();
  if (_amountRead == _fileSize) {
    complete_file.delete();
    boolean ok=incomplete_file.renameTo(complete_file);
    if (!ok)     throw new FileCantBeMovedException();
    FileManager.instance().addFileIfShared(path_to_complete);
  }
 else   throw new FileIncompleteException();
}

Fixed version (ground truth):
private void doDownload() throws IOException {
  SettingsManager settings=SettingsManager.instance();
  String download_dir=settings.getSaveDirectory();
  File complete_file=new File(download_dir,_filename);
  String path_to_complete=complete_file.getAbsolutePath();
  File shared=new File(download_dir);
  String shared_path=shared.getCanonicalPath();
  File parent_of_shared=new File(complete_file.getParent());
  String path_to_parent=parent_of_shared.getCanonicalPath();
  if (!path_to_parent.equals(shared_path)) {
    throw new InvalidPathException();
  }
  File incomplete_file=new TemporaryFile(_filename,_guid);
  String path_to_incomplete=incomplete_file.getAbsolutePath();
  boolean append=false;
  if (_initialReadingPoint > 0)   append=true;
  _fos=new FileOutputStream(path_to_incomplete,append);
  int c=-1;
  byte[] buf=new byte[1024];
  while (true) {
    if (_amountRead == _fileSize)     break;
    if (_amountRead > _fileSize)     throw new FileTooLargeException();
    c=_byteReader.read(buf);
    if (c == -1)     break;
    _fos.write(buf,0,c);
    _amountRead+=c;
  }
  _byteReader.close();
  _fos.close();
  if (_amountRead == _fileSize) {
    complete_file.delete();
    boolean ok=incomplete_file.renameTo(complete_file);
    if (!ok)     throw new FileCantBeMovedException();
    FileManager.instance().addFileIfShared(path_to_complete);
  }
 else   throw new FileIncompleteException();
}
Program: 5051
Project: 5051
Buggy source:
/** 
 * Tries to "smart download" any of the given files.<p>   If overwrite==false, then if any of the files already exists in the download directory, FileExistsException is thrown and no files are modified.  If overwrite==true, the files may be overwritten.<p> Otherwise returns a Downloader that allows you to stop and resume this download.  The ActivityCallback will also be notified of this download, so the return value can usually be ignored.  The download begins immediately, unless it is queued.  It stops after any of the files succeeds.
 * @modifies this, disk 
 */
public Downloader download(RemoteFileDesc[] files,boolean overwrite) throws com.limegroup.gnutella.downloader.FileExistsException {
  return downloader.getFiles(files,overwrite);
}

Fixed version (ground truth):
/** 
 * Tries to "smart download" any of the given files.<p>   If overwrite==false, then if any of the files already exists in the download directory, FileExistsException is thrown and no files are modified.  If overwrite==true, the files may be overwritten.<p> Otherwise returns a Downloader that allows you to stop and resume this download.  The ActivityCallback will also be notified of this download, so the return value can usually be ignored.  The download begins immediately, unless it is queued.  It stops after any of the files succeeds.
 * @modifies this, disk 
 */
public Downloader download(RemoteFileDesc[] files,boolean overwrite) throws FileExistsException, AlreadyDownloadingException {
  return downloader.getFiles(files,overwrite);
}
Program: 5052
Project: 5052
Buggy source:
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 * @exception CantConnectException couldn't connect to the host.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    SettingsManager sm=SettingsManager.instance();
    String incompleteDir;
    incompleteDir=sm.getIncompleteDirectory();
    if (incompleteDir == "String_Node_Str")     throw new NullIncompleteDirectoryException();
    File incompleteFile=new File(incompleteDir,_filename);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
      _amountRead=_initialReadingPoint;
    }
  }
  connect(host,port,file,index,timeout);
}

Fixed version (ground truth):
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 * @exception CantConnectException couldn't connect to the host.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    File incompleteFile=new TemporaryFile(_filename,guid);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
      _amountRead=_initialReadingPoint;
    }
  }
  connect(host,port,file,index,timeout);
}
Program: 5053
Project: 5053
Buggy source:
private void doDownload() throws IOException {
  SettingsManager settings=SettingsManager.instance();
  String download_dir=settings.getSaveDirectory();
  String incomplete_dir=settings.getIncompleteDirectory();
  File incomplete_file=new File(incomplete_dir,_filename);
  String path_to_incomplete=incomplete_file.getAbsolutePath();
  File complete_file=new File(download_dir,_filename);
  String path_to_complete=complete_file.getAbsolutePath();
  File shared=new File(download_dir);
  String shared_path=shared.getCanonicalPath();
  File parent_of_shared=new File(complete_file.getParent());
  String path_to_parent=parent_of_shared.getCanonicalPath();
  if (!path_to_parent.equals(shared_path)) {
    throw new InvalidPathException();
  }
  if (complete_file.exists()) {
    try {
      complete_file.delete();
    }
 catch (    SecurityException e) {
      throw new IOException("String_Node_Str");
    }
  }
  boolean append=false;
  if (_initialReadingPoint > 0)   append=true;
  _fos=new FileOutputStream(path_to_incomplete,append);
  int c=-1;
  byte[] buf=new byte[1024];
  while (true) {
    if (_amountRead == _fileSize)     break;
    if (_amountRead > _fileSize)     throw new FileTooLargeException();
    c=_byteReader.read(buf);
    if (c == -1)     break;
    _fos.write(buf,0,c);
    _amountRead+=c;
  }
  _byteReader.close();
  _fos.close();
  if (_amountRead == _fileSize) {
    complete_file.delete();
    boolean ok=incomplete_file.renameTo(complete_file);
    if (!ok)     throw new FileCantBeMovedException();
    FileManager.instance().addFileIfShared(path_to_complete);
  }
 else   throw new FileIncompleteException();
}

Fixed version (ground truth):
private void doDownload() throws IOException {
  SettingsManager settings=SettingsManager.instance();
  String download_dir=settings.getSaveDirectory();
  File complete_file=new File(download_dir,_filename);
  String path_to_complete=complete_file.getAbsolutePath();
  File shared=new File(download_dir);
  String shared_path=shared.getCanonicalPath();
  File parent_of_shared=new File(complete_file.getParent());
  String path_to_parent=parent_of_shared.getCanonicalPath();
  if (!path_to_parent.equals(shared_path)) {
    throw new InvalidPathException();
  }
  File incomplete_file=new TemporaryFile(_filename,_guid);
  String path_to_incomplete=incomplete_file.getAbsolutePath();
  boolean append=false;
  if (_initialReadingPoint > 0)   append=true;
  _fos=new FileOutputStream(path_to_incomplete,append);
  int c=-1;
  byte[] buf=new byte[1024];
  while (true) {
    if (_amountRead == _fileSize)     break;
    if (_amountRead > _fileSize)     throw new FileTooLargeException();
    c=_byteReader.read(buf);
    if (c == -1)     break;
    _fos.write(buf,0,c);
    _amountRead+=c;
  }
  _byteReader.close();
  _fos.close();
  if (_amountRead == _fileSize) {
    complete_file.delete();
    boolean ok=incomplete_file.renameTo(complete_file);
    if (!ok)     throw new FileCantBeMovedException();
    FileManager.instance().addFileIfShared(path_to_complete);
  }
 else   throw new FileIncompleteException();
}
Program: 5054
Project: 5054
Buggy source:
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    SettingsManager sm=SettingsManager.instance();
    String incompleteDir;
    incompleteDir=sm.getIncompleteDirectory();
    if (incompleteDir == "String_Node_Str")     throw new NullIncompleteDirectoryException();
    String incompletePath;
    incompletePath=incompleteDir + _filename;
    File incompleteFile=new File(incompletePath);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
    }
  }
  connect(host,port,file,index,timeout);
}

Fixed version (ground truth):
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 * @exception CantConnectException couldn't connect to the host.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    SettingsManager sm=SettingsManager.instance();
    String incompleteDir;
    incompleteDir=sm.getIncompleteDirectory();
    if (incompleteDir == "String_Node_Str")     throw new NullIncompleteDirectoryException();
    File incompleteFile=new File(incompleteDir,_filename);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
      _amountRead=_initialReadingPoint;
    }
  }
  connect(host,port,file,index,timeout);
}
Program: 5055
Project: 5055
Buggy source:
/** 
 * Start the download.  Throws IOException if the headers couldn't be read, there remote host has no more download slots, or the download was interrupted.  (In the future different exceptions will be thrown for each of these cases.
 * @modifies this
 */
public void start() throws IOException {
  readHeader();
  doDownload();
}

Fixed version (ground truth):
/** 
 * Start the download, returning when done.  Throws IOException if there is a problem.
 * @modifies this
 * @exception TryAgainLaterException the host is busy
 * @exception NotSharingException the host isn't sharing files
 * @exception FileIncompleteException transfer interrupted, eitherlocally or remotely
 */
public void start() throws IOException {
  readHeader();
  doDownload();
}
Program: 5056
Project: 5056
Buggy source:
private void connect(Socket s,String file,int index) throws IOException {
  _socket=s;
  try {
    InputStream istream=null;
    try {
      istream=_socket.getInputStream();
    }
 catch (    Exception e) {
      throw new IOException();
    }
    _byteReader=new ByteReader(istream);
    OutputStream os=_socket.getOutputStream();
    OutputStreamWriter osw=new OutputStreamWriter(os);
    BufferedWriter out=new BufferedWriter(osw);
    String startRange=java.lang.String.valueOf(_initialReadingPoint);
    out.write("String_Node_Str" + index + "String_Node_Str"+ file+ "String_Node_Str");
    out.write("String_Node_Str");
    out.write("String_Node_Str" + startRange + "String_Node_Str");
    out.write("String_Node_Str");
    out.flush();
  }
 catch (  ConnectException e) {
    throw new CantConnectException();
  }
catch (  java.net.MalformedURLException e) {
    throw new BadURLException();
  }
}

Fixed version (ground truth):
private void connect(Socket s,String file,int index) throws IOException {
  _socket=s;
  InputStream istream=null;
  try {
    istream=_socket.getInputStream();
  }
 catch (  Exception e) {
    throw new IOException();
  }
  _byteReader=new ByteReader(istream);
  OutputStream os=_socket.getOutputStream();
  OutputStreamWriter osw=new OutputStreamWriter(os);
  BufferedWriter out=new BufferedWriter(osw);
  String startRange=java.lang.String.valueOf(_initialReadingPoint);
  out.write("String_Node_Str" + index + "String_Node_Str"+ file+ "String_Node_Str");
  out.write("String_Node_Str");
  out.write("String_Node_Str" + startRange + "String_Node_Str");
  out.write("String_Node_Str");
  out.flush();
}
Program: 5057
Project: 5057
Buggy source:
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    SettingsManager sm=SettingsManager.instance();
    String incompleteDir;
    incompleteDir=sm.getIncompleteDirectory();
    if (incompleteDir == "String_Node_Str")     throw new NullIncompleteDirectoryException();
    String incompletePath;
    incompletePath=incompleteDir + _filename;
    File incompleteFile=new File(incompletePath);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
    }
  }
  connect(host,port,file,index,timeout);
}

Fixed version (ground truth):
/** 
 * @param timeout the amount of time, in milliseconds, to waitwhen establishing a connection.   Must be non-negative.  A timeout of 0 means no timeout.
 * @exception CantConnectException couldn't connect to the host.
 */
public HTTPDownloader(String file,String host,int port,int index,byte[] guid,int size,boolean resume,int timeout) throws IOException {
  _filename=file;
  _index=index;
  _guid=guid;
  _amountRead=0;
  _fileSize=size;
  _initialReadingPoint=0;
  if (resume) {
    SettingsManager sm=SettingsManager.instance();
    String incompleteDir;
    incompleteDir=sm.getIncompleteDirectory();
    if (incompleteDir == "String_Node_Str")     throw new NullIncompleteDirectoryException();
    File incompleteFile=new File(incompleteDir,_filename);
    if (incompleteFile.exists()) {
      _initialReadingPoint=(int)incompleteFile.length();
      _amountRead=_initialReadingPoint;
    }
  }
  connect(host,port,file,index,timeout);
}
Program: 5058
Project: 5058
Buggy source:
/** 
 * Start the download.  Throws IOException if the headers couldn't be read, there remote host has no more download slots, or the download was interrupted.  (In the future different exceptions will be thrown for each of these cases.
 * @modifies this
 */
public void start() throws IOException {
  readHeader();
  doDownload();
}

Fixed version (ground truth):
/** 
 * Start the download, returning when done.  Throws IOException if there is a problem.
 * @modifies this
 * @exception TryAgainLaterException the host is busy
 * @exception NotSharingException the host isn't sharing files
 * @exception FileIncompleteException transfer interrupted, eitherlocally or remotely
 */
public void start() throws IOException {
  readHeader();
  doDownload();
}
Program: 5059
Project: 5059
Buggy source:
private void connect(Socket s,String file,int index) throws IOException {
  _socket=s;
  try {
    InputStream istream=null;
    try {
      istream=_socket.getInputStream();
    }
 catch (    Exception e) {
      throw new IOException();
    }
    _byteReader=new ByteReader(istream);
    OutputStream os=_socket.getOutputStream();
    OutputStreamWriter osw=new OutputStreamWriter(os);
    BufferedWriter out=new BufferedWriter(osw);
    String startRange=java.lang.String.valueOf(_initialReadingPoint);
    out.write("String_Node_Str" + index + "String_Node_Str"+ file+ "String_Node_Str");
    out.write("String_Node_Str");
    out.write("String_Node_Str" + startRange + "String_Node_Str");
    out.write("String_Node_Str");
    out.flush();
  }
 catch (  ConnectException e) {
    throw new CantConnectException();
  }
catch (  java.net.MalformedURLException e) {
    throw new BadURLException();
  }
}

Fixed version (ground truth):
private void connect(Socket s,String file,int index) throws IOException {
  _socket=s;
  InputStream istream=null;
  try {
    istream=_socket.getInputStream();
  }
 catch (  Exception e) {
    throw new IOException();
  }
  _byteReader=new ByteReader(istream);
  OutputStream os=_socket.getOutputStream();
  OutputStreamWriter osw=new OutputStreamWriter(os);
  BufferedWriter out=new BufferedWriter(osw);
  String startRange=java.lang.String.valueOf(_initialReadingPoint);
  out.write("String_Node_Str" + index + "String_Node_Str"+ file+ "String_Node_Str");
  out.write("String_Node_Str");
  out.write("String_Node_Str" + startRange + "String_Node_Str");
  out.write("String_Node_Str");
  out.flush();
}
Program: 5060
Project: 5060
Buggy source:
public void run(){
  try {
    boolean success;
    for (int i=0; i < TRIES && !stopped; i++) {
      success=tryNormalDownloads();
      if (success) {
        manager.remove(ManagedDownloader.this,true);
        return;
      }
      if (i < 2)       sendPushes();
      success=waitForPushDownloads();
      if (success) {
        manager.remove(ManagedDownloader.this,true);
        return;
      }
    }
    setState(GAVE_UP);
    manager.remove(ManagedDownloader.this,false);
  }
 catch (  InterruptedException e) {
    return;
  }
 finally {
synchronized (ManagedDownloader.this) {
      stopped=true;
      for (Iterator iter=pushQueue.iterator(); iter.hasNext(); )       ((HTTPDownloader)iter.next()).stop();
    }
  }
}

Fixed version (ground truth):
public void run(){
  try {
    boolean success;
    for (int i=0; i < TRIES && !stopped; i++) {
      success=tryNormalDownloads();
      if (success) {
        manager.remove(ManagedDownloader.this,true);
        return;
      }
      if (i < 2)       sendPushes();
      success=waitForPushDownloads();
      if (success) {
        manager.remove(ManagedDownloader.this,true);
        return;
      }
    }
    setState(GAVE_UP);
    manager.remove(ManagedDownloader.this,false);
  }
 catch (  InterruptedException e) {
    return;
  }
 finally {
synchronized (ManagedDownloader.this) {
      stopped=true;
      for (Iterator iter=pushQueue.iterator(); iter.hasNext(); )       ((HTTPDownloader)iter.next()).stop();
      if (dloader != null)       dloader.stop();
    }
  }
}
Program: 5061
Project: 5061
Buggy source:
/** 
 * Waits at least WAIT_TIME seconds.  If any push downloads come in, handle them, acquiring a download slot first.  Return true if one of these downloads is successful.  Throws InterruptedException if a call to stop() is detected. 
 */
private boolean waitForPushDownloads() throws InterruptedException {
  Date start=new Date();
  while (true) {
synchronized (ManagedDownloader.this) {
      setState(WAITING_FOR_RETRY);
      while (pushQueue.isEmpty()) {
        Date now=new Date();
        long elapsed=now.getTime() - start.getTime();
        long waitTime=WAIT_TIME - elapsed;
        if (waitTime <= 0)         return false;
        ManagedDownloader.this.wait(waitTime);
      }
      dloader=(HTTPDownloader)pushQueue.remove(0);
    }
    try {
      setState(QUEUED);
      manager.waitForSlot(ManagedDownloader.this);
      setState(DOWNLOADING,dloader.getInetAddress().getHostAddress());
      dloader.start();
synchronized (ManagedDownloader.this) {
        if (stopped)         throw new InterruptedException();
        setState(COMPLETE);
      }
      return true;
    }
 catch (    IOException e) {
    }
 finally {
      manager.yieldSlot(ManagedDownloader.this);
    }
  }
}

Fixed version (ground truth):
/** 
 * Waits at least WAIT_TIME seconds.  If any push downloads come in, handle them, acquiring a download slot first.  Return true if one of these downloads is successful.  Throws InterruptedException if a call to stop() is detected. 
 */
private boolean waitForPushDownloads() throws InterruptedException {
  Date start=new Date();
  while (true) {
synchronized (ManagedDownloader.this) {
      setState(WAITING_FOR_RETRY);
      while (pushQueue.isEmpty()) {
        Date now=new Date();
        long elapsed=now.getTime() - start.getTime();
        long waitTime=WAIT_TIME - elapsed;
        if (waitTime <= 0)         return false;
        ManagedDownloader.this.wait(waitTime);
      }
      dloader=(HTTPDownloader)pushQueue.remove(0);
    }
    try {
      setState(QUEUED);
      manager.waitForSlot(ManagedDownloader.this);
      setState(DOWNLOADING,dloader.getInetAddress().getHostAddress());
      dloader.start();
      setState(COMPLETE);
      return true;
    }
 catch (    IOException e) {
synchronized (ManagedDownloader.this) {
        if (stopped)         throw new InterruptedException();
      }
    }
 finally {
      manager.yieldSlot(ManagedDownloader.this);
    }
  }
}
Program: 5062
Project: 5062
Buggy source:
/** 
 * Called only from initialize()
 * @requires _socket is properly set up
 */
private void sendString(String s) throws IOException {
  byte[] bytes=s.getBytes();
  OutputStream out=_socket.getOutputStream();
  out.write(bytes);
  out.flush();
}

Fixed version (ground truth):
/** 
 * Called only from initialize()
 * @requires _socket, _out are properly set up
 */
private void sendString(String s) throws IOException {
  byte[] bytes=s.getBytes();
  _out.write(bytes);
  _out.flush();
}
Program: 5063
Project: 5063
Buggy source:
public void remove(){
  if (lastYielded == null)   return;
  real.remove();
  FixedsizeForgetfulHashMap.this.remove(lastYielded);
}

Fixed version (ground truth):
/** 
 * Same as Iterator.remove().  That means that calling remove() multiple times may have undefined results! 
 */
public void remove(){
  if (lastYielded == null)   return;
  ValueElement ve=(ValueElement)map.get(lastYielded);
  if (ve != null) {
    currentSize--;
    removeList.remove(ve.getListElement());
  }
  real.remove();
}
Program: 5065
Project: 5065
Buggy source:
/** 
 * Receives a message with timeout.  This method is NOT thread-safe. Behavior is undefined if two threads are in a receive call at the same time for a given connection.
 * @requires this is fully initialized
 * @effects exactly like Message.read(), but throws InterruptedIOExceptionif timeout!=0 and no message is read after "timeout" milliseconds.  In this case, you should terminate the connection, as half a message may have been read.
 */
public Message receive(int timeout) throws IOException, BadPacketException, InterruptedIOException {
  int oldTimeout=_socket.getSoTimeout();
  _socket.setSoTimeout(timeout);
  try {
    Message m=Message.read(_in);
    if (m == null)     throw new InterruptedIOException();
    return m;
  }
  finally {
    _socket.setSoTimeout(oldTimeout);
  }
}

Fixed version (ground truth):
/** 
 * Receives a message with timeout.  This method is NOT thread-safe. Behavior is undefined if two threads are in a receive call at the same time for a given connection.
 * @requires this is fully initialized
 * @effects exactly like Message.read(), but throws InterruptedIOExceptionif timeout!=0 and no message is read after "timeout" milliseconds.  In this case, you should terminate the connection, as half a message may have been read.
 */
public Message receive(int timeout) throws IOException, BadPacketException, InterruptedIOException {
  if (_closed)   throw new IOException();
  int oldTimeout=_socket.getSoTimeout();
  _socket.setSoTimeout(timeout);
  try {
    Message m=Message.read(_in);
    if (m == null)     throw new InterruptedIOException();
    return m;
  }
  finally {
    _socket.setSoTimeout(oldTimeout);
  }
}
Program: 5066
Project: 5066
Buggy source:
/** 
 * @modifies this.responses
 * @effects extracts response from payload and stores in responses. 
 */
private void parseResults() throws BadPacketException {
  int i=11;
  int left=getResultCount();
  responses=new Response[left];
  try {
    for (; left > 0; left--) {
      long index=ByteOrder.ubytes2long(ByteOrder.leb2int(payload,i));
      long size=ByteOrder.ubytes2long(ByteOrder.leb2int(payload,i + 4));
      i+=8;
      int j=i;
      for (; ; j++) {
        if (payload[j] == (byte)0)         break;
      }
      String name=new String(payload,i,j - i);
      responses[responses.length - left]=new Response(index,size,name);
      for (j=j + 1; ; j++) {
        if (payload[j] == (byte)0)         break;
      }
      i=j + 1;
    }
    if (i < payload.length - 16)     throw new BadPacketException("String_Node_Str" + "String_Node_Str");
 else     if (i > payload.length - 16)     throw new BadPacketException("String_Node_Str" + "String_Node_Str");
  }
 catch (  ArrayIndexOutOfBoundsException e) {
    throw new BadPacketException();
  }
}

Fixed version (ground truth):
/** 
 * @modifies this.responses
 * @effects extracts response from payload and stores in responses. 
 */
private void parseResults() throws BadPacketException {
  int i=11;
  int left=getResultCount();
  responses=new Response[left];
  try {
    for (; left > 0; left--) {
      long index=ByteOrder.ubytes2long(ByteOrder.leb2int(payload,i));
      long size=ByteOrder.ubytes2long(ByteOrder.leb2int(payload,i + 4));
      i+=8;
      int j=i;
      for (; ; j++) {
        if (payload[j] == (byte)0)         break;
      }
      String name=new String(payload,i,j - i);
      responses[responses.length - left]=new Response(index,size,name);
      for (j=j + 1; ; j++) {
        if (payload[j] == (byte)0)         break;
      }
      i=j + 1;
    }
    if (i > payload.length - 16)     throw new BadPacketException("String_Node_Str" + "String_Node_Str");
  }
 catch (  ArrayIndexOutOfBoundsException e) {
    throw new BadPacketException();
  }
}
Program: 5067
Project: 5067
Buggy source:
public void setForcedIPAddress(String address){
  if (address == null)   throw new IllegalArgumentException();
  forcedIPAdress_=address;
  props_.put(SettingsInterface.FORCED_IP_ADDRESS,address);
  writeProperties();
}

Fixed version (ground truth):
public void setForcedIPAddress(String address){
  if (address == null)   throw new IllegalArgumentException();
  forcedIPAdress_=address;
  props_.put(SettingsInterface.FORCED_IP_ADDRESS,address);
}
Program: 5068
Project: 5068
Buggy source:
public void setForcedPort(){
}

Fixed version (ground truth):
public void setForcedPort(int port){
  forcedPort_=port;
  String s=Integer.toString(forcedPort_);
  props_.put(SettingsInterface.FORCED_PORT,s);
}
Program: 5069
Project: 5069
Buggy source:
public void setLastVersionChecked(String last){
  lastVersionChecked_=last;
  props_.put(SettingsInterface.LAST_VERSION_CHECKED,last);
  writeProperties();
}

Fixed version (ground truth):
/** 
 * private methods to handle versioning  control information
 */
public void setLastVersionChecked(String last){
  lastVersionChecked_=last;
  props_.put(SettingsInterface.LAST_VERSION_CHECKED,last);
  writeProperties();
}
Program: 5070
Project: 5070
Buggy source:
public void setForceIPAddress(boolean force){
  String c;
  if (force == true)   c="String_Node_Str";
 else   c="String_Node_Str";
  forceIPAdress_=force;
  props_.put(SettingsInterface.FORCE_IP_ADDRESS,c);
  writeProperties();
}

Fixed version (ground truth):
public void setForceIPAddress(boolean force){
  String c;
  if (force == true)   c="String_Node_Str";
 else   c="String_Node_Str";
  forceIPAdress_=force;
  props_.put(SettingsInterface.FORCE_IP_ADDRESS,c);
}
Program: 5071
Project: 5071
Buggy source:
/** 
 * @modifies this
 * @effects atomically removes and returns the highest priority host inthis.  If no host is available, blocks until one is.  If the calling thread is interrupted during this process, throws InterruptedException.
 */
public Endpoint getAnEndpoint() throws InterruptedException {
  if (settings.getUseQuickConnect() && stale) {
    try {
synchronized (staleWaitersLock) {
        staleWaiters++;
        staleWaitersLock.notify();
      }
synchronized (staleLock) {
        if (stale) {
          staleLock.wait(CONNECT_TIME);
        }
      }
    }
  finally {
synchronized (staleWaitersLock) {
        staleWaiters--;
      }
    }
  }
synchronized (this) {
    while (true) {
      try {
        return getAnEndpointInternal();
      }
 catch (      NoSuchElementException e) {
        wait();
      }
    }
  }
}

Fixed version (ground truth):
/** 
 * @modifies this
 * @effects atomically removes and returns the highest priority host inthis.  If no host is available, blocks until one is.  If the calling thread is interrupted during this process, throws InterruptedException.
 */
public Endpoint getAnEndpoint() throws InterruptedException {
  if (settings.getUseQuickConnect() && stale) {
    try {
synchronized (staleWaitersLock) {
        staleWaiters++;
        staleWaitersLock.notify();
      }
synchronized (staleLock) {
        if (stale) {
          staleLock.wait(CONNECT_TIME);
        }
      }
    }
  finally {
synchronized (staleWaitersLock) {
        staleWaiters--;
      }
    }
  }
  Endpoint endpoint=null;
synchronized (this) {
    while (true) {
      try {
        endpoint=getAnEndpointInternal();
        break;
      }
 catch (      NoSuchElementException e) {
        wait();
      }
    }
  }
  return endpoint;
}
Program: 5073
Project: 5073
Buggy source:
private synchronized void addMessage(Message m){
  messages.add(new TimeAndMessage(System.currentTimeMillis(),m));
  if ((mCount++ % 1000) == 0) {
    dumpMessages();
  }
}

Fixed version (ground truth):
private synchronized void addMessage(Message m){
  if (messages == null)   return;
 else   if (messages.size() < SIZE) {
    if ((messages.size() % 200) == 0) {
      System.out.print("String_Node_Str" + messages.size() + "String_Node_Str");
      System.out.println("String_Node_Str" + (SIZE - messages.size()) + "String_Node_Str");
    }
    messages.addElement(new TimeAndMessage(System.currentTimeMillis(),m));
  }
 else {
    System.out.println("String_Node_Str");
    System.out.print("String_Node_Str");
    dumpMessages();
    messages=null;
    System.out.println("String_Node_Str");
  }
}
Program: 5074
Project: 5074
Buggy source:
private void loopForPingRequest() throws IOException {
  while (true) {
    Message m=null;
    try {
      m=receive(SettingsManager.instance().getTimeout());
      if (m == null)       return;
    }
 catch (    BadPacketException e) {
      return;
    }
    if ((m instanceof PingRequest) && (m.getHops() == 0)) {
      Iterator iter=_hostCatcher.getBestHosts(10);
      while (iter.hasNext()) {
        Endpoint bestEndPoint=(Endpoint)iter.next();
        PingReply pr=new PingReply(m.getGUID(),(byte)1,bestEndPoint.getPort(),bestEndPoint.getHostBytes(),0,0);
        send(pr);
      }
    }
  }
}

Fixed version (ground truth):
private void loopForPingRequest() throws IOException {
  for (int i=0; i < 10; i++) {
    Message m=null;
    try {
      m=receive(SettingsManager.instance().getTimeout());
      if (m == null)       return;
    }
 catch (    BadPacketException e) {
      return;
    }
    if ((m instanceof PingRequest) && (m.getHops() == 0)) {
      Iterator iter=_hostCatcher.getBestHosts(10);
      while (iter.hasNext()) {
        Endpoint bestEndPoint=(Endpoint)iter.next();
        PingReply pr=new PingReply(m.getGUID(),(byte)1,bestEndPoint.getPort(),bestEndPoint.getHostBytes(),0,0);
        send(pr);
      }
      flush();
      return;
    }
  }
}
Program: 5075
Project: 5075
Buggy source:
/** 
 * This sets up the file name for nt to escape special characters. 
 */
private static String checkChars(String str){
  String escapeChars="String_Node_Str";
  char[] chars=str.toCharArray();
  int length=chars.length;
  char[] new_chars=new char[length * 3];
  int index=0;
  for (int i=0; i < length; i++) {
    if (escapeChars.indexOf(chars[i]) != -1) {
      new_chars[index++]='"';
      new_chars[index++]=chars[i];
      new_chars[index++]='"';
    }
 else     new_chars[index++]=chars[i];
  }
  String s=new String(new_chars);
  return s.trim();
}

Fixed version (ground truth):
/** 
 * This sets up the file name for nt to escape special characters. 
 */
private static String checkChars(String str){
  System.out.println("String_Node_Str" + str);
  String escapeChars="String_Node_Str";
  char[] chars=str.toCharArray();
  int length=chars.length;
  char[] new_chars=new char[length * 3];
  int index=0;
  for (int i=0; i < length; i++) {
    if (escapeChars.indexOf(chars[i]) != -1) {
      new_chars[index++]='"';
      new_chars[index++]=chars[i];
      new_chars[index++]='"';
    }
 else     new_chars[index++]=chars[i];
  }
  String s=new String(new_chars);
  return s.trim();
}
Program: 5077
Project: 5077
Buggy source:
public void initThree(){
  _stateString=null;
  SettingsManager set=SettingsManager.instance();
  _downloadDir=set.getSaveDirectory();
  String pathname=_downloadDir + _filename;
  File myFile=new File(pathname);
  if (!myFile.exists()) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  URLConnection conn;
  String furl="String_Node_Str" + String.valueOf(_index) + "String_Node_Str"+ _filename;
  long start=myFile.length();
  String startRange=java.lang.String.valueOf(start);
  try {
    URL url=new URL(_protocol,_host,_port,furl);
    conn=url.openConnection();
    conn.setRequestProperty("String_Node_Str","String_Node_Str" + startRange + "String_Node_Str");
    conn.connect();
    _istream=conn.getInputStream();
    _br=new ByteReader(_istream);
  }
 catch (  Exception e) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  _resume=true;
  _state=CONNECTED;
}

Fixed version (ground truth):
public void initThree(){
  _stateString=null;
  SettingsManager set=SettingsManager.instance();
  _downloadDir=set.getIncompleteDirectory();
  String pathname=_downloadDir + _filename;
  File myFile=new File(pathname);
  if (!myFile.exists()) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  URLConnection conn;
  String furl="String_Node_Str" + String.valueOf(_index) + "String_Node_Str"+ _filename;
  long start=myFile.length();
  String startRange=java.lang.String.valueOf(start);
  try {
    URL url=new URL(_protocol,_host,_port,furl);
    conn=url.openConnection();
    conn.setRequestProperty("String_Node_Str","String_Node_Str" + startRange + "String_Node_Str");
    conn.connect();
    _istream=conn.getInputStream();
    _br=new ByteReader(_istream);
  }
 catch (  Exception e) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  _resume=true;
  _state=CONNECTED;
}
Program: 5079
Project: 5079
Buggy source:
public void initThree(){
  _stateString=null;
  SettingsManager set=SettingsManager.instance();
  _downloadDir=set.getSaveDirectory();
  String pathname=_downloadDir + _filename;
  File myFile=new File(pathname);
  if (!myFile.exists()) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  URLConnection conn;
  String furl="String_Node_Str" + String.valueOf(_index) + "String_Node_Str"+ _filename;
  long start=myFile.length();
  String startRange=java.lang.String.valueOf(start);
  try {
    URL url=new URL(_protocol,_host,_port,furl);
    conn=url.openConnection();
    conn.setRequestProperty("String_Node_Str","String_Node_Str" + startRange + "String_Node_Str");
    conn.connect();
    _istream=conn.getInputStream();
    _br=new ByteReader(_istream);
  }
 catch (  Exception e) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  _resume=true;
  _state=CONNECTED;
}

Fixed version (ground truth):
public void initThree(){
  _stateString=null;
  SettingsManager set=SettingsManager.instance();
  _downloadDir=set.getIncompleteDirectory();
  String pathname=_downloadDir + _filename;
  File myFile=new File(pathname);
  if (!myFile.exists()) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  URLConnection conn;
  String furl="String_Node_Str" + String.valueOf(_index) + "String_Node_Str"+ _filename;
  long start=myFile.length();
  String startRange=java.lang.String.valueOf(start);
  try {
    URL url=new URL(_protocol,_host,_port,furl);
    conn=url.openConnection();
    conn.setRequestProperty("String_Node_Str","String_Node_Str" + startRange + "String_Node_Str");
    conn.connect();
    _istream=conn.getInputStream();
    _br=new ByteReader(_istream);
  }
 catch (  Exception e) {
    _stateString="String_Node_Str";
    _state=ERROR;
    return;
  }
  _resume=true;
  _state=CONNECTED;
}