nus-yam/ex-repair huggingface dataset:
Program: 4574
Project: 4574
Buggy source:
/** 
 * Sends an ack back to the GUESS client node.  
 */
protected void sendAcknowledgement(DatagramPacket datagram,byte[] guid){
  ConnectionManager manager=RouterService.getConnectionManager();
  Endpoint host=manager.getConnectedGUESSUltrapeer();
  PingReply reply;
  if (host != null) {
    try {
      reply=PingReply.createGUESSReply(guid,(byte)1,host);
    }
 catch (    UnknownHostException e) {
      reply=createPingReply(guid);
    }
  }
 else {
    reply=createPingReply(guid);
  }
  try {
    UDPService.instance().send(reply,datagram.getAddress(),datagram.getPort());
  }
 catch (  IOException ioe) {
    ErrorService.error(ioe,"String_Node_Str" + datagram.getAddress() + "String_Node_Str"+ datagram.getPort());
  }
  if (RECORD_STATS)   SentMessageStatHandler.UDP_PING_REPLIES.addMessage(reply);
}

Fixed version (ground truth):
/** 
 * Sends an ack back to the GUESS client node.  
 */
protected void sendAcknowledgement(DatagramPacket datagram,byte[] guid){
  ConnectionManager manager=RouterService.getConnectionManager();
  Endpoint host=manager.getConnectedGUESSUltrapeer();
  PingReply reply;
  if (host != null) {
    try {
      reply=PingReply.createGUESSReply(guid,(byte)1,host);
    }
 catch (    UnknownHostException e) {
      reply=createPingReply(guid);
    }
  }
 else {
    reply=createPingReply(guid);
  }
  if (reply == null)   return;
  try {
    UDPService.instance().send(reply,datagram.getAddress(),datagram.getPort());
  }
 catch (  IOException ioe) {
    ErrorService.error(ioe,"String_Node_Str" + datagram.getAddress() + "String_Node_Str"+ datagram.getPort());
  }
  if (RECORD_STATS)   SentMessageStatHandler.UDP_PING_REPLIES.addMessage(reply);
}
Program: 4576
Project: 4576
Buggy source:
/** 
 * Uses the push route table to send a push request to the appropriate connection.  Since this is used for PushRequests orginating here, no stats are updated.
 * @throws IOException if no appropriate route exists.
 */
public void sendPushRequest(PushRequest push) throws IOException {
  if (push == null) {
    throw new NullPointerException("String_Node_Str");
  }
  ReplyHandler replyHandler=_pushRouteTable.getReplyHandler(push.getClientGUID());
  if (replyHandler != null)   replyHandler.handlePushRequest(push,null);
 else   throw new IOException("String_Node_Str");
}

Fixed version (ground truth):
/** 
 * Uses the push route table to send a push request to the appropriate connection.  Since this is used for PushRequests orginating here, no stats are updated.
 * @throws IOException if no appropriate route exists.
 */
public void sendPushRequest(PushRequest push) throws IOException {
  if (push == null) {
    throw new NullPointerException("String_Node_Str");
  }
  ReplyHandler replyHandler=_pushRouteTable.getReplyHandler(push.getClientGUID());
  if (replyHandler != null)   replyHandler.handlePushRequest(push,FOR_ME_REPLY_HANDLER);
 else   throw new IOException("String_Node_Str");
}
Program: 4577
Project: 4577
Buggy source:
/** 
 * Notifies components that this' IP address has changed.
 */
public static boolean addressChanged(){
  if (!NetworkUtils.isValidAddress(getAddress()))   return false;
  if (!NetworkUtils.isValidPort(getPort()))   return false;
  FileDesc[] fds=fileManager.getAllSharedFileDescriptors();
  for (int i=0; i < fds.length; i++)   fds[i].addUrnsForSelf();
  return true;
}

Fixed version (ground truth):
/** 
 * Notifies components that this' IP address has changed.
 */
public static boolean addressChanged(){
  byte addr[]=getAddress();
  if (!NetworkUtils.isValidAddress(addr))   return false;
  if (NetworkUtils.isPrivateAddress(addr))   return false;
  if (!NetworkUtils.isValidPort(getPort()))   return false;
  FileDesc[] fds=fileManager.getAllSharedFileDescriptors();
  for (int i=0; i < fds.length; i++)   fds[i].addUrnsForSelf();
  return true;
}
Program: 4578
Project: 4578
Buggy source:
protected boolean respondToQueryRequest(QueryRequest queryRequest,byte[] clientGUID){
  Response[] responses=RouterService.getFileManager().query(queryRequest);
  if (RouterService.isShieldedLeaf() && queryRequest.isTCP()) {
    if (RECORD_STATS) {
      if (responses != null && responses.length > 0)       RoutedQueryStat.LEAF_HIT.incrementStat();
 else       RoutedQueryStat.LEAF_FALSE_POSITIVE.incrementStat();
    }
  }
  return sendResponses(responses,queryRequest);
}

Fixed version (ground truth):
protected boolean respondToQueryRequest(QueryRequest queryRequest,byte[] clientGUID){
  if (!NetworkUtils.isValidPort(RouterService.getPort()) || !NetworkUtils.isValidAddress(RouterService.getAddress()))   return false;
  Response[] responses=RouterService.getFileManager().query(queryRequest);
  if (RouterService.isShieldedLeaf() && queryRequest.isTCP()) {
    if (RECORD_STATS) {
      if (responses != null && responses.length > 0)       RoutedQueryStat.LEAF_HIT.incrementStat();
 else       RoutedQueryStat.LEAF_FALSE_POSITIVE.incrementStat();
    }
  }
  return sendResponses(responses,queryRequest);
}
Program: 4579
Project: 4579
Buggy source:
/** 
 * Constructor that sets the ip and port to reply to.
 * @param ip the <tt>InetAddress</tt> to reply to
 * @param port the port to reply to
 */
public UDPReplyHandler(InetAddress ip,int port){
  IP=ip;
  PORT=port;
}

Fixed version (ground truth):
/** 
 * Constructor that sets the ip and port to reply to.
 * @param ip the <tt>InetAddress</tt> to reply to
 * @param port the port to reply to
 */
public UDPReplyHandler(InetAddress ip,int port){
  if (!NetworkUtils.isValidPort(port))   throw new IllegalArgumentException("String_Node_Str" + port);
  if (!NetworkUtils.isValidAddress(ip))   throw new IllegalArgumentException("String_Node_Str" + ip);
  IP=ip;
  PORT=port;
}
Program: 4580
Project: 4580
Buggy source:
/** 
 * Sends the <tt>Message</tt> via UDP to the port and IP address specified. This method should not be called if the client is not GUESS enabled.
 * @param msg  the <tt>Message</tt> to send
 * @param ip   the <tt>InetAddress</tt> to send to
 * @param port the port to send to
 */
public synchronized void send(Message msg,InetAddress ip,int port) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    msg.write(baos);
  }
 catch (  IOException e) {
    ErrorService.error(e);
    return;
  }
  byte[] data=baos.toByteArray();
  DatagramPacket dg=new DatagramPacket(data,data.length,ip,port);
synchronized (_sendLock) {
    if (_socket == null)     return;
    try {
      _socket.send(dg);
    }
 catch (    BindException be) {
      return;
    }
catch (    IOException ioe) {
      if ("String_Node_Str".equals(ioe.getMessage()))       return;
      throw ioe;
    }
  }
}

Fixed version (ground truth):
/** 
 * Sends the <tt>Message</tt> via UDP to the port and IP address specified. This method should not be called if the client is not GUESS enabled. If sending fails for reasons such as a BindException, NoRouteToHostException or specific IOExceptions such as "No buffer space available", this message is silently dropped.
 * @param msg  the <tt>Message</tt> to send
 * @param ip   the <tt>InetAddress</tt> to send to
 * @param port the port to send to
 */
public synchronized void send(Message msg,InetAddress ip,int port) throws IOException {
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  try {
    msg.write(baos);
  }
 catch (  IOException e) {
    ErrorService.error(e);
    return;
  }
  byte[] data=baos.toByteArray();
  DatagramPacket dg=new DatagramPacket(data,data.length,ip,port);
synchronized (_sendLock) {
    if (_socket == null)     return;
    try {
      _socket.send(dg);
    }
 catch (    BindException be) {
      return;
    }
catch (    NoRouteToHostException nrthe) {
      return;
    }
catch (    IOException ioe) {
      if ("String_Node_Str".equals(ioe.getMessage()))       return;
      throw ioe;
    }
  }
}
Program: 4583
Project: 4583
Buggy source:
/** 
 * Constructs a new URN based on the specified <tt>File</tt> instance. The constructor calculates the SHA1 value for the file, and is a costly operation as a result.
 * @param file the <tt>File</tt> instance to construct the URN from
 * @param urnType the type of URN to construct for the <tt>File</tt>instance, such as SHA1_URN
 */
private URN(final String urnString,final UrnType urnType){
  this._urnString=urnString;
  this._urnType=urnType;
}

Fixed version (ground truth):
/** 
 * Constructs a new URN based on the specified <tt>File</tt> instance. The constructor calculates the SHA1 value for the file, and is a costly operation as a result.
 * @param file the <tt>File</tt> instance to construct the URN from
 * @param urnType the type of URN to construct for the <tt>File</tt>instance, such as SHA1_URN
 */
private URN(final String urnString,final UrnType urnType){
  int lastColon=urnString.lastIndexOf("String_Node_Str");
  String nameSpace=urnString.substring(0,lastColon + 1);
  String hash=urnString.substring(lastColon + 1);
  this._urnString=nameSpace.toLowerCase() + hash.toUpperCase();
  this._urnType=urnType;
}
Program: 4584
Project: 4584
Buggy source:
/** 
 * The idea is that this is smaller than any AlternateLocation who has a greater value of _count. There is one exception to this rule -- a demoted AlternateLocation has a higher value irrespective of count. <p>  This is because we want to have a sorted set of AlternateLocation where any demoted AlternateLocation is put  at the end of the list because it probably does not work.   <p>  Further we want to get AlternateLocations with smaller counts to be propogated more, since this will serve to get better load balancing of uploader. 
 */
public int compareTo(Object obj){
  if (this == obj)   return 0;
  if (obj == null)   return 1;
  if (!(obj instanceof AlternateLocation))   return 1;
  AlternateLocation other=(AlternateLocation)obj;
  if (_demoted != other._demoted) {
    if (_demoted)     return 1;
    return -1;
  }
  int ret=_count - other._count;
  if (ret != 0)   return ret;
  if (this.URL.equals(other.URL))   return 0;
  ret=this.URL.getHost().compareTo(other.URL.getHost());
  if (ret != 0)   return ret;
  return (this.URL.getPort() - other.URL.getPort());
}

Fixed version (ground truth):
/** 
 * The idea is that this is smaller than any AlternateLocation who has a greater value of _count. There is one exception to this rule -- a demoted AlternateLocation has a higher value irrespective of count. <p>  This is because we want to have a sorted set of AlternateLocation where any demoted AlternateLocation is put  at the end of the list because it probably does not work.   <p>  Further we want to get AlternateLocations with smaller counts to be propogated more, since this will serve to get better load balancing of uploader. 
 */
public int compareTo(Object obj){
  if (this == obj)   return 0;
  if (obj == null)   return 1;
  if (!(obj instanceof AlternateLocation))   return 1;
  AlternateLocation other=(AlternateLocation)obj;
  if (_demoted != other._demoted) {
    if (_demoted)     return 1;
    return -1;
  }
  int ret=_count - other._count;
  if (ret != 0)   return ret;
  ret=this.URL.getHost().compareTo(other.URL.getHost());
  if (ret != 0)   return ret;
  ret=(this.URL.getPort() - other.URL.getPort());
  if (ret != 0)   return ret;
  ret=SHA1_URN.hashCode() - other.SHA1_URN.hashCode();
  if (ret != 0)   return ret;
  return URL.getProtocol().hashCode() - other.URL.getProtocol().hashCode();
}
Program: 4585
Project: 4585
Buggy source:
/** 
 * Overrides the hashCode method of Object to meet the contract of  hashCode.  Since we override equals, it is necessary to also  override hashcode to ensure that two "equal" alternate locations return the same hashCode, less we unleash unknown havoc on the hash-based collections.
 * @return a hash code value for this object
 */
public int hashCode(){
  if (hashCode == 0)   hashCode=37 * this.URL.hashCode();
  return hashCode;
}

Fixed version (ground truth):
/** 
 * Overrides the hashCode method of Object to meet the contract of  hashCode.  Since we override equals, it is necessary to also  override hashcode to ensure that two "equal" alternate locations return the same hashCode, less we unleash unknown havoc on the hash-based collections.
 * @return a hash code value for this object
 */
public int hashCode(){
  if (hashCode == 0) {
    int result=17;
    result=(37 * result) + this.URL.getHost().hashCode();
    result=(37 * result) + this.URL.getPort();
    result=(37 * result) + this.SHA1_URN.hashCode();
    result=(37 * result) + this.URL.getProtocol().hashCode();
    hashCode=result;
  }
  return hashCode;
}
Program: 4586
Project: 4586
Buggy source:
/** 
 * Overrides the equals method to accurately compare  <tt>AlternateLocation</tt> instances.  <tt>AlternateLocation</tt>s  are equal if their <tt>URL</tt>s are equal.
 * @param obj the <tt>Object</tt> instance to compare to
 * @return <tt>true</tt> if the <tt>URL</tt> of this<tt>AlternateLocation</tt> is equal to the <tt>URL</tt> of the <tt>AlternateLocation</tt> location argument, and otherwise returns <tt>false</tt>
 */
public boolean equals(Object obj){
  if (obj == this)   return true;
  if (!(obj instanceof AlternateLocation))   return false;
  AlternateLocation al=(AlternateLocation)obj;
  return URL == null ? al.URL == null : URL.equals(al.URL);
}

Fixed version (ground truth):
/** 
 * Overrides the equals method to accurately compare  <tt>AlternateLocation</tt> instances.  <tt>AlternateLocation</tt>s  are equal if their <tt>URL</tt>s are equal.
 * @param obj the <tt>Object</tt> instance to compare to
 * @return <tt>true</tt> if the <tt>URL</tt> of this<tt>AlternateLocation</tt> is equal to the <tt>URL</tt> of the <tt>AlternateLocation</tt> location argument, and otherwise returns <tt>false</tt>
 */
public boolean equals(Object obj){
  if (obj == this)   return true;
  if (!(obj instanceof AlternateLocation))   return false;
  AlternateLocation other=(AlternateLocation)obj;
  return (URL.getHost().equals(other.URL.getHost()) && URL.getPort() == other.URL.getPort() && SHA1_URN.equals(other.SHA1_URN) && URL.getProtocol().equals(other.URL.getProtocol()));
}
Program: 4587
Project: 4587
Buggy source:
/** 
 * Creates a new <tt>URL</tt> instance based on the URL specified in the alternate location header.
 * @param locationHeader the alternate location header from an HTTPheader
 * @return a new <tt>URL</tt> instance for the URL in the alternatelocation header
 * @throws <tt>IOException</tt> if the url could not be extracted fromthe header in the expected format
 * @throws <tt>MalformedURLException</tt> if the enclosed URL is notformatted correctly
 */
private static URL createUrl(final String locationHeader) throws IOException {
  String test=locationHeader.toLowerCase();
  if (!test.startsWith("String_Node_Str"))   throw new IOException("String_Node_Str" + locationHeader);
  if (test.lastIndexOf("String_Node_Str") > 4)   throw new IOException("String_Node_Str" + locationHeader);
  String urlStr=AlternateLocation.removeTimestamp(locationHeader);
  URL url=new URL(urlStr);
  String host=url.getHost();
  if (host == null || host.equals("String_Node_Str"))   throw new IOException("String_Node_Str" + locationHeader);
  if (url.getPort() == -1)   url=new URL("String_Node_Str",url.getHost(),80,url.getFile());
  return url;
}

Fixed version (ground truth):
/** 
 * Creates a new <tt>URL</tt> instance based on the URL specified in the alternate location header.
 * @param locationHeader the alternate location header from an HTTPheader
 * @return a new <tt>URL</tt> instance for the URL in the alternatelocation header
 * @throws <tt>IOException</tt> if the url could not be extracted fromthe header in the expected format
 * @throws <tt>MalformedURLException</tt> if the enclosed URL is notformatted correctly
 */
private static URL createUrl(final String locationHeader) throws IOException {
  String locHeader=locationHeader.toLowerCase();
  if (!locHeader.startsWith("String_Node_Str"))   throw new IOException("String_Node_Str" + locationHeader);
  if (locHeader.lastIndexOf("String_Node_Str") > 4)   throw new IOException("String_Node_Str" + locationHeader);
  String urlStr=AlternateLocation.removeTimestamp(locHeader);
  URL url=new URL(urlStr);
  String host=url.getHost();
  if (host == null || host.equals("String_Node_Str"))   throw new IOException("String_Node_Str" + locationHeader);
  if (url.getPort() == -1)   url=new URL("String_Node_Str",url.getHost(),80,url.getFile());
  return url;
}
Program: 4591
Project: 4591
Buggy source:
/** 
 * Returns true if this incoming connections should be rejected with a 503. 
 */
private boolean reject(HandshakeResponse response){
  boolean allowedNow=_manager.allowConnection(response);
  if (allowedNow)   return false;
  boolean allowedAsLeaf=_manager.allowConnectionAsLeaf(response);
  return !(response.isUltrapeer() && allowedAsLeaf);
}

Fixed version (ground truth):
/** 
 * Returns true if this incoming connections should be rejected with a 503. 
 */
private boolean reject(HandshakeResponse response){
  boolean allowedNow=_manager.allowConnection(response);
  if (allowedNow)   return false;
  if (!response.isUltrapeer())   return true;
  return !_manager.allowConnectionAsLeaf(response);
}
Program: 4592
Project: 4592
Buggy source:
/** 
 * Respond to an outgoing connection request.
 * @param response the headers read from the connection
 */
private HandshakeResponse respondToOutgoing(HandshakeResponse response){
  if (!_manager.allowConnection(response)) {
    return HandshakeResponse.createRejectOutgoingResponse();
  }
  Properties ret=new Properties();
  if (response.hasLeafGuidance() && isNotBearshare(response) && _manager.allowLeafDemotion()) {
    ret.put(HeaderNames.X_ULTRAPEER,"String_Node_Str");
  }
  if (response.isDeflateAccepted()) {
    ret.put(HeaderNames.CONTENT_ENCODING,HeaderNames.DEFLATE_VALUE);
  }
  return HandshakeResponse.createAcceptOutgoingResponse(ret);
}

Fixed version (ground truth):
/** 
 * Respond to an outgoing connection request.
 * @param response the headers read from the connection
 */
private HandshakeResponse respondToOutgoing(HandshakeResponse response){
  if (!response.isUltrapeer())   return HandshakeResponse.createRejectOutgoingResponse();
  if (!_manager.allowConnection(response)) {
    return HandshakeResponse.createRejectOutgoingResponse();
  }
  Properties ret=new Properties();
  if (response.hasLeafGuidance() && isNotBearshare(response) && _manager.allowLeafDemotion()) {
    ret.put(HeaderNames.X_ULTRAPEER,"String_Node_Str");
  }
  if (response.isDeflateAccepted()) {
    ret.put(HeaderNames.CONTENT_ENCODING,HeaderNames.DEFLATE_VALUE);
  }
  return HandshakeResponse.createAcceptOutgoingResponse(ret);
}
Program: 4593
Project: 4593
Buggy source:
/** 
 * Returns the number of connections we should try depending on our speed, and how many downloaders we have active now.
 */
private synchronized int getNumAllowedDownloads(){
  int downloads=threads.size();
  int capacity=ConnectionSettings.CONNECTION_SPEED.getValue();
  if (capacity <= SpeedConstants.MODEM_SPEED_INT)   return Math.max(2 - downloads,0);
 else   if (capacity <= SpeedConstants.T1_SPEED_INT)   return Math.max(6 - downloads,0);
 else   return Math.max(8 - downloads,0);
}

Fixed version (ground truth):
/** 
 * Returns the number of connections we should try depending on our speed, and how many downloaders we have active now.
 */
private synchronized int getNumAllowedDownloads(){
  int downloads=threads.size();
  return Math.max(getSwarmCapacity() - downloads,0);
}
Program: 4594
Project: 4594
Buggy source:
public void open(File file,ManagedDownloader md) throws IOException {
  this.managedDownloader=md;
  File parentFile=FileUtils.getParentFile(file);
  FileUtils.setWriteable(parentFile);
  FileUtils.setWriteable(file);
  this.fos=new RandomAccessFile(file,"String_Node_Str");
}

Fixed version (ground truth):
public void open(File file,ManagedDownloader md) throws IOException {
  this.managedDownloader=md;
  File parentFile=FileUtils.getParentFile(file);
  if (parentFile != null)   FileUtils.setWriteable(parentFile);
  FileUtils.setWriteable(file);
  this.fos=new RandomAccessFile(file,"String_Node_Str");
}
Program: 4596
Project: 4596
Buggy source:
/** 
 * Utility method to set a file as non read only. If the file is already writable, does nothing.
 * @param f the <tt>File</tt> instance whose read only flag shouldbe unset.
 */
public static boolean setWriteable(File f){
  if (f.canWrite())   return true;
  String fName;
  try {
    fName=f.getCanonicalPath();
  }
 catch (  IOException ioe) {
    fName=f.getPath();
  }
  String cmds[]=null;
  if (CommonUtils.isWindows())   cmds=new String[]{"String_Node_Str","String_Node_Str",fName};
 else   if (CommonUtils.isMacClassic())   cmds=null;
 else   cmds=new String[]{"String_Node_Str","String_Node_Str",fName};
  if (cmds != null) {
    try {
      Process p=Runtime.getRuntime().exec(cmds);
      p.waitFor();
    }
 catch (    SecurityException ignored) {
    }
catch (    IOException ignored) {
    }
catch (    InterruptedException ignored) {
    }
  }
  return f.canWrite();
}

Fixed version (ground truth):
/** 
 * Utility method to set a file as non read only. If the file is already writable, does nothing.
 * @param f the <tt>File</tt> instance whose read only flag shouldbe unset.
 */
public static boolean setWriteable(File f){
  if (f.canWrite() || !f.exists())   return true;
  String fName;
  try {
    fName=f.getCanonicalPath();
  }
 catch (  IOException ioe) {
    fName=f.getPath();
  }
  if (UNWRITEABLE.contains(fName))   return false;
  String cmds[]=null;
  if (CommonUtils.isWindows())   cmds=new String[]{"String_Node_Str","String_Node_Str",fName};
 else   if (CommonUtils.isMacClassic())   cmds=null;
 else   cmds=new String[]{"String_Node_Str","String_Node_Str",fName};
  if (cmds != null) {
    try {
      Process p=Runtime.getRuntime().exec(cmds);
      p.waitFor();
    }
 catch (    SecurityException ignored) {
    }
catch (    IOException ignored) {
    }
catch (    InterruptedException ignored) {
    }
  }
  if (!f.canWrite()) {
    UNWRITEABLE.add(fName);
    return false;
  }
 else   return true;
}
Program: 4597
Project: 4597
Buggy source:
/** 
 * Returns a new socket to the given host/port.  If the socket couldn't be established withing timeout milliseconds, throws IOException.  If timeout==0, no timeout occurs.  If this thread is interrupted while making connection, throws IOException.
 * @requires connect has only been called once, no other thread callingconnect.  Timeout must be non-negative.  
 */
public synchronized Socket connect(int timeout) throws IOException {
  Thread t=new Thread(new SocketOpenerThread(),"String_Node_Str");
  t.setDaemon(true);
  t.start();
  try {
    this.wait(timeout);
  }
 catch (  InterruptedException e) {
    if (socket == null)     timedOut=true;
 else     try {
      socket.close();
    }
 catch (    IOException e2) {
    }
    throw new IOException();
  }
  if (!completed)   t.stop();
  if (socket != null) {
    return socket;
  }
 else {
    timedOut=true;
    throw new IOException();
  }
}

Fixed version (ground truth):
/** 
 * Returns a new socket to the given host/port.  If the socket couldn't be established withing timeout milliseconds, throws IOException.  If timeout==0, no timeout occurs.  If this thread is interrupted while making connection, throws IOException.
 * @requires connect has only been called once, no other thread callingconnect.  Timeout must be non-negative.  
 */
public synchronized Socket connect(int timeout) throws IOException {
  Thread t=new Thread(new SocketOpenerThread(),"String_Node_Str");
  t.setDaemon(true);
  t.start();
  try {
    this.wait(timeout);
  }
 catch (  InterruptedException e) {
    if (socket == null)     timedOut=true;
 else     try {
      socket.close();
    }
 catch (    IOException e2) {
    }
    throw new IOException();
  }
  if (!completed)   t.interrupt();
  if (socket != null) {
    return socket;
  }
 else {
    timedOut=true;
    throw new IOException();
  }
}
Program: 4598
Project: 4598
Buggy source:
/** 
 * Reads a message from the network and updates the appropriate statistics.
 */
private Message readAndUpdateStatistics() throws IOException, BadPacketException {
  int pCompressed=0, pUncompressed=0;
  Message msg=null;
  try {
    if (isReadDeflated()) {
      pCompressed=_inflater.getTotalIn();
      pUncompressed=_inflater.getTotalOut();
    }
    try {
      msg=Message.read(_in,HEADER_BUF,Message.N_TCP,_softMax);
    }
 catch (    IOException ioe) {
      close();
      throw ioe;
    }
    if (isReadDeflated()) {
      _compressedBytesReceived=_inflater.getTotalIn();
      _bytesReceived=_inflater.getTotalOut();
      if (!CommonUtils.isJava118()) {
        CompressionStat.GNUTELLA_UNCOMPRESSED_DOWNSTREAM.addData((int)(_inflater.getTotalOut() - pUncompressed));
        CompressionStat.GNUTELLA_COMPRESSED_DOWNSTREAM.addData((int)(_inflater.getTotalIn() - pCompressed));
      }
    }
 else     if (msg != null) {
      _bytesReceived+=msg.getTotalLength();
    }
  }
 catch (  NullPointerException npe) {
    throw CONNECTION_CLOSED;
  }
  return msg;
}

Fixed version (ground truth):
/** 
 * Reads a message from the network and updates the appropriate statistics.
 */
private Message readAndUpdateStatistics() throws IOException, BadPacketException {
  int pCompressed=0, pUncompressed=0;
  Message msg=null;
  try {
    if (isReadDeflated()) {
      pCompressed=_inflater.getTotalIn();
      pUncompressed=_inflater.getTotalOut();
    }
    msg=Message.read(_in,HEADER_BUF,Message.N_TCP,_softMax);
    if (isReadDeflated()) {
      _compressedBytesReceived=_inflater.getTotalIn();
      _bytesReceived=_inflater.getTotalOut();
      if (!CommonUtils.isJava118()) {
        CompressionStat.GNUTELLA_UNCOMPRESSED_DOWNSTREAM.addData((int)(_inflater.getTotalOut() - pUncompressed));
        CompressionStat.GNUTELLA_COMPRESSED_DOWNSTREAM.addData((int)(_inflater.getTotalIn() - pCompressed));
      }
    }
 else     if (msg != null) {
      _bytesReceived+=msg.getTotalLength();
    }
  }
 catch (  NullPointerException npe) {
    throw CONNECTION_CLOSED;
  }
  return msg;
}
Program: 4599
Project: 4599
Buggy source:
/** 
 * Sends a message.  The message may be buffered, so call flush() to guarantee that the message is sent synchronously.  This method is NOT thread-safe. Behavior is undefined if two threads are in a send call at the same time for a given connection.
 * @requires this is fully initialized
 * @modifies the network underlying this
 * @effects send m on the network.  Throws IOException if problemsarise.
 */
public void send(Message m) throws IOException {
  long priorCompressed=0, priorUncompressed=0;
  try {
    if (isWriteDeflated()) {
      priorUncompressed=_deflater.getTotalIn();
      priorCompressed=_deflater.getTotalOut();
    }
    try {
      m.write(_out);
    }
 catch (    IOException ioe) {
      close();
      throw ioe;
    }
    updateWriteStatistics(m,priorUncompressed,priorCompressed);
  }
 catch (  NullPointerException e) {
    throw CONNECTION_CLOSED;
  }
}

Fixed version (ground truth):
/** 
 * Sends a message.  The message may be buffered, so call flush() to guarantee that the message is sent synchronously.  This method is NOT thread-safe. Behavior is undefined if two threads are in a send call at the same time for a given connection.
 * @requires this is fully initialized
 * @modifies the network underlying this
 * @effects send m on the network.  Throws IOException if problemsarise.
 */
public void send(Message m) throws IOException {
  long priorCompressed=0, priorUncompressed=0;
  try {
    if (isWriteDeflated()) {
      priorUncompressed=_deflater.getTotalIn();
      priorCompressed=_deflater.getTotalOut();
    }
    m.write(_out);
    updateWriteStatistics(m,priorUncompressed,priorCompressed);
  }
 catch (  NullPointerException e) {
    throw CONNECTION_CLOSED;
  }
}
Program: 4600
Project: 4600
Buggy source:
/** 
 * Flushes any buffered messages sent through the send method.
 */
public void flush() throws IOException {
  long priorCompressed=0, priorUncompressed=0;
  try {
    if (isWriteDeflated()) {
      priorUncompressed=_deflater.getTotalIn();
      priorCompressed=_deflater.getTotalOut();
    }
    try {
      _out.flush();
    }
 catch (    IOException ioe) {
      close();
      throw ioe;
    }
    updateWriteStatistics(null,priorUncompressed,priorCompressed);
  }
 catch (  NullPointerException npe) {
    throw CONNECTION_CLOSED;
  }
}

Fixed version (ground truth):
/** 
 * Flushes any buffered messages sent through the send method.
 */
public void flush() throws IOException {
  long priorCompressed=0, priorUncompressed=0;
  try {
    if (isWriteDeflated()) {
      priorUncompressed=_deflater.getTotalIn();
      priorCompressed=_deflater.getTotalOut();
    }
    _out.flush();
    updateWriteStatistics(null,priorUncompressed,priorCompressed);
  }
 catch (  NullPointerException npe) {
    throw CONNECTION_CLOSED;
  }
}
Program: 4601
Project: 4601
Buggy source:
/** 
 * Closes the Connection's socket and thus the connection itself.
 */
public void close(){
  _closed=true;
  if (_socket != null) {
    try {
      _socket.close();
    }
 catch (    IOException e) {
    }
  }
  if (_deflater != null)   _deflater.end();
  if (_inflater != null)   _inflater.end();
  if (_in != null) {
    try {
      _in.close();
    }
 catch (    IOException e) {
    }
  }
  if (_out != null) {
    try {
      _out.close();
    }
 catch (    IOException e) {
    }
  }
}

Fixed version (ground truth):
/** 
 * Closes the Connection's socket and thus the connection itself.
 */
public void close(){
  if (_closed)   return;
  _closed=true;
  if (_socket != null) {
    try {
      _socket.close();
    }
 catch (    IOException e) {
    }
  }
  if (_deflater != null)   _deflater.end();
  if (_inflater != null)   _inflater.end();
  if (_in != null) {
    try {
      _in.close();
    }
 catch (    IOException e) {
    }
  }
  if (_out != null) {
    try {
      _out.close();
    }
 catch (    IOException e) {
    }
  }
}
Program: 4602
Project: 4602
Buggy source:
/** 
 * Runs standard calls that should be made whenever a connection is fully established and should wait for messages.
 * @param conn the <tt>ManagedConnection</tt> instance to start
 * @throws <tt>IOException</tt> if there is an excpetion while loopingfor messages
 */
private void startConnection(ManagedConnection conn) throws IOException {
  Thread.currentThread().setName("String_Node_Str");
  try {
    if (conn.isGUESSUltrapeer()) {
      QueryUnicaster.instance().addUnicastEndpoint(conn.getInetAddress(),conn.getListeningPort());
    }
    conn.loopForMessages();
  }
  finally {
    remove(conn);
  }
}

Fixed version (ground truth):
/** 
 * Runs standard calls that should be made whenever a connection is fully established and should wait for messages.
 * @param conn the <tt>ManagedConnection</tt> instance to start
 * @throws <tt>IOException</tt> if there is an excpetion while loopingfor messages
 */
private void startConnection(ManagedConnection conn) throws IOException {
  Thread.currentThread().setName("String_Node_Str");
  if (conn.isGUESSUltrapeer()) {
    QueryUnicaster.instance().addUnicastEndpoint(conn.getInetAddress(),conn.getListeningPort());
  }
  conn.loopForMessages();
}
Program: 4603
Project: 4603
Buggy source:
/** 
 * While the connection is not closed, sends all data delay. 
 */
public void run(){
  try {
    while (true) {
      repOk();
      waitForQueued();
      sendQueued();
      repOk();
    }
  }
 catch (  IOException e) {
    _runnerDied=true;
  }
catch (  Throwable t) {
    _runnerDied=true;
    ErrorService.error(t);
  }
}

Fixed version (ground truth):
/** 
 * While the connection is not closed, sends all data delay. 
 */
public void run(){
  try {
    while (true) {
      repOk();
      waitForQueued();
      sendQueued();
      repOk();
    }
  }
 catch (  IOException e) {
    if (_manager != null)     _manager.remove(ManagedConnection.this);
    _runnerDied=true;
  }
catch (  Throwable t) {
    if (_manager != null)     _manager.remove(ManagedConnection.this);
    _runnerDied=true;
    ErrorService.error(t);
  }
}
Program: 4604
Project: 4604
Buggy source:
/** 
 * Override of receive to do MessageRouter stats and to properly shut down the connection on IOException
 */
public Message receive(int timeout) throws IOException, BadPacketException, InterruptedIOException {
  Message m=super.receive(timeout);
  addReceived();
  return m;
}

Fixed version (ground truth):
/** 
 * Override of receive to do MessageRouter stats and to properly shut down the connection on IOException
 */
public Message receive(int timeout) throws IOException, BadPacketException, InterruptedIOException {
  Message m=null;
  try {
    m=super.receive(timeout);
  }
 catch (  IOException e) {
    if (_manager != null)     _manager.remove(this);
    throw e;
  }
  addReceived();
  return m;
}
Program: 4605
Project: 4605
Buggy source:
public String toString(){
  return ("String_Node_Str" + getHost() + "String_Node_Str"+ getPort()+ "String_Node_Str"+ getFileName()+ "String_Node_Str"+ getSize()+ "String_Node_Str"+ getSpeed()+ "String_Node_Str"+ getSHA1Urn()+ "String_Node_Str"+ getQuality()+ "String_Node_Str"+ _replyToMulticast+ "String_Node_Str");
}

Fixed version (ground truth):
public String toString(){
  return ("String_Node_Str" + getHost() + "String_Node_Str"+ getPort()+ "String_Node_Str"+ getFileName()+ "String_Node_Str");
}
Program: 4606
Project: 4606
Buggy source:
/** 
 * Returns true if 'other' should be accepted as a new download location.
 */
protected boolean allowAddition(RemoteFileDesc other){
  if (!initDone) {
synchronized (matcher) {
      matcher.setIgnoreCase(true);
      matcher.setIgnoreWhitespace(true);
      matcher.setCompareBackwards(true);
    }
    initDone=true;
  }
  if (other.getQuality() < 1)   return false;
  final URN otherUrn=other.getSHA1Urn();
  final String otherName=other.getFileName();
  final long otherLength=other.getSize();
synchronized (this) {
    for (int i=0; i < allFiles.length; i++) {
      RemoteFileDesc rfd=(RemoteFileDesc)allFiles[i];
      final URN urn=rfd.getSHA1Urn();
      if (otherUrn != null && urn != null) {
        return otherUrn.equals(urn);
      }
      final String thisName=rfd.getFileName();
      final long thisLength=rfd.getSize();
      if (sizeClose(otherLength,thisLength))       if (namesClose(otherName,thisName))       return true;
    }
  }
  return false;
}

Fixed version (ground truth):
/** 
 * Returns true if 'other' should be accepted as a new download location.
 */
protected boolean allowAddition(RemoteFileDesc other){
  if (!initDone) {
synchronized (matcher) {
      matcher.setIgnoreCase(true);
      matcher.setIgnoreWhitespace(true);
      matcher.setCompareBackwards(true);
    }
    initDone=true;
  }
  if (other.getQuality() < 1)   return false;
  if (other.isFromAlternateLocation() && invalidAlts.containsKey(other))   return false;
  final URN otherUrn=other.getSHA1Urn();
  final String otherName=other.getFileName();
  final long otherLength=other.getSize();
synchronized (this) {
    for (int i=0; i < allFiles.length; i++) {
      RemoteFileDesc rfd=(RemoteFileDesc)allFiles[i];
      final URN urn=rfd.getSHA1Urn();
      if (otherUrn != null && urn != null) {
        return otherUrn.equals(urn);
      }
      final String thisName=rfd.getFileName();
      final long thisLength=rfd.getSize();
      if (sizeClose(otherLength,thisLength))       if (namesClose(otherName,thisName))       return true;
    }
  }
  return false;
}
Program: 4607
Project: 4607
Buggy source:
private synchronized void informMesh(RemoteFileDesc rfd,boolean good){
  if (!rfd.isAltLocCapable())   return;
  AlternateLocation loc=null;
  try {
    loc=AlternateLocation.create(rfd);
  }
 catch (  IOException iox) {
    return;
  }
  for (Iterator iter=dloaders.iterator(); iter.hasNext(); ) {
    HTTPDownloader httpDloader=(HTTPDownloader)iter.next();
    RemoteFileDesc r=httpDloader.getRemoteFileDesc();
    if (r.getHost() == rfd.getHost() && r.getPort() == rfd.getPort())     continue;
    if (good)     httpDloader.addSuccessfulAltLoc(loc);
 else     httpDloader.addFailedAltLoc(loc);
  }
  if (!good)   validAlts.remove(loc);
  if (RECORD_STATS && ("String_Node_Str".equals(rfd.getVendor()))) {
    if (good)     DownloadStat.ALTERNATE_WORKED.incrementStat();
 else     DownloadStat.ALTERNATE_NOT_ADDED.incrementStat();
  }
}

Fixed version (ground truth):
/** 
 * Notifies all existing HTTPDownloaders about this RFD. If good is true, it notifies them of a succesful alternate location, otherwise it notifies them of a failed alternate location. The internal validAlts is also updated if good is true, and invalidAlts is updated if good is false. The IncompleteFileDesc is also notified of new locations for this file.
 */
private synchronized void informMesh(RemoteFileDesc rfd,boolean good){
  if (!rfd.isAltLocCapable())   return;
  AlternateLocation loc=null;
  AlternateLocation forFD=null;
  try {
    loc=AlternateLocation.create(rfd);
    forFD=AlternateLocation.create(rfd);
  }
 catch (  IOException iox) {
    return;
  }
  for (Iterator iter=dloaders.iterator(); iter.hasNext(); ) {
    HTTPDownloader httpDloader=(HTTPDownloader)iter.next();
    RemoteFileDesc r=httpDloader.getRemoteFileDesc();
    if (r.getHost() == rfd.getHost() && r.getPort() == rfd.getPort())     continue;
    if (good)     httpDloader.addSuccessfulAltLoc(loc);
 else     httpDloader.addFailedAltLoc(loc);
  }
  FileDesc fd=fileManager.getFileDescForFile(incompleteFile);
  IncompleteFileDesc ifd=null;
  if (fd != null && fd instanceof IncompleteFileDesc)   ifd=(IncompleteFileDesc)fd;
  if (good) {
    if (RECORD_STATS && rfd.isFromAlternateLocation())     DownloadStat.ALTERNATE_WORKED.incrementStat();
    validAlts.add(loc);
    if (ifd != null)     ifd.addVerified(forFD);
  }
 else {
    if (RECORD_STATS && rfd.isFromAlternateLocation())     DownloadStat.ALTERNATE_NOT_ADDED.incrementStat();
    validAlts.remove(loc);
    if (ifd != null)     ifd.remove(forFD);
    invalidAlts.put(rfd,rfd);
  }
}
Program: 4608
Project: 4608
Buggy source:
/** 
 * Like addDownload, but doesn't call allowAddition(..). If cache is false, the RFD is not added to allFiles, but is added to the appropriate bucket. If the RFD matches one already in allFiles, the new one is NOT added to allFiles, but IS added the appropriate bucket if and only if a matching RFD is not currently in the bucket. If the file is ultimately added to buckets, either reqLock is released or this is notified. This ALWAYS returns true, because the download is either allowed or silently ignored (because we're already downloading or going to attempt to download from the host described in the RFD).
 */
protected final synchronized boolean addDownloadForced(RemoteFileDesc rfd,boolean cache){
  if (NetworkUtils.isMe(rfd.getHost(),rfd.getPort()))   return true;
  boolean exists=false;
  for (int i=0; i < allFiles.length; i++) {
    if (rfd.equals(allFiles[i])) {
      cache=false;
      exists=true;
      break;
    }
  }
  boolean added=false;
  if (buckets != null) {
    added=(buckets.add(rfd,exists) != -1);
  }
  if (cache) {
    RemoteFileDesc[] newAllFiles=new RemoteFileDesc[allFiles.length + 1];
    System.arraycopy(allFiles,0,newAllFiles,0,allFiles.length);
    newAllFiles[newAllFiles.length - 1]=rfd;
    allFiles=newAllFiles;
  }
  if (added) {
    if ((state == Downloader.WAITING_FOR_RETRY) || (state == Downloader.WAITING_FOR_RESULTS) || (state == Downloader.GAVE_UP)|| (state == Downloader.WAITING_FOR_USER))     reqLock.releaseDueToNewResults();
 else     this.notify();
  }
  return true;
}

Fixed version (ground truth):
/** 
 * Like addDownload, but doesn't call allowAddition(..). If cache is false, the RFD is not added to allFiles, but is added to the appropriate bucket. If the RFD matches one already in allFiles, the new one is NOT added to allFiles, but IS added the appropriate bucket if and only if a matching RFD is not currently in the bucket. If the file is ultimately added to buckets, either reqLock is released or this is notified. This ALWAYS returns true, because the download is either allowed or silently ignored (because we're already downloading or going to attempt to download from the host described in the RFD).
 */
protected final synchronized boolean addDownloadForced(RemoteFileDesc rfd,boolean cache){
  if (NetworkUtils.isMe(rfd.getHost(),rfd.getPort()))   return true;
  for (int i=0; i < allFiles.length; i++) {
    if (rfd.equals(allFiles[i])) {
      cache=false;
      break;
    }
  }
  boolean added=false;
  if (buckets != null) {
    added=(buckets.add(rfd,true) != -1);
  }
  if (cache) {
    RemoteFileDesc[] newAllFiles=new RemoteFileDesc[allFiles.length + 1];
    System.arraycopy(allFiles,0,newAllFiles,0,allFiles.length);
    newAllFiles[newAllFiles.length - 1]=rfd;
    allFiles=newAllFiles;
  }
  if (added) {
    if ((state == Downloader.WAITING_FOR_RETRY) || (state == Downloader.WAITING_FOR_RESULTS) || (state == Downloader.GAVE_UP)|| (state == Downloader.WAITING_FOR_USER))     reqLock.releaseDueToNewResults();
 else     this.notify();
  }
  return true;
}
Program: 4612
Project: 4612
Buggy source:
/** 
 * Initializes a ManagedDownloader read from disk. Also used for internally initializing or resuming a normal download; there is no need to explicitly call this method in that case. After the call, this is in the queued state, at least for the moment.
 * @requires this is uninitialized or stopped, and allFiles, and incompleteFileManager are set
 * @modifies everything but the above fields 
 * @param deserialized True if this downloader is being initialized after being read from disk, false otherwise.
 */
public void initialize(DownloadManager manager,FileManager fileManager,ActivityCallback callback,final boolean deserialized){
  this.manager=manager;
  this.fileManager=fileManager;
  this.callback=callback;
  dloaders=new LinkedList();
  threads=new ArrayList();
  chatList=new DownloadChatList();
  browseList=new DownloadBrowseHostList();
  stealLock=new Object();
  stopped=false;
  setState(QUEUED);
  miniRFDToLock=Collections.synchronizedMap(new HashMap());
  threadLockToSocket=Collections.synchronizedMap(new HashMap());
  corruptState=NOT_CORRUPT_STATE;
  corruptStateLock=new Object();
  numMeasures=0;
  averageBandwidth=0f;
  this.dloaderManagerThread=new Thread("String_Node_Str"){
    public void run(){
      try {
        tryAllDownloads(deserialized);
      }
 catch (      Throwable e) {
        ErrorService.error(e);
      }
    }
  }
;
  dloaderManagerThread.setDaemon(true);
  dloaderManagerThread.start();
}

Fixed version (ground truth):
/** 
 * Initializes a ManagedDownloader read from disk. Also used for internally initializing or resuming a normal download; there is no need to explicitly call this method in that case. After the call, this is in the queued state, at least for the moment.
 * @requires this is uninitialized or stopped, and allFiles, and incompleteFileManager are set
 * @modifies everything but the above fields 
 * @param deserialized True if this downloader is being initialized after being read from disk, false otherwise.
 */
public void initialize(DownloadManager manager,FileManager fileManager,ActivityCallback callback,final boolean deserialized){
  this.manager=manager;
  this.fileManager=fileManager;
  this.callback=callback;
  dloaders=new LinkedList();
  threads=new ArrayList();
  chatList=new DownloadChatList();
  browseList=new DownloadBrowseHostList();
  stealLock=new Object();
  stopped=false;
  setState(QUEUED);
  miniRFDToLock=Collections.synchronizedMap(new HashMap());
  threadLockToSocket=Collections.synchronizedMap(new HashMap());
  corruptState=NOT_CORRUPT_STATE;
  corruptStateLock=new Object();
  numMeasures=0;
  averageBandwidth=0f;
  invalidAlts=new FixedsizeForgetfulHashMap(100);
  this.dloaderManagerThread=new Thread("String_Node_Str"){
    public void run(){
      try {
        tryAllDownloads(deserialized);
      }
 catch (      Throwable e) {
        ErrorService.error(e);
      }
    }
  }
;
  dloaderManagerThread.setDaemon(true);
  dloaderManagerThread.start();
}
Program: 4613
Project: 4613
Buggy source:
/** 
 * Starts "uploading" the requested file.  The behavior of the upload, however, depends on the current upload state.  If the file was not found, for example, the upload sends a 404 Not Found message, whereas in the case of a normal upload, the file is transferred as expected.<p> This method also handles storing any newly discovered alternate  locations for this file in the corresponding <tt>FileDesc</tt>.  The new alternate locations are discovered through the requesting client's HTTP headers.<p> Implements the <tt>Uploader</tt> interface.
 */
public void writeResponse() throws IOException {
  try {
    _method.writeHttpResponse(_state,_ostream);
  }
 catch (  IOException e) {
    if (_amountRead < _amountRequested)     throw e;
  }
 finally {
    if (_fileDesc != null) {
synchronized (_badLocs) {
        Iterator iter=_badLocs.iterator();
        while (iter.hasNext()) {
          AlternateLocation loc=((AlternateLocation)iter.next()).createClone();
          Assert.that(loc != null,"String_Node_Str");
          _fileDesc.remove(loc);
        }
      }
synchronized (_goodLocs) {
        Iterator iter=_goodLocs.iterator();
        while (iter.hasNext()) {
          AlternateLocation loc=((AlternateLocation)iter.next()).createClone();
          Assert.that(loc != null,"String_Node_Str");
          _fileDesc.add(loc);
        }
      }
    }
  }
}

Fixed version (ground truth):
/** 
 * Starts "uploading" the requested file.  The behavior of the upload, however, depends on the current upload state.  If the file was not found, for example, the upload sends a 404 Not Found message, whereas in the case of a normal upload, the file is transferred as expected.<p> This method also handles storing any newly discovered alternate  locations for this file in the corresponding <tt>FileDesc</tt>.  The new alternate locations are discovered through the requesting client's HTTP headers.<p> Implements the <tt>Uploader</tt> interface.
 */
public void writeResponse() throws IOException {
  try {
    _method.writeHttpResponse(_state,_ostream);
  }
 catch (  IOException e) {
    if (_amountRead < _amountRequested)     throw e;
  }
 finally {
    if (_fileDesc != null) {
      if (_badLocs != null) {
synchronized (_badLocs) {
          Iterator iter=_badLocs.iterator();
          while (iter.hasNext()) {
            AlternateLocation loc=((AlternateLocation)iter.next()).createClone();
            Assert.that(loc != null,"String_Node_Str");
            _fileDesc.remove(loc);
          }
        }
      }
      if (_goodLocs != null) {
synchronized (_goodLocs) {
          Iterator iter=_goodLocs.iterator();
          while (iter.hasNext()) {
            AlternateLocation loc=((AlternateLocation)iter.next()).createClone();
            Assert.that(loc != null,"String_Node_Str");
            _fileDesc.add(loc);
          }
        }
      }
    }
  }
}