nus-yam/ex-repair huggingface dataset:
Program: 55091
Project: 55091
Buggy source:
@Test public void testPOSTWithWrongToken() throws IOException, ServletException {
  CSFRFilter filter=new CSFRFilter();
  MockHttpServletRequest request=new MockHttpServletRequest();
  request.setMethod("String_Node_Str");
  MockHttpServletResponse response=new MockHttpServletResponse();
  FilterChain chain=Mockito.mock(FilterChain.class);
  filter.init(filterConfig);
  filter.doFilterInternal(request,response,chain);
  Mockito.verify(chain).doFilter(request,response);
  request.setMethod("String_Node_Str");
  request.setParameter("String_Node_Str",response.getHeader("String_Node_Str"));
  request.getSession().setAttribute(CSRFToken.CSRF_TOKEN,"String_Node_Str");
  filter.doFilterInternal(request,response,chain);
  Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN,response.getStatus());
}

Fixed version (ground truth):
@Test public void testPOSTWithWrongToken() throws IOException, ServletException {
  CSFRFilter filter=new CSFRFilter();
  MockHttpServletRequest request=new MockHttpServletRequest();
  request.setMethod("String_Node_Str");
  MockHttpServletResponse response=new MockHttpServletResponse();
  FilterChain chain=Mockito.mock(FilterChain.class);
  filter.init(filterConfig);
  filter.doFilterInternal(request,response,chain);
  Mockito.verify(chain).doFilter(request,response);
  request.setMethod("String_Node_Str");
  request.setParameter("String_Node_Str",response.getHeader("String_Node_Str"));
  CSRFToken.setToken(request,"String_Node_Str");
  filter.doFilterInternal(request,response,chain);
  Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN,response.getStatus());
}
Program: 55092
Project: 55092
Buggy source:
@ExpectPermission(Permission.UPDATE_PROFILE) @RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public int updateUserProfile(UserWithPermission user,@RequestBody DisplayNameEmail toUpdate){
  int result=userRepository.updateProfile(user,toUpdate.getEmail(),toUpdate.getDisplayName(),toUpdate.isEmailNotification(),toUpdate.isSkipOwnNotifications());
  eventEmitter.emitUpdateUserProfile(user.getId());
  return result;
}

Fixed version (ground truth):
@ExpectPermission(Permission.UPDATE_PROFILE) @RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public int updateUserProfile(UserWithPermission user,@RequestBody DisplayNameEmail toUpdate){
  int result=userRepository.updateProfile(user,toUpdate.getEmail(),toUpdate.getDisplayName(),toUpdate.getEmailNotification(),toUpdate.getSkipOwnNotifications());
  eventEmitter.emitUpdateUserProfile(user.getId());
  return result;
}
Program: 55093
Project: 55093
Buggy source:
@Transactional(readOnly=false) public ImmutablePair<Boolean,CardData> createFile(String name,String digest,long fileSize,int cardId,InputStream content,String contentType,User user,Date time){
  if (!cardDataRepository.fileExists(digest)) {
    cardDataRepository.addUploadContent(digest,fileSize,content,contentType);
  }
  if (!cardDataRepository.isFileAvailableByCard(digest,cardId)) {
    CardData file=cardDataRepository.createData(cardId,CardType.FILE,digest);
    cardDataRepository.createUploadInfo(digest,name,name,file.getId());
    eventRepository.insertFileEvent(file.getId(),cardId,EventType.FILE_UPLOAD,user.getId(),file.getId(),name,time);
    return ImmutablePair.of(true,file);
  }
  return ImmutablePair.of(false,null);
}

Fixed version (ground truth):
@Transactional(readOnly=false) public ImmutablePair<Boolean,CardData> createFile(String name,String digest,long fileSize,int cardId,InputStream content,String contentType,User user,Date time){
  if (!cardDataRepository.fileExists(digest)) {
    cardDataRepository.addUploadContent(digest,fileSize,content,contentType);
  }
  if (!cardDataRepository.isFileAvailableByCard(digest,cardId)) {
    CardData file=cardDataRepository.createData(cardId,CardType.FILE,digest);
    cardDataRepository.createUploadInfo(digest,name,name,file.getId());
    eventRepository.insertFileEvent(file.getId(),cardId,EventType.FILE_UPLOAD,user.getId(),file.getId(),name,time);
    return ImmutablePair.of(true,file);
  }
  return ImmutablePair.<Boolean,CardData>of(false,null);
}
Program: 55094
Project: 55094
Buggy source:
private WebSecurityUser(io.lavagna.model.User user){
  this.id=user.getId();
  this.anonymous=user.isAnonymous();
}

Fixed version (ground truth):
private WebSecurityUser(io.lavagna.model.User user){
  this.id=user.getId();
  this.anonymous=user.getAnonymous();
}
Program: 55095
Project: 55095
Buggy source:
@Transactional(readOnly=false) public CardLabelValue addLabelValueToCard(CardLabel label,int cardId,LabelValue val){
  queries.addLabelValueToCard(cardId,label.isUnique() ? true : null,label.getId(),label.getType().toString(),val.getValueString(),val.getValueTimestamp(),val.getValueInt(),val.getValueCard(),val.getValueUser(),val.getValueList());
  return queries.findLastCreatedLabelValue();
}

Fixed version (ground truth):
@Transactional(readOnly=false) public CardLabelValue addLabelValueToCard(CardLabel label,int cardId,LabelValue val){
  queries.addLabelValueToCard(cardId,label.getUnique() ? true : null,label.getId(),label.getType().toString(),val.getValueString(),val.getValueTimestamp(),val.getValueInt(),val.getValueCard(),val.getValueUser(),val.getValueList());
  return queries.findLastCreatedLabelValue();
}
Program: 55096
Project: 55096
Buggy source:
private void importLabels(Path tempFile,Project createdProject,String projectNameDir){
  List<Pair<CardLabel,List<LabelListValueWithMetadata>>> labels=readObject(projectNameDir + "String_Node_Str",tempFile,new TypeToken<List<Pair<CardLabel,List<LabelListValueWithMetadata>>>>(){
  }
);
  for (  Pair<CardLabel,List<LabelListValueWithMetadata>> pLabel : labels) {
    CardLabel label=pLabel.getFirst();
    if (label.getDomain() == LabelDomain.USER) {
      cardLabelRepository.addLabel(createdProject.getId(),label.isUnique(),label.getType(),label.getDomain(),label.getName(),label.getColor());
    }
    if (label.getType() == LabelType.LIST && !pLabel.getSecond().isEmpty()) {
      CardLabel importedCl=cardLabelRepository.findLabelByName(createdProject.getId(),label.getName(),label.getDomain());
      for (      LabelListValueWithMetadata llv : pLabel.getSecond()) {
        LabelListValue addedLabeListValue=cardLabelRepository.addLabelListValue(importedCl.getId(),llv.getValue());
        if (llv.getMetadata() != null) {
          for (          Entry<String,String> metadataKV : llv.getMetadata().entrySet()) {
            cardLabelRepository.createLabelListMetadata(addedLabeListValue.getId(),metadataKV.getKey(),metadataKV.getValue());
          }
        }
      }
    }
  }
}

Fixed version (ground truth):
private void importLabels(Path tempFile,Project createdProject,String projectNameDir){
  List<Pair<CardLabel,List<LabelListValueWithMetadata>>> labels=readObject(projectNameDir + "String_Node_Str",tempFile,new TypeToken<List<Pair<CardLabel,List<LabelListValueWithMetadata>>>>(){
  }
);
  for (  Pair<CardLabel,List<LabelListValueWithMetadata>> pLabel : labels) {
    CardLabel label=pLabel.getFirst();
    if (label.getDomain() == LabelDomain.USER) {
      cardLabelRepository.addLabel(createdProject.getId(),label.getUnique(),label.getType(),label.getDomain(),label.getName(),label.getColor());
    }
    if (label.getType() == LabelType.LIST && !pLabel.getSecond().isEmpty()) {
      CardLabel importedCl=cardLabelRepository.findLabelByName(createdProject.getId(),label.getName(),label.getDomain());
      for (      LabelListValueWithMetadata llv : pLabel.getSecond()) {
        LabelListValue addedLabeListValue=cardLabelRepository.addLabelListValue(importedCl.getId(),llv.getValue());
        if (llv.getMetadata() != null) {
          for (          Entry<String,String> metadataKV : llv.getMetadata().entrySet()) {
            cardLabelRepository.createLabelListMetadata(addedLabeListValue.getId(),metadataKV.getKey(),metadataKV.getValue());
          }
        }
      }
    }
  }
}
Program: 55097
Project: 55097
Buggy source:
private void importMissingBoard(Project project,BoardInfo boardInfo,Path tempFile,ImportContext idMapping){
  Board createdBoard=boardRepository.createEmptyBoard(boardInfo.getName(),boardInfo.getShortName(),boardInfo.getDescription(),project.getId());
  boardRepository.updateBoard(createdBoard.getId(),createdBoard.getName(),createdBoard.getDescription(),boardInfo.isArchived());
  List<BoardColumn> boardColumns=readObject("String_Node_Str" + boardInfo.getShortName() + "String_Node_Str",tempFile,new TypeToken<List<BoardColumn>>(){
  }
);
  int boardId=boardRepository.findBoardIdByShortName(boardInfo.getShortName());
  Map<ColumnDefinition,BoardColumnDefinition> colsDef=projectService.findMappedColumnDefinitionsByProjectId(project.getId());
  for (  BoardColumn bc : boardColumns) {
    BoardColumn added=boardColumnRepository.addColumnToBoard(bc.getName(),colsDef.get(bc.getStatus()).getId(),bc.getLocation(),boardId);
    boardColumnRepository.updateOrder(added.getId(),bc.getOrder());
    idMapping.getColumns().put(bc.getId(),added.getId());
  }
  List<StatisticForExport> stats=readObject("String_Node_Str" + boardInfo.getShortName() + "String_Node_Str",tempFile,new TypeToken<List<StatisticForExport>>(){
  }
);
  for (  StatisticForExport stat : stats) {
    statisticsQuery.addFromImport(stat.getDate(),boardId,colsDef.get(stat.getColumnDefinition()).getId(),stat.getLocation().toString(),stat.getCount());
  }
}

Fixed version (ground truth):
private void importMissingBoard(Project project,BoardInfo boardInfo,Path tempFile,ImportContext idMapping){
  Board createdBoard=boardRepository.createEmptyBoard(boardInfo.getName(),boardInfo.getShortName(),boardInfo.getDescription(),project.getId());
  boardRepository.updateBoard(createdBoard.getId(),createdBoard.getName(),createdBoard.getDescription(),boardInfo.getArchived());
  List<BoardColumn> boardColumns=readObject("String_Node_Str" + boardInfo.getShortName() + "String_Node_Str",tempFile,new TypeToken<List<BoardColumn>>(){
  }
);
  int boardId=boardRepository.findBoardIdByShortName(boardInfo.getShortName());
  Map<ColumnDefinition,BoardColumnDefinition> colsDef=projectService.findMappedColumnDefinitionsByProjectId(project.getId());
  for (  BoardColumn bc : boardColumns) {
    BoardColumn added=boardColumnRepository.addColumnToBoard(bc.getName(),colsDef.get(bc.getStatus()).getId(),bc.getLocation(),boardId);
    boardColumnRepository.updateOrder(added.getId(),bc.getOrder());
    idMapping.getColumns().put(bc.getId(),added.getId());
  }
  List<StatisticForExport> stats=readObject("String_Node_Str" + boardInfo.getShortName() + "String_Node_Str",tempFile,new TypeToken<List<StatisticForExport>>(){
  }
);
  for (  StatisticForExport stat : stats) {
    statisticsQuery.addFromImport(stat.getDate(),boardId,colsDef.get(stat.getColumnDefinition()).getId(),stat.getLocation().toString(),stat.getCount());
  }
}
Program: 55098
Project: 55098
Buggy source:
/** 
 * Send email (if all the conditions are met) to the user.
 * @param userId
 * @param upTo
 * @param emailEnabled
 * @param mailConfig
 */
public void notifyUser(int userId,Date upTo,boolean emailEnabled,MailConfig mailConfig){
  Date lastSent=queries.lastEmailSent(userId);
  User user=userRepository.findById(userId);
  Date fromDate=ObjectUtils.firstNonNull(lastSent,DateUtils.addDays(upTo,-1));
  List<Event> events=user.isSkipOwnNotifications() ? queries.eventsForUserWithoutHisOwns(userId,fromDate,upTo) : queries.eventsForUser(userId,fromDate,upTo);
  if (!events.isEmpty() && mailConfig != null && mailConfig.isMinimalConfigurationPresent() && emailEnabled && user.canSendEmail()) {
    try {
      sendEmailToUser(user,events,mailConfig);
    }
 catch (    MustacheException|IOException|MailException e) {
      LOG.warn("String_Node_Str" + user.getId(),e);
    }
  }
  queries.updateSentEmailDate(upTo,userId);
}

Fixed version (ground truth):
/** 
 * Send email (if all the conditions are met) to the user.
 * @param userId
 * @param upTo
 * @param emailEnabled
 * @param mailConfig
 */
public void notifyUser(int userId,Date upTo,boolean emailEnabled,MailConfig mailConfig){
  Date lastSent=queries.lastEmailSent(userId);
  User user=userRepository.findById(userId);
  Date fromDate=ObjectUtils.firstNonNull(lastSent,DateUtils.addDays(upTo,-1));
  List<Event> events=user.getSkipOwnNotifications() ? queries.eventsForUserWithoutHisOwns(userId,fromDate,upTo) : queries.eventsForUser(userId,fromDate,upTo);
  if (!events.isEmpty() && mailConfig != null && mailConfig.getMinimalConfigurationPresent() && emailEnabled && user.canSendEmail()) {
    try {
      sendEmailToUser(user,events,mailConfig);
    }
 catch (    MustacheException|IOException|MailException e) {
      LOG.warn("String_Node_Str" + user.getId(),e);
    }
  }
  queries.updateSentEmailDate(upTo,userId);
}
Program: 55099
Project: 55099
Buggy source:
private void checkRoleCondition(String roleName,Set<Integer> usersId){
  if ("String_Node_Str".equals(roleName) && !usersId.isEmpty()) {
    Validate.isTrue(usersId.size() == 1);
    Validate.isTrue(userRepository.findById(usersId.iterator().next()).isAnonymous());
  }
}

Fixed version (ground truth):
private void checkRoleCondition(String roleName,Set<Integer> usersId){
  if ("String_Node_Str".equals(roleName) && !usersId.isEmpty()) {
    Validate.isTrue(usersId.size() == 1);
    Validate.isTrue(userRepository.findById(usersId.iterator().next()).getAnonymous());
  }
}
Program: 55100
Project: 55100
Buggy source:
private RoleAndPermissions(RoleAndPermission base){
  this.name=base.getRoleName();
  this.removable=base.isRemovable();
  this.hidden=base.isHidden();
  this.readOnly=base.isReadOnly();
}

Fixed version (ground truth):
private RoleAndPermissions(RoleAndPermission base){
  this.name=base.getRoleName();
  this.removable=base.getRemovable();
  this.hidden=base.getHidden();
  this.readOnly=base.getReadOnly();
}
Program: 55101
Project: 55101
Buggy source:
@Transactional(readOnly=false) public void createMissingRolesWithPermissions(Map<RoleAndPermission,Set<Permission>> rolesWithPermissions){
  Set<String> currentRoles=findAllRolesAndRelatedPermission().keySet();
  for (  Entry<RoleAndPermission,Set<Permission>> kv : rolesWithPermissions.entrySet()) {
    RoleAndPermission rp=kv.getKey();
    if (!currentRoles.contains(rp.getRoleName())) {
      queries.createFullRole(rp.getRoleName(),rp.isRemovable(),rp.isHidden(),rp.isHidden());
    }
    updatePermissionsToRole(new Role(rp.getRoleName()),kv.getValue());
  }
}

Fixed version (ground truth):
@Transactional(readOnly=false) public void createMissingRolesWithPermissions(Map<RoleAndPermission,Set<Permission>> rolesWithPermissions){
  Set<String> currentRoles=findAllRolesAndRelatedPermission().keySet();
  for (  Entry<RoleAndPermission,Set<Permission>> kv : rolesWithPermissions.entrySet()) {
    RoleAndPermission rp=kv.getKey();
    if (!currentRoles.contains(rp.getRoleName())) {
      queries.createFullRole(rp.getRoleName(),rp.getRemovable(),rp.getHidden(),rp.getHidden());
    }
    updatePermissionsToRole(new Role(rp.getRoleName()),kv.getValue());
  }
}
Program: 55102
Project: 55102
Buggy source:
@Transactional(readOnly=false) public void createMissingRolesWithPermissionForProjects(Map<Integer,Map<RoleAndPermission,Set<Permission>>> r){
  for (  Entry<Integer,Map<RoleAndPermission,Set<Permission>>> projIdToRolesAndPermissions : r.entrySet()) {
    int projectId=projIdToRolesAndPermissions.getKey();
    Set<String> currentRoles=findAllRolesAndRelatedPermissionInProjectId(projectId).keySet();
    for (    Entry<RoleAndPermission,Set<Permission>> kv : projIdToRolesAndPermissions.getValue().entrySet()) {
      RoleAndPermission rp=kv.getKey();
      if (!currentRoles.contains(rp.getRoleName())) {
        createFullRoleInProjectId(new Role(rp.getRoleName()),projectId,rp.isRemovable(),rp.isHidden(),rp.isReadOnly());
      }
      updatePermissionsToRoleInProjectId(new Role(rp.getRoleName()),kv.getValue(),projectId);
    }
  }
}

Fixed version (ground truth):
@Transactional(readOnly=false) public void createMissingRolesWithPermissionForProjects(Map<Integer,Map<RoleAndPermission,Set<Permission>>> r){
  for (  Entry<Integer,Map<RoleAndPermission,Set<Permission>>> projIdToRolesAndPermissions : r.entrySet()) {
    int projectId=projIdToRolesAndPermissions.getKey();
    Set<String> currentRoles=findAllRolesAndRelatedPermissionInProjectId(projectId).keySet();
    for (    Entry<RoleAndPermission,Set<Permission>> kv : projIdToRolesAndPermissions.getValue().entrySet()) {
      RoleAndPermission rp=kv.getKey();
      if (!currentRoles.contains(rp.getRoleName())) {
        createFullRoleInProjectId(new Role(rp.getRoleName()),projectId,rp.getRemovable(),rp.getHidden(),rp.getReadOnly());
      }
      updatePermissionsToRoleInProjectId(new Role(rp.getRoleName()),kv.getValue(),projectId);
    }
  }
}
Program: 55103
Project: 55103
Buggy source:
/** 
 * Bulk creation of projects. Will skip the project that already exists.
 * @param projects
 */
@Transactional(readOnly=false) public ImmutablePair<List<Project>,List<Project>> createMissing(List<Project> projects){
  List<Project> created=new ArrayList<>();
  List<Project> skipped=new ArrayList<>();
  Set<String> usedShortNames=new HashSet<>();
  for (  Project pi : findAll()) {
    usedShortNames.add(pi.getShortName());
  }
  for (  Project p : projects) {
    if (!usedShortNames.contains(p.getShortName())) {
      Project createdProject=create(p.getName(),p.getShortName(),p.getDescription());
      updateProject(createdProject.getId(),createdProject.getName(),createdProject.getDescription(),p.isArchived());
      created.add(createdProject);
    }
 else {
      skipped.add(p);
    }
  }
  return ImmutablePair.of(Collections.unmodifiableList(created),Collections.unmodifiableList(skipped));
}

Fixed version (ground truth):
/** 
 * Bulk creation of projects. Will skip the project that already exists.
 * @param projects
 */
@Transactional(readOnly=false) public ImmutablePair<List<Project>,List<Project>> createMissing(List<Project> projects){
  List<Project> created=new ArrayList<>();
  List<Project> skipped=new ArrayList<>();
  Set<String> usedShortNames=new HashSet<>();
  for (  Project pi : findAll()) {
    usedShortNames.add(pi.getShortName());
  }
  for (  Project p : projects) {
    if (!usedShortNames.contains(p.getShortName())) {
      Project createdProject=create(p.getName(),p.getShortName(),p.getDescription());
      updateProject(createdProject.getId(),createdProject.getName(),createdProject.getDescription(),p.getArchived());
      created.add(createdProject);
    }
 else {
      skipped.add(p);
    }
  }
  return ImmutablePair.of(Collections.unmodifiableList(created),Collections.unmodifiableList(skipped));
}
Program: 55104
Project: 55104
Buggy source:
private static SqlParameterSource prepareUserParameterSource(User user){
  return new MapSqlParameterSource("String_Node_Str",trimToNull(user.getProvider())).addValue("String_Node_Str",trimToNull(user.getUsername())).addValue("String_Node_Str",trimToNull(user.getEmail())).addValue("String_Node_Str",trimToNull(user.getDisplayName())).addValue("String_Node_Str",user.isEnabled()).addValue("String_Node_Str",user.isEmailNotification()).addValue("String_Node_Str",ObjectUtils.firstNonNull(user.getMemberSince(),new Date())).addValue("String_Node_Str",user.isSkipOwnNotifications()).addValue("String_Node_Str",user.getUserMetadataRaw());
}

Fixed version (ground truth):
private static SqlParameterSource prepareUserParameterSource(User user){
  return new MapSqlParameterSource("String_Node_Str",trimToNull(user.getProvider())).addValue("String_Node_Str",trimToNull(user.getUsername())).addValue("String_Node_Str",trimToNull(user.getEmail())).addValue("String_Node_Str",trimToNull(user.getDisplayName())).addValue("String_Node_Str",user.getEnabled()).addValue("String_Node_Str",user.getEmailNotification()).addValue("String_Node_Str",ObjectUtils.firstNonNull(user.getMemberSince(),new Date())).addValue("String_Node_Str",user.getSkipOwnNotifications()).addValue("String_Node_Str",user.getUserMetadataRaw());
}
Program: 55105
Project: 55105
Buggy source:
@Transactional(readOnly=false) public void createUser(UserToCreate userToCreate){
  requireNonNull(userToCreate);
  requireNonNull(userToCreate.getProvider());
  requireNonNull(userToCreate.getUsername());
  userRepository.createUser(userToCreate.getProvider(),userToCreate.getUsername(),userToCreate.getEmail(),userToCreate.getDisplayName(),userToCreate.isEnabled());
  if (userToCreate.getRoles() == null) {
    return;
  }
  User u=userRepository.findUserByName(userToCreate.getProvider(),userToCreate.getUsername());
  Set<Integer> userId=Collections.singleton(u.getId());
  for (  String r : userToCreate.getRoles()) {
    permissionService.assignRoleToUsers(new Role(r),userId);
  }
}

Fixed version (ground truth):
@Transactional(readOnly=false) public void createUser(UserToCreate userToCreate){
  requireNonNull(userToCreate);
  requireNonNull(userToCreate.getProvider());
  requireNonNull(userToCreate.getUsername());
  userRepository.createUser(userToCreate.getProvider(),userToCreate.getUsername(),userToCreate.getEmail(),userToCreate.getDisplayName(),userToCreate.getEnabled());
  if (userToCreate.getRoles() == null) {
    return;
  }
  User u=userRepository.findUserByName(userToCreate.getProvider(),userToCreate.getUsername());
  Set<Integer> userId=Collections.singleton(u.getId());
  for (  String r : userToCreate.getRoles()) {
    permissionService.assignRoleToUsers(new Role(r),userId);
  }
}
Program: 55106
Project: 55106
Buggy source:
@ExpectPermission(Permission.PROJECT_ADMINISTRATION) @RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public CardLabel addLabel(@PathVariable("String_Node_Str") String projectShortName,@RequestBody Label label){
  int projectId=projectService.findIdByShortName(projectShortName);
  CardLabel cl=cardLabelRepository.addLabel(projectId,label.isUnique(),label.getType(),LabelDomain.USER,label.getName(),label.getColor());
  eventEmitter.emitAddLabel(projectShortName);
  return cl;
}

Fixed version (ground truth):
@ExpectPermission(Permission.PROJECT_ADMINISTRATION) @RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public CardLabel addLabel(@PathVariable("String_Node_Str") String projectShortName,@RequestBody Label label){
  int projectId=projectService.findIdByShortName(projectShortName);
  CardLabel cl=cardLabelRepository.addLabel(projectId,label.getUnique(),label.getType(),LabelDomain.USER,label.getName(),label.getColor());
  eventEmitter.emitAddLabel(projectShortName);
  return cl;
}
Program: 55107
Project: 55107
Buggy source:
@RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public void updateRole(@PathVariable("String_Node_Str") String roleName,@RequestBody UpdateRole updateRole){
  RoleAndMetadata role=permissionService.findRoleByName(roleName);
  Validate.isTrue(!role.isReadOnly());
  permissionService.updatePermissionsToRole(new Role(roleName),updateRole.getPermissions());
  eventEmitter.emitUpdatePermissionsToRole();
}

Fixed version (ground truth):
@RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public void updateRole(@PathVariable("String_Node_Str") String roleName,@RequestBody UpdateRole updateRole){
  RoleAndMetadata role=permissionService.findRoleByName(roleName);
  Validate.isTrue(!role.getReadOnly());
  permissionService.updatePermissionsToRole(new Role(roleName),updateRole.getPermissions());
  eventEmitter.emitUpdatePermissionsToRole();
}
Program: 55108
Project: 55108
Buggy source:
@RequestMapping(value="String_Node_Str",method=RequestMethod.DELETE) public void deleteRole(@PathVariable("String_Node_Str") String roleName){
  RoleAndMetadata role=permissionService.findRoleByName(roleName);
  Validate.isTrue(role.isRemovable());
  permissionService.deleteRole(new Role(roleName));
  eventEmitter.emitDeleteRole();
}

Fixed version (ground truth):
@RequestMapping(value="String_Node_Str",method=RequestMethod.DELETE) public void deleteRole(@PathVariable("String_Node_Str") String roleName){
  RoleAndMetadata role=permissionService.findRoleByName(roleName);
  Validate.isTrue(role.getRemovable());
  permissionService.deleteRole(new Role(roleName));
  eventEmitter.emitDeleteRole();
}
Program: 55109
Project: 55109
Buggy source:
@RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public void updateRole(@PathVariable("String_Node_Str") String projectShortName,@PathVariable("String_Node_Str") String roleName,@RequestBody UpdateRole updateRole){
  int projectId=projectService.findIdByShortName(projectShortName);
  RoleAndMetadata role=permissionService.findRoleInProjectByName(projectId,roleName);
  Validate.isTrue(!role.isReadOnly());
  permissionService.updatePermissionsToRoleInProjectId(new Role(roleName),updateRole.getPermissions(),projectId);
  eventEmitter.emitUpdatePermissionsToRole(projectShortName);
}

Fixed version (ground truth):
@RequestMapping(value="String_Node_Str",method=RequestMethod.POST) public void updateRole(@PathVariable("String_Node_Str") String projectShortName,@PathVariable("String_Node_Str") String roleName,@RequestBody UpdateRole updateRole){
  int projectId=projectService.findIdByShortName(projectShortName);
  RoleAndMetadata role=permissionService.findRoleInProjectByName(projectId,roleName);
  Validate.isTrue(!role.getReadOnly());
  permissionService.updatePermissionsToRoleInProjectId(new Role(roleName),updateRole.getPermissions(),projectId);
  eventEmitter.emitUpdatePermissionsToRole(projectShortName);
}
Program: 55110
Project: 55110
Buggy source:
@RequestMapping(value="String_Node_Str",method=RequestMethod.DELETE) public void deleteRole(@PathVariable("String_Node_Str") String projectShortName,@PathVariable("String_Node_Str") String roleName){
  int projectId=projectService.findIdByShortName(projectShortName);
  RoleAndMetadata role=permissionService.findRoleInProjectByName(projectId,roleName);
  Validate.isTrue(role.isRemovable());
  permissionService.deleteRoleInProjectId(new Role(roleName),projectId);
  eventEmitter.emitDeleteRole(projectShortName);
}

Fixed version (ground truth):
@RequestMapping(value="String_Node_Str",method=RequestMethod.DELETE) public void deleteRole(@PathVariable("String_Node_Str") String projectShortName,@PathVariable("String_Node_Str") String roleName){
  int projectId=projectService.findIdByShortName(projectShortName);
  RoleAndMetadata role=permissionService.findRoleInProjectByName(projectId,roleName);
  Validate.isTrue(role.getRemovable());
  permissionService.deleteRoleInProjectId(new Role(roleName),projectId);
  eventEmitter.emitDeleteRole(projectShortName);
}
Program: 55111
Project: 55111
Buggy source:
@RequestMapping(value="String_Node_Str",method=RequestMethod.GET) public Map<PermissionCategory,List<Permission>> existingPermissions(@PathVariable("String_Node_Str") String projectShortName){
  Map<PermissionCategory,List<Permission>> byCategory=new LinkedHashMap<>();
  for (  PermissionCategory pc : PermissionCategory.values()) {
    if (!pc.isOnlyForBase()) {
      byCategory.put(pc,new ArrayList<Permission>());
    }
  }
  for (  Permission permission : Permission.values()) {
    if (!permission.isOnlyForBase() && byCategory.containsKey(permission.getCategory())) {
      byCategory.get(permission.getCategory()).add(permission);
    }
  }
  return byCategory;
}

Fixed version (ground truth):
@RequestMapping(value="String_Node_Str",method=RequestMethod.GET) public Map<PermissionCategory,List<Permission>> existingPermissions(@PathVariable("String_Node_Str") String projectShortName){
  Map<PermissionCategory,List<Permission>> byCategory=new LinkedHashMap<>();
  for (  PermissionCategory pc : PermissionCategory.values()) {
    if (!pc.getOnlyForBase()) {
      byCategory.put(pc,new ArrayList<Permission>());
    }
  }
  for (  Permission permission : Permission.values()) {
    if (!permission.getOnlyForBase() && byCategory.containsKey(permission.getCategory())) {
      byCategory.get(permission.getCategory()).add(permission);
    }
  }
  return byCategory;
}
Program: 55112
Project: 55112
Buggy source:
public static void authenticateUserIfRemembered(HttpServletRequest req,HttpServletResponse resp,UserRepository userRepository){
  Cookie c;
  if (isUserAuthenticated(req) || (c=getCookie(req,CookieNames.getRememberMeCookieName())) == null) {
    return;
  }
  ImmutablePair<Integer,String> uIdToken=extractUserIdAndToken(c.getValue());
  if (uIdToken != null && userRepository.rememberMeTokenExists(uIdToken.getLeft(),uIdToken.getRight())) {
    userRepository.deleteRememberMeToken(uIdToken.getLeft(),uIdToken.getRight());
    User user=userRepository.findById(uIdToken.getLeft());
    setUser(user.getId(),user.isAnonymous(),req,resp,userRepository,true);
  }
 else {
    c.setMaxAge(0);
    c.setValue(null);
    resp.addCookie(c);
  }
}

Fixed version (ground truth):
public static void authenticateUserIfRemembered(HttpServletRequest req,HttpServletResponse resp,UserRepository userRepository){
  Cookie c;
  if (isUserAuthenticated(req) || (c=getCookie(req,CookieNames.getRememberMeCookieName())) == null) {
    return;
  }
  ImmutablePair<Integer,String> uIdToken=extractUserIdAndToken(c.getValue());
  if (uIdToken != null && userRepository.rememberMeTokenExists(uIdToken.getLeft(),uIdToken.getRight())) {
    userRepository.deleteRememberMeToken(uIdToken.getLeft(),uIdToken.getRight());
    User user=userRepository.findById(uIdToken.getLeft());
    setUser(user.getId(),user.getAnonymous(),req,resp,userRepository,true);
  }
 else {
    c.setMaxAge(0);
    c.setValue(null);
    resp.addCookie(c);
  }
}
Program: 55115
Project: 55115
Buggy source:
public UserPublicProfile(User user,List<EventsCount> dailyActivity,List<ProjectWithEventCounts> activeProjects,List<Event> lastWeekActivity,List<Event> latestActivityByPage){
  this.user=new User(user.getId(),user.getProvider(),user.getUsername(),null,user.getDisplayName(),user.isEnabled(),user.isEmailNotification(),user.getMemberSince(),user.isSkipOwnNotifications());
  this.activeProjects=activeProjects;
  this.dailyActivity=dailyActivity;
  this.lastWeekActivity=lastWeekActivity;
  this.latestActivityByPage=latestActivityByPage;
}

Fixed version (ground truth):
public UserPublicProfile(User user,List<EventsCount> dailyActivity,List<ProjectWithEventCounts> activeProjects,List<Event> latestActivityByPage){
  this.user=new User(user.getId(),user.getProvider(),user.getUsername(),null,user.getDisplayName(),user.isEnabled(),user.isEmailNotification(),user.getMemberSince(),user.isSkipOwnNotifications());
  this.activeProjects=activeProjects;
  this.dailyActivity=dailyActivity;
  this.latestActivityByPage=latestActivityByPage;
}
Program: 55116
Project: 55116
Buggy source:
@RequestMapping(value="String_Node_Str",method=RequestMethod.GET) public UserPublicProfile getUserProfile(@PathVariable("String_Node_Str") String provider,@PathVariable("String_Node_Str") String name,UserWithPermission currentUser,@RequestParam(value="String_Node_Str",defaultValue="String_Node_Str") int page){
  User user=userRepository.findUserByName(provider,name);
  final List<EventsCount> dailyActivity;
  final List<ProjectWithEventCounts> activeProjects;
  final List<Event> lastWeekActivity;
  final List<Event> activitiesByPage;
  Date lastYear=DateUtils.setDays(DateUtils.addMonths(new Date(),-11),1);
  Date lastWeek=DateUtils.addDays(new Date(),-7);
  if (currentUser.getBasePermissions().containsKey(Permission.READ)) {
    dailyActivity=eventRepository.getUserActivity(user.getId(),lastYear);
    activeProjects=projectService.findProjectsActivityByUser(user.getId());
    lastWeekActivity=eventRepository.getLatestActivity(user.getId(),lastWeek);
    activitiesByPage=eventRepository.getLatestActivityByPage(user.getId(),page);
  }
 else {
    Collection<Integer> visibleProjectsIds=currentUser.projectsIdWithPermission(Permission.READ);
    dailyActivity=eventRepository.getUserActivityForProjects(user.getId(),lastYear,visibleProjectsIds);
    activeProjects=projectService.findProjectsActivityByUserInProjects(user.getId(),visibleProjectsIds);
    lastWeekActivity=eventRepository.getLatestActivityByProjects(user.getId(),lastWeek,visibleProjectsIds);
    activitiesByPage=eventRepository.getLatestActivityByPageAndProjects(user.getId(),page,visibleProjectsIds);
  }
  return new UserPublicProfile(user,dailyActivity,activeProjects,lastWeekActivity,activitiesByPage);
}

Fixed version (ground truth):
@RequestMapping(value="String_Node_Str",method=RequestMethod.GET) public UserPublicProfile getUserProfile(@PathVariable("String_Node_Str") String provider,@PathVariable("String_Node_Str") String name,UserWithPermission currentUser,@RequestParam(value="String_Node_Str",defaultValue="String_Node_Str") int page){
  User user=userRepository.findUserByName(provider,name);
  final List<EventsCount> dailyActivity;
  final List<ProjectWithEventCounts> activeProjects;
  final List<Event> activitiesByPage;
  Date lastYear=DateUtils.setDays(DateUtils.addMonths(new Date(),-11),1);
  if (currentUser.getBasePermissions().containsKey(Permission.READ)) {
    dailyActivity=eventRepository.getUserActivity(user.getId(),lastYear);
    activeProjects=projectService.findProjectsActivityByUser(user.getId());
    activitiesByPage=eventRepository.getLatestActivityByPage(user.getId(),page);
  }
 else {
    Collection<Integer> visibleProjectsIds=currentUser.projectsIdWithPermission(Permission.READ);
    dailyActivity=eventRepository.getUserActivityForProjects(user.getId(),lastYear,visibleProjectsIds);
    activeProjects=projectService.findProjectsActivityByUserInProjects(user.getId(),visibleProjectsIds);
    activitiesByPage=eventRepository.getLatestActivityByPageAndProjects(user.getId(),page,visibleProjectsIds);
  }
  return new UserPublicProfile(user,dailyActivity,activeProjects,activitiesByPage);
}
Program: 55117
Project: 55117
Buggy source:
@ExpectPermission({Permission.ADMINISTRATION,Permission.PROJECT_ADMINISTRATION}) @RequestMapping(value="String_Node_Str",method=RequestMethod.GET) public List<User> findAllUsers(){
  return userRepository.findAll();
}

Fixed version (ground truth):
@ExpectPermission(Permission.ADMINISTRATION) @RequestMapping(value="String_Node_Str",method=RequestMethod.GET) public List<User> findAllUsers(){
  return userRepository.findAll();
}
Program: 55118
Project: 55118
Buggy source:
@Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {
  ExpectPermission expectPermission=ExpectPermission.Helper.getAnnotation(handler);
  if (expectPermission == null) {
    return true;
  }
  Class<? extends OwnershipChecker> ownershipChecker=expectPermission.ownershipChecker();
  UserWithPermission user=UserSession.fetchFromRequest(request,userService);
  if (containtsOneKeyOf(user,expectPermission.value())) {
    return true;
  }
  if (NoOpOwnershipChecker.class != ownershipChecker && user.getBasePermissions().containsKey(Permission.READ) && context.getBean(expectPermission.ownershipChecker()).hasOwnership(request,user)) {
    return true;
  }
  Set<String> projectIds=extractProjectIdsFromRequestUri(request.getRequestURI(),projectService);
  if (allProjectsIdsHavePermission(projectIds,user,expectPermission.value())) {
    return true;
  }
  if (NoOpOwnershipChecker.class != ownershipChecker && allProjectsIdsHavePermission(projectIds,user,Permission.READ) && context.getBean(expectPermission.ownershipChecker()).hasOwnership(request,user)) {
    return true;
  }
  response.sendError(HttpStatus.FORBIDDEN.value());
  return false;
}

Fixed version (ground truth):
@Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {
  ExpectPermission expectPermission=ExpectPermission.Helper.getAnnotation(handler);
  if (expectPermission == null) {
    return true;
  }
  Class<? extends OwnershipChecker> ownershipChecker=expectPermission.ownershipChecker();
  UserWithPermission user=UserSession.fetchFromRequest(request,userService);
  if (user.getBasePermissions().containsKey(expectPermission.value())) {
    return true;
  }
  if (NoOpOwnershipChecker.class != ownershipChecker && user.getBasePermissions().containsKey(Permission.READ) && context.getBean(expectPermission.ownershipChecker()).hasOwnership(request,user)) {
    return true;
  }
  Set<String> projectIds=extractProjectIdsFromRequestUri(request.getRequestURI(),projectService);
  if (allProjectsIdsHavePermission(projectIds,user,expectPermission.value())) {
    return true;
  }
  if (NoOpOwnershipChecker.class != ownershipChecker && allProjectsIdsHavePermission(projectIds,user,Permission.READ) && context.getBean(expectPermission.ownershipChecker()).hasOwnership(request,user)) {
    return true;
  }
  response.sendError(HttpStatus.FORBIDDEN.value());
  return false;
}
Program: 55119
Project: 55119
Buggy source:
private long calculateDelayNanosAfterWillBePossibleToConsumeForIntervalBandwidth(int bandwidthIndex,Bandwidth bandwidth,long deficit,long currentTimeNanos){
  long refillPeriodNanos=bandwidth.refillPeriodNanos;
  long refillPeriodTokens=bandwidth.refillTokens;
  long previousRefillNanos=getLastRefillTimeNanos(bandwidthIndex);
  long timeOfNextRefillNanos=previousRefillNanos + refillPeriodNanos;
  long waitForNextRefillNanos=timeOfNextRefillNanos - currentTimeNanos;
  if (deficit <= refillPeriodTokens) {
    return waitForNextRefillNanos;
  }
  deficit-=waitForNextRefillNanos;
  long deficitPeriods=deficit / refillPeriodTokens + (deficit % refillPeriodTokens == 0L ? 0 : 1);
  if (deficit < refillPeriodNanos) {
    return waitForNextRefillNanos + refillPeriodNanos;
  }
  long deficitNanos=multiplyExactOrReturnMaxValue(deficitPeriods,refillPeriodNanos) + waitForNextRefillNanos;
  if (deficitNanos <= 0) {
    return Long.MAX_VALUE;
  }
  return deficitNanos;
}

Fixed version (ground truth):
private long calculateDelayNanosAfterWillBePossibleToConsumeForIntervalBandwidth(int bandwidthIndex,Bandwidth bandwidth,long deficit,long currentTimeNanos){
  long refillPeriodNanos=bandwidth.refillPeriodNanos;
  long refillTokens=bandwidth.refillTokens;
  long previousRefillNanos=getLastRefillTimeNanos(bandwidthIndex);
  long timeOfNextRefillNanos=previousRefillNanos + refillPeriodNanos;
  long waitForNextRefillNanos=timeOfNextRefillNanos - currentTimeNanos;
  if (deficit <= refillTokens) {
    return waitForNextRefillNanos;
  }
  deficit-=refillTokens;
  if (deficit < refillTokens) {
    return waitForNextRefillNanos + refillPeriodNanos;
  }
  long deficitPeriods=deficit / refillTokens + (deficit % refillTokens == 0L ? 0 : 1);
  long deficitNanos=multiplyExactOrReturnMaxValue(deficitPeriods,refillPeriodNanos);
  if (deficitNanos == Long.MAX_VALUE) {
    return Long.MAX_VALUE;
  }
  deficitNanos+=waitForNextRefillNanos;
  if (deficitNanos < 0) {
    return Long.MAX_VALUE;
  }
  return deficitNanos;
}
Program: 55120
Project: 55120
Buggy source:
/** 
 * Creates the   {@link Refill} that does refill of tokens in of manner,it will try to add the tokens to bucket as soon as possible. For example "of" refill "10 tokens per 1 second" will add 1 token per each 100 millisecond, in other words refill will not wait 1 second to regenerate whole bunch of 10 tokens. <p> The three refills bellow do refill of tokens with same speed: <pre> <code>Refill.greedy(600, Duration.ofMinutes(1));</code> <code>Refill.greedy(10, Duration.ofSeconds(1));</code> <code>Refill.greedy(1, Duration.ofMillis(100));</code> </pre> <p> If greediness is undesired then you can specify the fixed interval refill via  {@link #intervally(long,Duration)}
 * @param tokens amount of tokens
 * @param period the period within {@code tokens} will be fully regenerated
 * @return the {@link Refill} that does refill of tokens in of manner
 */
public static Refill greedy(long tokens,Duration period){
  return new Refill(tokens,period,false);
}

Fixed version (ground truth):
/** 
 * Creates the   {@link Refill} that does refill of tokens in greedy manner,it will try to add the tokens to bucket as soon as possible. For example "of" refill "10 tokens per 1 second" will add 1 token per each 100 millisecond, in other words refill will not wait 1 second to regenerate whole bunch of 10 tokens. <p> The three refills bellow do refill of tokens with same speed: <pre> <code>Refill.greedy(600, Duration.ofMinutes(1));</code> <code>Refill.greedy(10, Duration.ofSeconds(1));</code> <code>Refill.greedy(1, Duration.ofMillis(100));</code> </pre> <p> If greediness is undesired then you can specify the fixed interval refill via  {@link #intervally(long,Duration)}
 * @param tokens amount of tokens
 * @param period the period within {@code tokens} will be fully regenerated
 * @return the {@link Refill} that does refill of tokens in of manner
 */
public static Refill greedy(long tokens,Duration period){
  return new Refill(tokens,period,false);
}
Program: 55121
Project: 55121
Buggy source:
/** 
 * Creates the   {@link Refill} that does refill of tokens in intervally manner,in opposite to "of" refill the "intervally" refill will wait until whole  {@code period} will be elapsed before regenerate {@code tokens}
 * @param tokens amount of tokens
 * @param period the period within {@code tokens} will be fully regenerated
 * @return the {@link Refill} that does refill of tokens in intervally manner
 */
public static Refill intervally(long tokens,Duration period){
  return new Refill(tokens,period,true);
}

Fixed version (ground truth):
/** 
 * Creates the   {@link Refill} that does refill of tokens in intervally manner."Intervally" in opposite to "greedy"  will wait until whole  {@code period} will be elapsed before regenerate {@code tokens}
 * @param tokens amount of tokens
 * @param period the period within {@code tokens} will be fully regenerated
 * @return the {@link Refill} that does refill of tokens in intervally manner
 */
public static Refill intervally(long tokens,Duration period){
  return new Refill(tokens,period,true);
}
Program: 55122
Project: 55122
Buggy source:
public boolean isCompatible(BucketConfiguration newConfiguration){
  return bandwidths.length != newConfiguration.bandwidths.length;
}

Fixed version (ground truth):
public boolean isCompatible(BucketConfiguration newConfiguration){
  return bandwidths.length == newConfiguration.bandwidths.length;
}
Program: 55123
Project: 55123
Buggy source:
private static String generateMessage(BucketConfiguration previousConfiguration,BucketConfiguration newConfiguration){
  return MessageFormat.format("String_Node_Str",newConfiguration,previousConfiguration);
}

Fixed version (ground truth):
private static String generateMessage(BucketConfiguration previousConfiguration,BucketConfiguration newConfiguration){
  String format="String_Node_Str";
  return MessageFormat.format(format,newConfiguration,previousConfiguration);
}
Program: 55124
Project: 55124
Buggy source:
@Override protected CompletableFuture<Void> replaceConfigurationAsyncImpl(BucketConfiguration newConfiguration){
  ReplaceConfigurationOrReturnPreviousCommand replaceConfigCommand=new ReplaceConfigurationOrReturnPreviousCommand(newConfiguration);
  CompletableFuture<BucketConfiguration> result=executeAsync(replaceConfigCommand);
  return result.thenCompose(previousConfiguration -> {
    if (previousConfiguration == null) {
      return CompletableFuture.completedFuture(null);
    }
 else {
      CompletableFuture<Void> future=new CompletableFuture<>();
      future.completeExceptionally(new IncompatibleConfigurationException(newConfiguration,previousConfiguration));
      return future;
    }
  }
);
}

Fixed version (ground truth):
@Override protected CompletableFuture<Void> replaceConfigurationAsyncImpl(BucketConfiguration newConfiguration){
  ReplaceConfigurationOrReturnPreviousCommand replaceConfigCommand=new ReplaceConfigurationOrReturnPreviousCommand(newConfiguration);
  CompletableFuture<BucketConfiguration> result=executeAsync(replaceConfigCommand);
  return result.thenCompose(previousConfiguration -> {
    if (previousConfiguration == null) {
      return CompletableFuture.completedFuture(null);
    }
 else {
      CompletableFuture<Void> future=new CompletableFuture<>();
      future.completeExceptionally(new IncompatibleConfigurationException(previousConfiguration,newConfiguration));
      return future;
    }
  }
);
}
Program: 55125
Project: 55125
Buggy source:
@Override protected void replaceConfigurationImpl(BucketConfiguration newConfiguration){
  ReplaceConfigurationOrReturnPreviousCommand replaceConfigCommand=new ReplaceConfigurationOrReturnPreviousCommand(newConfiguration);
  BucketConfiguration previousConfiguration=execute(replaceConfigCommand);
  if (previousConfiguration != null) {
    throw new IncompatibleConfigurationException(newConfiguration,previousConfiguration);
  }
}

Fixed version (ground truth):
@Override protected void replaceConfigurationImpl(BucketConfiguration newConfiguration){
  ReplaceConfigurationOrReturnPreviousCommand replaceConfigCommand=new ReplaceConfigurationOrReturnPreviousCommand(newConfiguration);
  BucketConfiguration previousConfiguration=execute(replaceConfigCommand);
  if (previousConfiguration != null) {
    throw new IncompatibleConfigurationException(previousConfiguration,newConfiguration);
  }
}
Program: 55126
Project: 55126
Buggy source:
@Override public BucketConfiguration execute(GridBucketState state,long currentTimeNanos){
  BucketConfiguration previousConfiguration=state.replaceConfigurationOrReturnPrevious(newConfiguration);
  if (previousConfiguration != null) {
    return previousConfiguration;
  }
  state.refillAllBandwidth(currentTimeNanos);
  replaced=true;
  return null;
}

Fixed version (ground truth):
@Override public BucketConfiguration execute(GridBucketState state,long currentTimeNanos){
  state.refillAllBandwidth(currentTimeNanos);
  BucketConfiguration previousConfiguration=state.replaceConfigurationOrReturnPrevious(newConfiguration);
  if (previousConfiguration != null) {
    return previousConfiguration;
  }
  replaced=true;
  return null;
}
Program: 55127
Project: 55127
Buggy source:
@Override protected void replaceConfigurationImpl(BucketConfiguration newConfiguration){
  StateWithConfiguration previousState=stateReference.get();
  StateWithConfiguration newState=previousState.copy();
  long currentTimeNanos=timeMeter.currentTimeNanos();
  while (true) {
    previousState.configuration.checkCompatibility(newConfiguration);
    newState.configuration=newConfiguration;
    newState.refillAllBandwidth(currentTimeNanos);
    if (stateReference.compareAndSet(previousState,newState)) {
      return;
    }
 else {
      previousState=stateReference.get();
      newState.copyStateFrom(previousState);
    }
  }
}

Fixed version (ground truth):
@Override protected void replaceConfigurationImpl(BucketConfiguration newConfiguration){
  StateWithConfiguration previousState=stateReference.get();
  StateWithConfiguration newState=previousState.copy();
  long currentTimeNanos=timeMeter.currentTimeNanos();
  while (true) {
    previousState.configuration.checkCompatibility(newConfiguration);
    newState.refillAllBandwidth(currentTimeNanos);
    newState.configuration=newConfiguration;
    if (stateReference.compareAndSet(previousState,newState)) {
      return;
    }
 else {
      previousState=stateReference.get();
      newState.copyStateFrom(previousState);
    }
  }
}
Program: 55128
Project: 55128
Buggy source:
@Override protected void replaceConfigurationImpl(BucketConfiguration newConfiguration){
  long currentTimeNanos=timeMeter.currentTimeNanos();
  lock.lock();
  try {
    configuration.checkCompatibility(newConfiguration);
    this.configuration=newConfiguration;
    this.bandwidths=newConfiguration.getBandwidths();
    this.state.refillAllBandwidth(bandwidths,currentTimeNanos);
  }
  finally {
    lock.unlock();
  }
}

Fixed version (ground truth):
@Override protected void replaceConfigurationImpl(BucketConfiguration newConfiguration){
  long currentTimeNanos=timeMeter.currentTimeNanos();
  lock.lock();
  try {
    configuration.checkCompatibility(newConfiguration);
    this.state.refillAllBandwidth(bandwidths,currentTimeNanos);
    this.configuration=newConfiguration;
    this.bandwidths=newConfiguration.getBandwidths();
  }
  finally {
    lock.unlock();
  }
}