nus-yam/ex-repair huggingface dataset:
Program: 4956
Project: 4956
Buggy source:
/** 
 * Sends a get request to out, reads the response from in, and returns the content.  Doesn't close in or out.
 */
private static String downloadInternal(String file,String header,BufferedWriter out,BufferedReader in) throws IOException {
  out.write("String_Node_Str" + index + "String_Node_Str"+ file+ "String_Node_Str");
  if (header != null)   out.write(header + "String_Node_Str");
  out.write("String_Node_Str");
  out.flush();
  while (!in.readLine().equals("String_Node_Str")) {
  }
  StringBuffer buf=new StringBuffer();
  while (true) {
    int c=in.read();
    if (c < 0)     break;
    buf.append((char)c);
  }
  return buf.toString();
}

Fixed version (ground truth):
/** 
 * Sends a get request to out, reads the response from in, and returns the content.  Doesn't close in or out.
 * @param requiredHeader a header to look for, or null if we don't care
 */
private static String downloadInternal(String file,String header,BufferedWriter out,BufferedReader in,String requiredHeader) throws IOException {
  out.write("String_Node_Str" + index + "String_Node_Str"+ file+ "String_Node_Str");
  if (header != null)   out.write(header + "String_Node_Str");
  out.write("String_Node_Str");
  out.flush();
  boolean foundHeader=false;
  while (true) {
    String line=in.readLine();
    if (line.equals("String_Node_Str"))     break;
    if (requiredHeader != null)     if (canonicalizeHeader(line).equals(canonicalizeHeader(requiredHeader)))     foundHeader=true;
  }
  if (requiredHeader != null)   Assert.that(foundHeader,"String_Node_Str");
  StringBuffer buf=new StringBuffer();
  while (true) {
    int c=in.read();
    if (c < 0)     break;
    buf.append((char)c);
  }
  return buf.toString();
}
Program: 4958
Project: 4958
Buggy source:
/** 
 * writes the appropriate header information to the socket
 */
private void writeHeader() throws IOException {
  String str;
  str="String_Node_Str";
  _ostream.write(str.getBytes());
  str="String_Node_Str" + CommonUtils.getVendor() + "String_Node_Str";
  _ostream.write(str.getBytes());
  String type=getMimeType();
  str="String_Node_Str" + type + "String_Node_Str";
  _ostream.write(str.getBytes());
  str="String_Node_Str" + (_uploadEnd - _uploadBegin) + "String_Node_Str";
  _ostream.write(str.getBytes());
  if (_uploadBegin != 0) {
    str="String_Node_Str" + _uploadBegin + "String_Node_Str"+ (_fileSize - 1)+ "String_Node_Str"+ _fileSize+ "String_Node_Str";
    _ostream.write(str.getBytes());
  }
  str="String_Node_Str";
  _ostream.write(str.getBytes());
}

Fixed version (ground truth):
/** 
 * writes the appropriate header information to the socket
 */
private void writeHeader() throws IOException {
  String str;
  str="String_Node_Str";
  _ostream.write(str.getBytes());
  str="String_Node_Str" + CommonUtils.getVendor() + "String_Node_Str";
  _ostream.write(str.getBytes());
  String type=getMimeType();
  str="String_Node_Str" + type + "String_Node_Str";
  _ostream.write(str.getBytes());
  str="String_Node_Str" + (_uploadEnd - _uploadBegin) + "String_Node_Str";
  _ostream.write(str.getBytes());
  if (_uploadBegin != 0) {
    str="String_Node_Str" + _uploadBegin + "String_Node_Str"+ (_uploadEnd - 1)+ "String_Node_Str"+ _fileSize+ "String_Node_Str";
    _ostream.write(str.getBytes());
  }
  str="String_Node_Str";
  _ostream.write(str.getBytes());
}
Program: 4959
Project: 4959
Buggy source:
/** 
 * Returns the directory where all user settings should be stored.  This is where all application data should be stored.  If the directory does does not already exist, this attempts to create the directory, although this is not guaranteed to succeed.
 * @return the <tt>File</tt> instance denoting the user's home directory for the application, or <tt>null</tt> if that directory  does not exist
 */
public static File getUserSettingsDir(){
  if (this.isWindows()) {
    return this.getCurrentDirectory();
  }
  final File HOME_DIR=new File(getUserHomeDir(),"String_Node_Str");
  if (!HOME_DIR.isDirectory()) {
    HOME_DIR.mkdirs();
  }
  return HOME_DIR;
}

Fixed version (ground truth):
/** 
 * Returns the directory where all user settings should be stored.  This is where all application data should be stored.  If the directory does does not already exist, this attempts to create the directory, although this is not guaranteed to succeed.
 * @return the <tt>File</tt> instance denoting the user's home directory for the application, or <tt>null</tt> if that directory  does not exist
 */
public static File getUserSettingsDir(){
  if (isWindows()) {
    return getCurrentDirectory();
  }
  final File HOME_DIR=new File(getUserHomeDir(),"String_Node_Str");
  if (!HOME_DIR.isDirectory()) {
    HOME_DIR.mkdirs();
  }
  return HOME_DIR;
}
Program: 4960
Project: 4960
Buggy source:
private void readHeaders() throws IOException {
  if (_byteReader == null)   throw new ReaderIsNullException();
  String str=_byteReader.readLine();
  if (str == null || str.equals("String_Node_Str"))   return;
  int code=parseHTTPCode(str);
  if ((code < 200) || (code > 300)) {
    if (code == 404)     throw new com.limegroup.gnutella.downloader.FileNotFoundException();
 else     if (code == 410)     throw new com.limegroup.gnutella.downloader.NotSharingException();
 else     if (code == 503)     throw new TryAgainLaterException();
 else     throw new IOException();
  }
  while (true) {
    str=_byteReader.readLine();
    if (str == null || str.equals("String_Node_Str"))     break;
    if (str.toUpperCase().startsWith("String_Node_Str")) {
      int startOffset=parseContentRangeStart(str);
      if (startOffset != _initialReadingPoint)       throw new IOException("String_Node_Str");
    }
  }
}

Fixed version (ground truth):
private void readHeaders() throws IOException {
  if (_byteReader == null)   throw new ReaderIsNullException();
  String str=_byteReader.readLine();
  if (str == null || str.equals("String_Node_Str"))   return;
  int code=parseHTTPCode(str);
  if ((code < 200) || (code >= 300)) {
    if (code == 404)     throw new com.limegroup.gnutella.downloader.FileNotFoundException();
 else     if (code == 410)     throw new com.limegroup.gnutella.downloader.NotSharingException();
 else     if (code == 503)     throw new TryAgainLaterException();
 else     throw new IOException();
  }
  while (true) {
    str=_byteReader.readLine();
    if (str == null || str.equals("String_Node_Str"))     break;
    if (str.toUpperCase().startsWith("String_Node_Str")) {
      int startOffset=parseContentRangeStart(str);
      if (startOffset != _initialReadingPoint)       throw new IOException("String_Node_Str");
    }
  }
}
Program: 4961
Project: 4961
Buggy source:
/** 
 * Canonicalizes a file name - gets rid of articles, etc...
 * @param map Adds the canonicalized elements to this map.
 */
private final void canonicalize(String fileName,Map map){
  StringTokenizer st=new StringTokenizer(fileName,FileManager.DELIMETERS);
  while (st.hasMoreTokens()) {
    final String currToken=st.nextToken().toLowerCase();
    if (wordSet.contains(currToken))     continue;
    try {
      Double.parseDouble(currToken);
      continue;
    }
 catch (    NumberFormatException ignored) {
    }
{
      Integer occurrences=(Integer)map.get(currToken);
      if (occurrences == null)       occurrences=new Integer(1);
 else       occurrences=new Integer(occurrences.intValue() + 1);
      map.put(currToken,occurrences);
    }
  }
}

Fixed version (ground truth):
/** 
 * Canonicalizes a file name - gets rid of articles, etc...
 * @param map Adds the canonicalized elements to this map.
 */
private final void canonicalize(String fileName,Map map){
  StringTokenizer st=new StringTokenizer(fileName,FileManager.DELIMETERS);
  while (st.hasMoreTokens()) {
    final String currToken=st.nextToken().toLowerCase();
    if (wordSet.contains(currToken))     continue;
    try {
      Double d=new Double(currToken);
      continue;
    }
 catch (    NumberFormatException ignored) {
    }
{
      Integer occurrences=(Integer)map.get(currToken);
      if (occurrences == null)       occurrences=new Integer(1);
 else       occurrences=new Integer(occurrences.intValue() + 1);
      map.put(currToken,occurrences);
    }
  }
}
Program: 4963
Project: 4963
Buggy source:
/** 
 * Accepts a new upload, creating a new <tt>HTTPUploader</tt> if it successfully parses the HTTP 'get' header.
 * @param socket the <tt>Socket</tt> that will be used for the new upload
 */
public void acceptUpload(Socket socket){
  HTTPUploader uploader;
  GETLine line;
  try {
synchronized (this) {
      _activeUploads++;
    }
    while (true) {
      try {
        line=parseGET(socket);
      }
 catch (      IOException e) {
        return;
      }
      uploader=new HTTPUploader(line._file,socket,line._index,this,_fileManager);
      doSingleUpload(uploader,socket.getInetAddress().getHostAddress(),line._index);
      if (!line.isHTTP11() || uploader.getCloseConnection())       return;
      try {
        int oldTimeout=socket.getSoTimeout();
        socket.setSoTimeout(SettingsManager.instance().getPersistentHTTPConnectionTimeout());
        String word=IOUtils.readWord(socket.getInputStream(),3);
        socket.setSoTimeout(oldTimeout);
        if (!word.equalsIgnoreCase("String_Node_Str"))         return;
      }
 catch (      IOException ioe) {
        return;
      }
    }
  }
  finally {
synchronized (this) {
      _activeUploads--;
    }
    close(socket);
  }
}

Fixed version (ground truth):
/** 
 * Accepts a new upload, creating a new <tt>HTTPUploader</tt> if it successfully parses the HTTP 'get' header.  BLOCKING.
 * @param socket the <tt>Socket</tt> that will be used for the new upload
 */
public void acceptUpload(Socket socket){
  HTTPUploader uploader;
  GETLine line;
  try {
synchronized (this) {
      _activeUploads++;
    }
    while (true) {
      try {
        line=parseGET(socket);
      }
 catch (      IOException e) {
        return;
      }
      uploader=new HTTPUploader(line._file,socket,line._index,this,_fileManager);
      doSingleUpload(uploader,socket.getInetAddress().getHostAddress(),line._index);
      if (!line.isHTTP11() || uploader.getCloseConnection())       return;
      try {
        int oldTimeout=socket.getSoTimeout();
        socket.setSoTimeout(SettingsManager.instance().getPersistentHTTPConnectionTimeout());
        String word=IOUtils.readWord(socket.getInputStream(),3);
        socket.setSoTimeout(oldTimeout);
        if (!word.equalsIgnoreCase("String_Node_Str"))         return;
      }
 catch (      IOException ioe) {
        return;
      }
    }
  }
  finally {
synchronized (this) {
      _activeUploads--;
    }
    close(socket);
  }
}
Program: 4964
Project: 4964
Buggy source:
/** 
 * Accepts a new push upload, creating a new <tt>HTTPUploader</tt>.
 * @param file the fully qualified pathname of the file to upload
 * @param host the ip address of the host to upload to
 * @param port the port over which the transfer will occur
 * @param index the index of the file in <tt>FileManager</tt>
 * @param guid the unique identifying client guid of the uploading client
 */
public synchronized void acceptPushUpload(String file,String host,int port,int index,String guid){
synchronized (this) {
    _activeUploads++;
  }
  clearFailedPushes();
  Uploader uploader=null;
  try {
    uploader=new HTTPUploader(file,host,port,index,guid,this,_fileManager);
    if ((!testAttemptedPush(host,index)) || (!testFailedPush(host,index)))     return;
    insertAttemptedPush(host,index);
    doSingleUpload(uploader,host,index);
  }
  finally {
synchronized (this) {
      _activeUploads--;
    }
    if (uploader != null)     uploader.stop();
  }
}

Fixed version (ground truth):
/** 
 * Accepts a new push upload, creating a new <tt>HTTPUploader</tt>. NON-BLOCKING: creates a new thread to transfer the file.
 * @param file the fully qualified pathname of the file to upload
 * @param host the ip address of the host to upload to
 * @param port the port over which the transfer will occur
 * @param index the index of the file in <tt>FileManager</tt>
 * @param guid the unique identifying client guid of the uploading client
 */
public synchronized void acceptPushUpload(final String file,final String host,final int port,final int index,final String guid){
  final Uploader uploader=new HTTPUploader(file,host,port,index,guid,this,_fileManager);
  clearFailedPushes();
  if ((!testAttemptingPush(host,index)) || (!testFailedPush(host,index)))   return;
  insertAttemptingPush(host,index);
  Thread runner=new Thread(){
    public void run(){
      try {
synchronized (UploadManager.this) {
          _activeUploads++;
        }
        doSingleUpload(uploader,host,index);
      }
  finally {
synchronized (UploadManager.this) {
          _activeUploads--;
        }
        uploader.stop();
      }
    }
  }
;
  runner.start();
}
Program: 4965
Project: 4965
Buggy source:
private void doSingleUpload(Uploader uploader,String host,int index){
  long startTime=-1;
  try {
    insertAndTest(uploader,host);
    uploader.connect();
    startTime=System.currentTimeMillis();
    uploader.start();
    if (uploader.getState() == Uploader.COMPLETE)     _hadSuccesfulUpload=true;
  }
 catch (  IOException e) {
synchronized (UploadManager.this) {
      insertFailedPush(host,index);
    }
  }
 finally {
    long finishTime=System.currentTimeMillis();
synchronized (UploadManager.this) {
      if (startTime > 0)       reportUploadSpeed(finishTime - startTime,uploader.amountUploaded());
      removeFromMapAndList(uploader,host);
      removeAttemptedPush(host,index);
      _callback.removeUpload(uploader);
    }
  }
}

Fixed version (ground truth):
private void doSingleUpload(Uploader uploader,String host,int index){
  long startTime=-1;
  try {
    insertAndTest(uploader,host);
    uploader.connect();
    startTime=System.currentTimeMillis();
    uploader.start();
    if (uploader.getState() == Uploader.COMPLETE)     _hadSuccesfulUpload=true;
  }
 catch (  IOException e) {
synchronized (UploadManager.this) {
      insertFailedPush(host,index);
    }
  }
 finally {
    long finishTime=System.currentTimeMillis();
synchronized (UploadManager.this) {
      if (startTime > 0)       reportUploadSpeed(finishTime - startTime,uploader.amountUploaded());
      removeFromMapAndList(uploader,host);
      removeAttemptingPush(host,index);
      _callback.removeUpload(uploader);
    }
  }
}
Program: 4966
Project: 4966
Buggy source:
/** 
 * Adds the given location to this.  This will terminate after downloading rfd or any of the other locations in this.  This may swarm some file from rfd and other locations.
 * @param rfd a new download candidate.  Typically rfd will be similar orsame to some entry in this, but that is not required.  
 */
public synchronized void addDownload(RemoteFileDesc rfd){
  for (int i=0; i < allFiles.length; i++) {
    if (rfd.equals(allFiles[i]))     return;
  }
  buckets.add(rfd);
  RemoteFileDesc[] newAllFiles=new RemoteFileDesc[allFiles.length + 1];
  System.arraycopy(allFiles,0,newAllFiles,0,allFiles.length);
  newAllFiles[newAllFiles.length - 1]=rfd;
  allFiles=newAllFiles;
  if ((state == Downloader.WAITING_FOR_RETRY) || (state == Downloader.WAITING_FOR_RESULTS))   reqLock.release();
 else   this.notify();
}

Fixed version (ground truth):
/** 
 * Adds the given location to this.  This will terminate after downloading rfd or any of the other locations in this.  This may swarm some file from rfd and other locations.
 * @param rfd a new download candidate.  Typically rfd will be similar orsame to some entry in this, but that is not required.  
 */
public synchronized void addDownload(RemoteFileDesc rfd){
  for (int i=0; i < allFiles.length; i++) {
    if (rfd.equals(allFiles[i]))     return;
  }
  if (buckets != null)   buckets.add(rfd);
  RemoteFileDesc[] newAllFiles=new RemoteFileDesc[allFiles.length + 1];
  System.arraycopy(allFiles,0,newAllFiles,0,allFiles.length);
  newAllFiles[newAllFiles.length - 1]=rfd;
  allFiles=newAllFiles;
  if ((state == Downloader.WAITING_FOR_RETRY) || (state == Downloader.WAITING_FOR_RESULTS))   reqLock.release();
 else   this.notify();
}
Program: 4967
Project: 4967
Buggy source:
/** 
 * Increments the count of uploads in progress for host. If uploader has exceeded its limits, places it in LIMIT_REACHED state. Notifies callback of this.
 * @requires this' monitor is held
 * @modifies _uploadsInProgress, uploader, _callback 
 */
private void insertAndTest(Uploader uploader,String host){
  insertIntoMapAndList(uploader,host);
  if ((!testPerHostLimit(host)) || (!testTotalUploadLimit()))   uploader.setState(Uploader.LIMIT_REACHED);
  _callback.addUpload(uploader);
}

Fixed version (ground truth):
/** 
 * Increments the count of uploads in progress for host. If uploader has exceeded its limits, places it in LIMIT_REACHED state. Notifies callback of this.
 * @modifies _uploadsInProgress, uploader, _callback 
 */
private synchronized void insertAndTest(Uploader uploader,String host){
  insertIntoMapAndList(uploader,host);
  if ((!testPerHostLimit(host)) || (!testTotalUploadLimit()))   uploader.setState(Uploader.LIMIT_REACHED);
  _callback.addUpload(uploader);
}
Program: 4968
Project: 4968
Buggy source:
/** 
 * Downloads file (stored in slot index) from address:port, returning the content as a string. If header!=null, includes it as a request header. Do not include new line or carriage return in header.  Throws IOException if there is a problem, without cleaning up. 
 */
private static String download(String file,String header) throws IOException {
  Socket s=new Socket(address,port);
  BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
  BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
  String ret=downloadInternal(file,header,out,in);
  in.close();
  out.close();
  s.close();
  return ret;
}

Fixed version (ground truth):
private static boolean download(String file,String header,String expResp) throws IOException {
  Socket s=new Socket(address,port);
  BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
  BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
  String ret=downloadInternal(file,header,out,in);
  in.close();
  out.close();
  s.close();
  return ret.equals(expResp);
}
Program: 4969
Project: 4969
Buggy source:
private static void test(String testName,boolean passed,String output){
  System.out.println((passed ? "String_Node_Str" : "String_Node_Str") + "String_Node_Str" + testName);
  if (!passed)   System.out.println("String_Node_Str" + output + "String_Node_Str");
}

Fixed version (ground truth):
private static void test(String testName,boolean passed){
  System.out.println((passed ? "String_Node_Str" : "String_Node_Str") + "String_Node_Str" + testName);
  if (!passed)   System.out.println("String_Node_Str");
}
Program: 4971
Project: 4971
Buggy source:
private static String downloadPush(String file,String header) throws IOException, BadPacketException {
  Connection c=new Connection(address,port);
  c.initialize();
  QueryRequest query=new QueryRequest((byte)5,0,"String_Node_Str");
  c.send(query);
  c.flush();
  QueryReply reply=null;
  while (true) {
    Message m=c.receive(2000);
    if (m instanceof QueryReply) {
      reply=(QueryReply)m;
      break;
    }
  }
  PushRequest push=new PushRequest(GUID.makeGuid(),(byte)5,reply.getClientGUID(),0,new byte[]{(byte)127,(byte)0,(byte)0,(byte)1},callbackPort);
  ServerSocket ss=new ServerSocket(callbackPort);
  c.send(push);
  c.flush();
  Socket s=ss.accept();
  BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
  BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
  in.readLine();
  in.readLine();
  String ret=downloadInternal(file,header,out,in);
  c.close();
  s.close();
  ss.close();
  return ret;
}

Fixed version (ground truth):
private static boolean downloadPush(String file,String header,String expResp) throws IOException, BadPacketException {
  Connection c=new Connection(address,port);
  c.initialize();
  QueryRequest query=new QueryRequest((byte)5,0,"String_Node_Str");
  c.send(query);
  c.flush();
  QueryReply reply=null;
  while (true) {
    Message m=c.receive(2000);
    if (m instanceof QueryReply) {
      reply=(QueryReply)m;
      break;
    }
  }
  PushRequest push=new PushRequest(GUID.makeGuid(),(byte)5,reply.getClientGUID(),0,new byte[]{(byte)127,(byte)0,(byte)0,(byte)1},callbackPort);
  ServerSocket ss=new ServerSocket(callbackPort);
  c.send(push);
  c.flush();
  Socket s=ss.accept();
  BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
  BufferedWriter out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
  in.readLine();
  in.readLine();
  String retStr=downloadInternal(file,header,out,in);
  c.close();
  s.close();
  ss.close();
  return retStr.equals(expResp);
}
Program: 4972
Project: 4972
Buggy source:
/** 
 * Increments the count of uploads in progress for host. If uploader has exceeded its limits, places it in LIMIT_REACHED state and returns false.  Otherwise returns true. Notifies callback of this.
 * @modifies _uploadsInProgress, uploader, _callback 
 */
private synchronized boolean insertAndTest(HTTPUploader uploader,String host){
  insertIntoMapAndList(uploader,host);
  if ((!testPerHostLimit(host)) || (!testTotalUploadLimit())) {
    uploader.setState(Uploader.LIMIT_REACHED);
    return false;
  }
  _callback.addUpload(uploader);
  return true;
}

Fixed version (ground truth):
/** 
 * Increments the count of uploads in progress for host. If uploader has exceeded its limits, places it in LIMIT_REACHED state and returns false.  Otherwise returns true. Notifies callback of this.
 * @modifies _uploadsInProgress, uploader, _callback 
 */
private synchronized boolean insertAndTest(HTTPUploader uploader,String host){
  insertIntoMapAndList(uploader,host);
  if ((!testPerHostLimit(host)) || (!testTotalUploadLimit())) {
    uploader.setState(Uploader.LIMIT_REACHED);
    return false;
  }
  return true;
}
Program: 4973
Project: 4973
Buggy source:
/** 
 * Does some book-keeping and makes the downloader, start the download
 * @param uploader This method assumes that uploader is connected.
 */
private void doSingleUpload(HTTPUploader uploader,String host,int index){
  long startTime=-1;
  boolean accepted=insertAndTest(uploader,host);
synchronized (this) {
    if (accepted)     _activeUploads++;
  }
  startTime=System.currentTimeMillis();
  uploader.start();
  if (uploader.getState() == Uploader.COMPLETE)   _hadSuccesfulUpload=true;
  long finishTime=System.currentTimeMillis();
synchronized (UploadManager.this) {
    if (startTime > 0)     reportUploadSpeed(finishTime - startTime,uploader.amountUploaded());
    removeFromMapAndList(uploader,host);
    removeAttemptingPush(host,index);
    if (accepted)     _activeUploads--;
    _callback.removeUpload(uploader);
  }
}

Fixed version (ground truth):
/** 
 * Does some book-keeping and makes the downloader, start the download
 * @param uploader This method assumes that uploader is connected.
 */
private void doSingleUpload(HTTPUploader uploader,String host,int index){
  long startTime=-1;
  boolean accepted=insertAndTest(uploader,host);
  _callback.addUpload(uploader);
synchronized (this) {
    if (accepted)     _activeUploads++;
  }
  startTime=System.currentTimeMillis();
  uploader.start();
  if (uploader.getState() == Uploader.COMPLETE)   _hadSuccesfulUpload=true;
  long finishTime=System.currentTimeMillis();
synchronized (UploadManager.this) {
    if (startTime > 0)     reportUploadSpeed(finishTime - startTime,uploader.amountUploaded());
    removeFromMapAndList(uploader,host);
    removeAttemptingPush(host,index);
    if (accepted)     _activeUploads--;
    _callback.removeUpload(uploader);
  }
}
Program: 4974
Project: 4974
Buggy source:
/** 
 * @return the bytes for a new GUID flagged to be a requery made by LW. 
 */
public static byte[] makeGuidRequery(){
  byte[] ret=makeGuid();
  tagGuid(ret,0,9,13);
  return ret;
}

Fixed version (ground truth):
/** 
 * @return the bytes for a new GUID flagged to be a requery made by LW. 
 */
public static byte[] makeGuidRequery(){
  byte[] ret=makeGuid();
  tagGuid(ret,0,2,13);
  return ret;
}
Program: 4975
Project: 4975
Buggy source:
/** 
 * Returns true if this is a specially marked LimeWire Requery GUID. This does NOT mean that it's a new GUID as well; the caller will probably want to check that. 
 */
public static boolean isLimeRequeryGUID(byte[] bytes){
  return checkMatching(bytes,0,9,13);
}

Fixed version (ground truth):
/** 
 * Returns true if this is a specially marked LimeWire Requery GUID. This does NOT mean that it's a new GUID as well; the caller will probably want to check that. 
 * @param isOld true if the caller is interested in LW 2.2.0-2.2.3requery GUIDs, false if the caller is interested 2.2.4+ GUIDs.
 */
public static boolean isLimeRequeryGUID(byte[] bytes,boolean isOld){
  if (isOld)   return checkMatching(bytes,0,9,13);
 else   return checkMatching(bytes,0,2,13);
}
Program: 4977
Project: 4977
Buggy source:
/** 
 * @return the number of minutes to wait for your next requery....
 */
private int getMinutesToWaitForRequery(int numCalls){
switch (numCalls) {
case 1:
    return 2;
case 2:
  return 15;
case 3:
return 60;
case 4:
return 120;
default :
return 180;
}
}

Fixed version (ground truth):
/** 
 * Returns the time to wait between the n'th and n+1'th automatic requery, where n=requeries.  Hence getMinutesToWaitForRequery(0) is the time to wait before the first requery.  getMinutesToWaitForRequery(1) is the time to wait after that before requerying again.
 * @param requeriesthe number of requeries sent, which must be non-negative
 * @return minutes to wait
 */
private int getMinutesToWaitForRequery(int requeries){
switch (requeries) {
case 0:
    return 2;
case 1:
  return 15;
case 2:
return 60;
case 3:
return 120;
default :
return 180;
}
}
Program: 4978
Project: 4978
Buggy source:
/** 
 * Accepts a new push upload, creating a new <tt>HTTPUploader</tt>.
 * @param file the fully qualified pathname of the file to upload
 * @param host the ip address of the host to upload to
 * @param port the port over which the transfer will occur
 * @param index the index of the file in <tt>FileManager</tt>
 * @param guid the unique identifying client guid of the uploading client
 */
public synchronized void acceptPushUpload(String file,String host,int port,int index,String guid){
  clearFailedPushes();
  Uploader uploader=null;
  try {
    uploader=new HTTPUploader(file,host,port,index,guid,this,_fileManager);
    if ((!testAttemptedPush(host,index)) || (!testFailedPush(host,index)))     return;
    insertAndTest(uploader,host);
    insertAttemptedPush(host,index);
    doSingleUpload(uploader,host,index);
  }
  finally {
    if (uploader != null)     uploader.stop();
  }
}

Fixed version (ground truth):
/** 
 * Accepts a new push upload, creating a new <tt>HTTPUploader</tt>.
 * @param file the fully qualified pathname of the file to upload
 * @param host the ip address of the host to upload to
 * @param port the port over which the transfer will occur
 * @param index the index of the file in <tt>FileManager</tt>
 * @param guid the unique identifying client guid of the uploading client
 */
public synchronized void acceptPushUpload(String file,String host,int port,int index,String guid){
synchronized (this) {
    _activeUploads++;
  }
  clearFailedPushes();
  Uploader uploader=null;
  try {
    uploader=new HTTPUploader(file,host,port,index,guid,this,_fileManager);
    if ((!testAttemptedPush(host,index)) || (!testFailedPush(host,index)))     return;
    insertAttemptedPush(host,index);
    doSingleUpload(uploader,host,index);
  }
  finally {
synchronized (this) {
      _activeUploads--;
    }
    if (uploader != null)     uploader.stop();
  }
}
Program: 4979
Project: 4979
Buggy source:
private boolean doSingleUpload(Uploader uploader,String host,int index){
  long startTime=-1;
  try {
    insertAndTest(uploader,host);
    uploader.connect();
    startTime=System.currentTimeMillis();
    uploader.start();
    if (uploader.getState() == Uploader.COMPLETE)     _hadSuccesfulUpload=true;
  }
 catch (  IOException e) {
synchronized (UploadManager.this) {
      insertFailedPush(host,index);
    }
  }
 finally {
    long finishTime=System.currentTimeMillis();
synchronized (UploadManager.this) {
      if (startTime > 0)       reportUploadSpeed(finishTime - startTime,uploader.amountUploaded());
      removeFromMapAndList(uploader,host);
      removeAttemptedPush(host,index);
      _callback.removeUpload(uploader);
    }
  }
  return false;
}

Fixed version (ground truth):
private void doSingleUpload(Uploader uploader,String host,int index){
  long startTime=-1;
  try {
    insertAndTest(uploader,host);
    uploader.connect();
    startTime=System.currentTimeMillis();
    uploader.start();
    if (uploader.getState() == Uploader.COMPLETE)     _hadSuccesfulUpload=true;
  }
 catch (  IOException e) {
synchronized (UploadManager.this) {
      insertFailedPush(host,index);
    }
  }
 finally {
    long finishTime=System.currentTimeMillis();
synchronized (UploadManager.this) {
      if (startTime > 0)       reportUploadSpeed(finishTime - startTime,uploader.amountUploaded());
      removeFromMapAndList(uploader,host);
      removeAttemptedPush(host,index);
      _callback.removeUpload(uploader);
    }
  }
}
Program: 4980
Project: 4980
Buggy source:
/** 
 * Gets a list of keywords from all the documents in this collection. <p> delegates to the individual documents and collates the list
 */
protected List getKeyWords(){
  List retList=new ArrayList();
  Iterator docs;
synchronized (mainMapLock) {
    docs=mainMap.values().iterator();
  }
  while (docs.hasNext()) {
    LimeXMLDocument d=(LimeXMLDocument)docs.next();
    retList.addAll(d.getKeyWords());
  }
  return retList;
}

Fixed version (ground truth):
/** 
 * Gets a list of keywords from all the documents in this collection. <p> delegates to the individual documents and collates the list
 */
protected List getKeyWords(){
  List retList=new ArrayList();
  Iterator docs;
synchronized (mainMapLock) {
    docs=mainMap.values().iterator();
    while (docs.hasNext()) {
      LimeXMLDocument d=(LimeXMLDocument)docs.next();
      retList.addAll(d.getKeyWords());
    }
  }
  return retList;
}
Program: 4982
Project: 4982
Buggy source:
private void addAudioMetadata(Response[] responses){
  if (responses == null)   return;
  String audioURI="String_Node_Str";
  SchemaReplyCollectionMapper map=SchemaReplyCollectionMapper.instance();
  LimeXMLReplyCollection coll=map.getReplyCollection(audioURI);
  if (coll == null)   return;
  int z=responses.length;
  for (int i=0; i < z; i++) {
    FileDesc f=get((int)responses[i].getIndex());
    File file=new File(f._path);
    String hash=readFromMap(file,true);
    LimeXMLDocument doc=coll.getDocForHash(hash);
    if (doc == null)     continue;
    String XMLString="String_Node_Str";
    try {
      XMLString=doc.getXMLString();
    }
 catch (    Exception e) {
      e.printStackTrace();
      continue;
    }
    if (XMLString != null && !XMLString.equals("String_Node_Str")) {
      responses[i].setMetadata(XMLString);
    }
  }
}

Fixed version (ground truth):
private void addAudioMetadata(Response[] responses){
  if (responses == null)   return;
  String audioURI="String_Node_Str";
  SchemaReplyCollectionMapper map=SchemaReplyCollectionMapper.instance();
  LimeXMLReplyCollection coll=map.getReplyCollection(audioURI);
  if (coll == null)   return;
  int z=responses.length;
  for (int i=0; i < z; i++) {
    FileDesc f=get((int)responses[i].getIndex());
    File file=new File(f._path);
    String hash=readFromMap(file,true);
    if (hash == null)     hash=readFromMap(file,false);
    LimeXMLDocument doc=coll.getDocForHash(hash);
    if (doc == null)     continue;
    String XMLString="String_Node_Str";
    try {
      XMLString=doc.getXMLString();
    }
 catch (    Exception e) {
      e.printStackTrace();
      continue;
    }
    if (XMLString != null && !XMLString.equals("String_Node_Str")) {
      responses[i].setMetadata(XMLString);
    }
  }
}
Program: 4985
Project: 4985
Buggy source:
/** 
 * Indicates that we are a client node, and have received supernode connection. Executing this method will lead to dropping all the  connections except the one to the supernode. 
 * @param supernodeConnection The connectionto the supernode that wewanna preserve
 */
private synchronized void gotShieldedClientSupernodeConnection(ManagedConnection supernodeConnection){
  deactivateUltraFastConnectShutdown();
  setKeepAlive(0);
  Iterator iterator=_connections.iterator();
  while (iterator.hasNext()) {
    ManagedConnection connection=(ManagedConnection)iterator.next();
    if (!connection.equals(supernodeConnection))     remove(connection);
  }
}

Fixed version (ground truth):
/** 
 * Indicates that we are a client node, and have received supernode connection. Executing this method will lead to dropping all the  connections except the one to the supernode. 
 * @param supernodeConnection The connectionto the supernode that wewanna preserve
 */
private synchronized void gotShieldedClientSupernodeConnection(ManagedConnection supernodeConnection){
  deactivateUltraFastConnectShutdown();
  setKeepAlive(Math.min(1,_keepAlive));
  Iterator iterator=_connections.iterator();
  while (iterator.hasNext()) {
    ManagedConnection connection=(ManagedConnection)iterator.next();
    if (!connection.equals(supernodeConnection))     remove(connection);
  }
}
Program: 4986
Project: 4986
Buggy source:
/** 
 * Indicates that the node is in the client node, and has now lost its only connection to the supernode
 */
private synchronized void lostShieldedClientSupernodeConnection(){
  if (_connections.size() == 0) {
    setKeepAlive(SettingsManager.instance().getKeepAlive());
  }
}

Fixed version (ground truth):
/** 
 * Indicates that the node is in the client node, and has now lost its only connection to the supernode
 */
private synchronized void lostShieldedClientSupernodeConnection(){
  if (_connections.size() == 0 && _keepAlive > 0) {
    setKeepAlive(SettingsManager.instance().getKeepAlive());
  }
}
Program: 4987
Project: 4987
Buggy source:
/** 
 * Reset how many connections you want and start kicking more off if required.  This IS synchronized because we don't want threads adding or removing connections while this is deciding whether to add more threads.  Ignores request if a shielded leaf node.
 */
public synchronized void setKeepAlive(int newKeep){
  if (hasClientSupernodeConnection())   return;
  _keepAlive=newKeep;
  adjustConnectionFetchers();
}

Fixed version (ground truth):
/** 
 * Reset how many connections you want and start kicking more off if required.  This IS synchronized because we don't want threads adding or removing connections while this is deciding whether to add more threads.  Ignores request if a shielded leaf node and newKeep>1 (sic).
 */
public synchronized void setKeepAlive(int newKeep){
  if (newKeep > 1 && hasClientSupernodeConnection())   return;
  _keepAlive=newKeep;
  adjustConnectionFetchers();
}
Program: 4988
Project: 4988
Buggy source:
/** 
 * Broadcasts the query request to all initialized connections that are not the receivingConnection, setting up the routing to the designated QueryReplyHandler.  This is called from the default handleQueryRequest and the default broadcastQueryRequest(QueryRequest) If different (smarter) broadcasting functionality is desired, override as desired.  If you do, note that receivingConnection may be null (for requests originating here).
 */
protected void broadcastQueryRequest(QueryRequest queryRequest,ManagedConnection receivingConnection,ConnectionManager manager){
  List list=_manager.getInitializedConnections2();
  for (int i=0; i < list.size(); i++) {
    ManagedConnection c=(ManagedConnection)list.get(i);
    c.send(queryRequest);
  }
  list=_manager.getInitializedClientConnections2();
  for (int i=0; i < list.size(); i++) {
    ManagedConnection c=(ManagedConnection)list.get(i);
    if (c != receivingConnection) {
      ManagedConnectionQueryInfo qi=c.getQueryRouteState();
      if (qi == null || qi.lastReceived == null)       return;
 else       if (qi.lastReceived.contains(queryRequest)) {
        c.send(queryRequest);
      }
    }
  }
}

Fixed version (ground truth):
/** 
 * Broadcasts the query request to all initialized connections that are not the receivingConnection, setting up the routing to the designated QueryReplyHandler.  This is called from the default handleQueryRequest and the default broadcastQueryRequest(QueryRequest) If different (smarter) broadcasting functionality is desired, override as desired.  If you do, note that receivingConnection may be null (for requests originating here).
 */
protected void broadcastQueryRequest(QueryRequest queryRequest,ManagedConnection receivingConnection,ConnectionManager manager){
  List list=_manager.getInitializedConnections2();
  for (int i=0; i < list.size(); i++) {
    ManagedConnection c=(ManagedConnection)list.get(i);
    if (c != receivingConnection) {
      c.send(queryRequest);
    }
  }
  list=_manager.getInitializedClientConnections2();
  for (int i=0; i < list.size(); i++) {
    ManagedConnection c=(ManagedConnection)list.get(i);
    if (c != receivingConnection) {
      ManagedConnectionQueryInfo qi=c.getQueryRouteState();
      if (qi == null || qi.lastReceived == null)       return;
 else       if (qi.lastReceived.contains(queryRequest)) {
        c.send(queryRequest);
      }
    }
  }
}
Program: 4989
Project: 4989
Buggy source:
/** 
 * Sets EVER_SUPERNODE_CAPABLE to true if this has the necessary requirements for becoming a supernode if needed, based on  the node's bandwidth, operating system, firewalled status,  uptime, etc.  Does not modify the property if the capabilities are not met.  If the user has disabled supernode support,  sets EVER_SUPERNODE_CAPABLE to false.
 */
public void setSupernodeCapable(){
  if (SETTINGS.getDisableSupernodeMode()) {
    SETTINGS.setEverSupernodeCapable(false);
    return;
  }
  boolean isSupernodeCapable=(((_maxUpstreamBytesPerSec >= MINIMUM_REQUIRED_UPSTREAM_BYTES_PER_SECOND) || (_maxDownstreamBytesPerSec >= MINIMUM_REQUIRED_DOWNSTREAM_BYTES_PER_SECOND)) && (AVERAGE_UPTIME >= MINIMUM_AVERAGE_UPTIME) && (_currentUptime >= MINIMUM_CURRENT_UPTIME)&& (SETTINGS.getEverAcceptedIncoming())&& (SUPERNODE_OS));
  if (isSupernodeCapable)   SETTINGS.setEverSupernodeCapable(true);
}

Fixed version (ground truth):
/** 
 * Sets EVER_SUPERNODE_CAPABLE to true if this has the necessary requirements for becoming a supernode if needed, based on  the node's bandwidth, operating system, firewalled status,  uptime, etc.  Does not modify the property if the capabilities are not met.  If the user has disabled supernode support,  sets EVER_SUPERNODE_CAPABLE to false.
 */
public void setSupernodeCapable(){
  if (SETTINGS.getDisableSupernodeMode()) {
    SETTINGS.setEverSupernodeCapable(false);
    return;
  }
  boolean isSupernodeCapable=(_maxUpstreamBytesPerSec >= MINIMUM_REQUIRED_UPSTREAM_KBYTES_PER_SECOND || _maxDownstreamBytesPerSec >= MINIMUM_REQUIRED_DOWNSTREAM_KBYTES_PER_SECOND) && (SETTINGS.getAverageUptime() >= MINIMUM_AVERAGE_UPTIME || _currentUptime >= MINIMUM_CURRENT_UPTIME) && SETTINGS.getEverAcceptedIncoming()&& SUPERNODE_OS;
  if (isSupernodeCapable)   SETTINGS.setEverSupernodeCapable(true);
}
Program: 4990
Project: 4990
Buggy source:
/** 
 * Returns whether or not this operating system is considered capable of meeting the requirements of a supernode.
 * @return <tt>true</tt> if this os meets supernode requirements,<tt>false</tt> otherwise
 */
public static boolean isSupernodeOS(){
  if (!_isWindows98 && !_isWindows95 && !_isMacClassic) {
    return false;
  }
  return true;
}

Fixed version (ground truth):
/** 
 * Returns whether or not this operating system is considered capable of meeting the requirements of a supernode.
 * @return <tt>true</tt> if this os meets supernode requirements,<tt>false</tt> otherwise
 */
public static boolean isSupernodeOS(){
  if (_isWindows98 || _isWindows95 || _isMacClassic) {
    return false;
  }
  return true;
}
Program: 4991
Project: 4991
Buggy source:
/** 
 * Blocks until we get a good pong. Throws InterruptedException if interrupted while waiting. 
 */
private void connectUntilPong() throws InterruptedException {
  gotGoodPong=false;
  while (!gotGoodPong) {
    String[] hosts=settings.getQuickConnectHosts();
    for (int i=0; i < hosts.length; i++) {
      Endpoint e;
      try {
        e=new Endpoint(hosts[i]);
      }
 catch (      IllegalArgumentException exc) {
        continue;
      }
      try {
        manager.createRouterConnection(e.getHostname(),e.getPort());
      }
 catch (      IOException exc) {
        continue;
      }
synchronized (gotGoodPongLock) {
        if (!gotGoodPong) {
          gotGoodPongLock.wait(CONNECT_TIME);
        }
      }
    }
    if (stale) {
synchronized (staleLock) {
        stale=false;
        staleLock.notifyAll();
      }
    }
    if (!gotGoodPong)     Thread.sleep(RETRY_TIME);
  }
}

Fixed version (ground truth):
/** 
 * Blocks until we get a good pong. Throws InterruptedException if interrupted while waiting. 
 */
private void connectUntilPong() throws InterruptedException {
  gotGoodPong=false;
  while (!gotGoodPong) {
    String[] hosts=settings.getQuickConnectHosts();
    for (int i=0; i < hosts.length && !gotGoodPong; i++) {
      Endpoint e;
      try {
        e=new Endpoint(hosts[i]);
      }
 catch (      IllegalArgumentException exc) {
        continue;
      }
      try {
        manager.createRouterConnection(e.getHostname(),e.getPort());
      }
 catch (      IOException exc) {
        continue;
      }
synchronized (gotGoodPongLock) {
        if (!gotGoodPong) {
          gotGoodPongLock.wait(CONNECT_TIME);
        }
      }
    }
    if (stale) {
synchronized (staleLock) {
        stale=false;
        staleLock.notifyAll();
      }
    }
    if (!gotGoodPong)     Thread.sleep(RETRY_TIME);
  }
}
Program: 4992
Project: 4992
Buggy source:
public void doDownload() throws IOException {
  _fos=new RandomAccessFile(_incompleteFile,"String_Node_Str");
  _fos.seek(_initialReadingPoint);
  int c=-1;
  byte[] buf=new byte[1024];
  while (true) {
    if (_amountRead >= _amountToRead)     break;
    c=_byteReader.read(buf);
    if (c == -1)     break;
    _fos.write(buf,0,c);
    _amountRead+=c;
  }
  _byteReader.close();
  _fos.close();
  if (_amountRead != _amountToRead) {
    throw new FileIncompleteException();
  }
}

Fixed version (ground truth):
public void doDownload() throws IOException {
  _fos=new RandomAccessFile(_incompleteFile,"String_Node_Str");
  _fos.seek(_initialReadingPoint);
  int c=-1;
  byte[] buf=new byte[BUF_LENGTH];
  while (true) {
    if (_amountRead >= _amountToRead)     break;
    int left=_amountToRead - _amountRead;
    c=_byteReader.read(buf,0,Math.min(BUF_LENGTH,left));
    if (c == -1)     break;
    _fos.write(buf,0,c);
    _amountRead+=c;
  }
  _byteReader.close();
  _fos.close();
  if (_amountRead != _amountToRead) {
    throw new FileIncompleteException();
  }
}
Program: 4993
Project: 4993
Buggy source:
/** 
 * Sets the shared directories.  This method filters out any duplicate or invalid directories in the string. Note, however, that it does not currently filter out listing subdirectories that have parent directories also in the string. 
 * @param dirs an array of <tt>File</tt> instances denotingthe abstract pathnames of the shared directories
 */
public void setDirectories(final File[] dirArray){
  HashMap directories=new HashMap();
  for (int i=0; i < dirArray.length; i++) {
    directories.put(dirArray[i],"String_Node_Str");
  }
  Set fileSet=directories.keySet();
  Object[] prunedFiles=fileSet.toArray();
  StringBuffer sb=new StringBuffer();
  for (int z=0; z < prunedFiles.length; z++) {
    if (prunedFiles[z] != null) {
      sb.append(prunedFiles[z]);
      sb.append(';');
    }
  }
  _directories=new File[prunedFiles.length];
  for (int r=0; r < prunedFiles.length; r++) {
    _directories[r]=(File)prunedFiles[r];
  }
  PROPS.put(DIRECTORIES,sb.toString());
}

Fixed version (ground truth):
/** 
 * Sets the shared directories.  This method filters out any duplicate or invalid directories in the string. Note, however, that it does not currently filter out listing subdirectories that have parent directories also in the string. 
 * @param dirs an array of <tt>File</tt> instances denotingthe abstract pathnames of the shared directories
 */
public void setDirectories(final File[] dirArray){
  HashMap directories=new HashMap();
  for (int i=0; i < dirArray.length; i++) {
    if (dirArray[i].isDirectory())     directories.put(dirArray[i],"String_Node_Str");
  }
  Set fileSet=directories.keySet();
  Object[] prunedFiles=fileSet.toArray();
  StringBuffer sb=new StringBuffer();
  for (int z=0; z < prunedFiles.length; z++) {
    if (prunedFiles[z] != null) {
      sb.append(prunedFiles[z]);
      sb.append(';');
    }
  }
  _directories=new File[prunedFiles.length];
  for (int r=0; r < prunedFiles.length; r++) {
    _directories[r]=(File)prunedFiles[r];
  }
  PROPS.put(DIRECTORIES,sb.toString());
}
Program: 4994
Project: 4994
Buggy source:
/** 
 * Initializes the key backend components.  Some tasks are postponed until postGuiInit().
 */
public void initialize(){
  SettingsManager settings=SettingsManager.instance();
  int port=settings.getPort();
  this.acceptor=new Acceptor(port,callback);
  this.manager=new ConnectionManager(callback);
  this.catcher=new HostCatcher(callback);
  this.downloader=new DownloadManager();
  this.uploadManager=new UploadManager();
  this.catcher.initialize(acceptor,manager,SettingsManager.instance().getHostList());
  this.router.initialize(acceptor,manager,catcher,uploadManager);
  this.manager.initialize(router,catcher);
  this.uploadManager.initialize(callback,router,acceptor,fileManager);
  this.acceptor.initialize(manager,router,downloader,uploadManager);
  this.catcher.connectToRouter();
  this.downloader.initialize(callback,router,acceptor,fileManager);
  Thread supernodeThread=new Thread(new SupernodeAssigner(uploadManager,downloader));
  supernodeThread.setDaemon(true);
  supernodeThread.start();
  int outgoing=settings.getKeepAlive();
  if (outgoing > 0)   connect();
}

Fixed version (ground truth):
/** 
 * Initializes the key backend components.  Some tasks are postponed until postGuiInit().
 */
public void initialize(){
  SettingsManager settings=SettingsManager.instance();
  int port=settings.getPort();
  this.acceptor=new Acceptor(port,callback);
  this.manager=new ConnectionManager(callback);
  this.catcher=new HostCatcher(callback);
  this.downloader=new DownloadManager();
  this.uploadManager=new UploadManager();
  this.chatManager=ChatManager.instance();
  this.catcher.initialize(acceptor,manager,SettingsManager.instance().getHostList());
  this.router.initialize(acceptor,manager,catcher,uploadManager);
  this.manager.initialize(router,catcher);
  this.uploadManager.initialize(callback,router,acceptor,fileManager);
  this.acceptor.initialize(manager,router,downloader,uploadManager);
  this.chatManager.setActivityCallback(callback);
  this.catcher.connectToRouter();
  this.downloader.initialize(callback,router,acceptor,fileManager);
  Thread supernodeThread=new Thread(new SupernodeAssigner(uploadManager,downloader));
  supernodeThread.setDaemon(true);
  supernodeThread.start();
  int outgoing=settings.getKeepAlive();
  if (outgoing > 0)   connect();
}