nus-yam/ex-repair huggingface dataset:
Program: 168360
Project: 168360
Buggy source:
void createEncounter(){
  Encountercreate encountercreate=new Encountercreate();
  encountercreate.setPatient(patient.getUuid());
  encountercreate.setEncounterType(encountertype);
  List<Obscreate> observations=new ArrayList<>();
  List<Fragment> activefrag=getActiveFragments();
  for (  Fragment f : activefrag) {
    FormPageFragment formPageFragment=(FormPageFragment)f;
    if (!formPageFragment.checkfields())     break;
    List<InputField> pageinputlist=formPageFragment.getInputFields();
    inputlist.addAll(pageinputlist);
  }
  for (  InputField input : inputlist) {
    Obscreate obscreate=new Obscreate();
    obscreate.setConcept(input.getConcept());
    obscreate.setValue(input.getValue());
    LocalDateTime localDateTime=new LocalDateTime();
    obscreate.setObsDatetime(localDateTime.toString());
    obscreate.setPerson(patient.getUuid());
    observations.add(obscreate);
  }
  encountercreate.setObservations(observations);
  encountercreate.setFormname(formname);
  encountercreate.setPatientId(mPatientID);
  encountercreate.setObslist();
  new EncounterService().addEncounter(encountercreate);
  finish();
}

Fixed version (ground truth):
void createEncounter(){
  Encountercreate encountercreate=new Encountercreate();
  encountercreate.setPatient(patient.getUuid());
  encountercreate.setEncounterType(encountertype);
  List<Obscreate> observations=new ArrayList<>();
  List<Fragment> activefrag=getActiveFragments();
  boolean valid=true;
  for (  Fragment f : activefrag) {
    FormPageFragment formPageFragment=(FormPageFragment)f;
    if (!formPageFragment.checkfields()) {
      valid=false;
      break;
    }
    List<InputField> pageinputlist=formPageFragment.getInputFields();
    inputlist.addAll(pageinputlist);
  }
  if (valid) {
    for (    InputField input : inputlist) {
      if (input.getValue() != -1.0) {
        Obscreate obscreate=new Obscreate();
        obscreate.setConcept(input.getConcept());
        obscreate.setValue(input.getValue());
        LocalDateTime localDateTime=new LocalDateTime();
        obscreate.setObsDatetime(localDateTime.toString());
        obscreate.setPerson(patient.getUuid());
        observations.add(obscreate);
      }
    }
    encountercreate.setObservations(observations);
    encountercreate.setFormname(formname);
    encountercreate.setPatientId(mPatientID);
    encountercreate.setObslist();
    new EncounterService().addEncounter(encountercreate);
    finish();
  }
}
Program: 168361
Project: 168361
Buggy source:
@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.activity_form_list);
  Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
  Bundle b=getIntent().getExtras();
  if (b != null) {
    mPatientID=(long)b.get(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE);
  }
  if (toolbar != null) {
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }
  formresourcelist=getFormResourceList();
  int size=formresourcelist.size();
  FORMS=new String[size];
  for (int i=0; i < size; i++) {
    FORMS[i]=formresourcelist.get(i).getName();
  }
  ListView formlist=(ListView)findViewById(R.id.formlist);
  formlist.setAdapter(new ArrayAdapter<String>(FormListActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1,FORMS));
  formlist.setOnItemClickListener(listclick);
}

Fixed version (ground truth):
@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.activity_form_list);
  Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
  Bundle b=getIntent().getExtras();
  if (b != null) {
    mPatientID=(long)b.get(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE);
  }
  if (toolbar != null) {
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  }
  formresourcelist=getFormResourceList();
  Iterator<FormResource> iterator=formresourcelist.iterator();
  while (iterator.hasNext()) {
    FormResource formResource=iterator.next();
    List<FormResource> valueref=formResource.getResourceList();
    String valuerefString=null;
    for (    FormResource resource : valueref) {
      if (resource.getName().equals("String_Node_Str"))       valuerefString=resource.getValueReference();
    }
    if (valuerefString == null) {
      iterator.remove();
    }
  }
  int size=formresourcelist.size();
  FORMS=new String[size];
  for (int i=0; i < size; i++) {
    FORMS[i]=formresourcelist.get(i).getName();
  }
  ListView formlist=(ListView)findViewById(R.id.formlist);
  formlist.setAdapter(new ArrayAdapter<String>(FormListActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1,FORMS));
  formlist.setOnItemClickListener(listclick);
}
Program: 168362
Project: 168362
Buggy source:
public void onItemClick(AdapterView<?> parent,View view,final int position,long id){
  List<FormResource> valueref=formresourcelist.get(position).getResourceList();
  String valuerefString=null;
  for (  FormResource resource : valueref) {
    if (resource.getName().equals("String_Node_Str"))     valuerefString=resource.getValueReference();
  }
  if (valuerefString != null) {
    EncounterType enctype=getEncounterType(FORMS[position]);
    String encountertype=enctype.getUuid();
    Intent intent=new Intent(FormListActivity.this,FormDisplayActivity.class);
    intent.putExtra(ApplicationConstants.BundleKeys.FORM_NAME,FORMS[position]);
    intent.putExtra(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE,mPatientID);
    intent.putExtra(ApplicationConstants.BundleKeys.VALUEREFERENCE,valuerefString);
    intent.putExtra(ApplicationConstants.BundleKeys.ENCOUNTERTYPE,encountertype);
    ToastUtil.notify("String_Node_Str");
    startActivity(intent);
  }
 else {
    ToastUtil.error("String_Node_Str");
  }
}

Fixed version (ground truth):
public void onItemClick(AdapterView<?> parent,View view,final int position,long id){
  List<FormResource> valueref=formresourcelist.get(position).getResourceList();
  String valuerefString=null;
  for (  FormResource resource : valueref) {
    if (resource.getName().equals("String_Node_Str"))     valuerefString=resource.getValueReference();
  }
  EncounterType enctype=getEncounterType(FORMS[position]);
  String encountertype=enctype.getUuid();
  Intent intent=new Intent(FormListActivity.this,FormDisplayActivity.class);
  intent.putExtra(ApplicationConstants.BundleKeys.FORM_NAME,FORMS[position]);
  intent.putExtra(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE,mPatientID);
  intent.putExtra(ApplicationConstants.BundleKeys.VALUEREFERENCE,valuerefString);
  intent.putExtra(ApplicationConstants.BundleKeys.ENCOUNTERTYPE,encountertype);
  ToastUtil.notify("String_Node_Str");
  startActivity(intent);
}
Program: 168363
Project: 168363
Buggy source:
@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.patient_dashboard_layout);
  getSupportActionBar().setElevation(0);
  Bundle patientBundle=savedInstanceState;
  if (null != patientBundle) {
    patientBundle.getString(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE);
  }
 else {
    patientBundle=getIntent().getExtras();
  }
  if (patientBundle.getBoolean(ApplicationConstants.BundleKeys.PROGRESS_BAR)) {
    showProgressDialog(R.string.action_synchronize_patients,DialogAction.SYNCHRONIZE);
  }
  mPatient=new PatientDAO().findPatientByUUID(patientBundle.getString(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE));
  new VisitsManager().getLastVitals(VisitsHelper.createLastVitalsListener(mPatient.getUuid()));
  mPatientDashboardPagerAdapter=new PatientDashboardPagerAdapter(getSupportFragmentManager());
  initViewPager();
}

Fixed version (ground truth):
@Override protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.patient_dashboard_layout);
  getSupportActionBar().setElevation(0);
  rootView=findViewById(R.id.rootview);
  Bundle patientBundle=savedInstanceState;
  if (null != patientBundle) {
    patientBundle.getString(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE);
  }
 else {
    patientBundle=getIntent().getExtras();
  }
  if (patientBundle.getBoolean(ApplicationConstants.BundleKeys.PROGRESS_BAR)) {
    showProgressDialog(R.string.action_synchronize_patients,DialogAction.SYNCHRONIZE);
  }
  mPatient=new PatientDAO().findPatientByUUID(patientBundle.getString(ApplicationConstants.BundleKeys.PATIENT_ID_BUNDLE));
  new VisitsManager().getLastVitals(VisitsHelper.createLastVitalsListener(mPatient.getUuid()));
  mPatientDashboardPagerAdapter=new PatientDashboardPagerAdapter(getSupportFragmentManager());
  initViewPager();
  if (NetworkUtils.isOnline())   refreshPatient();
 else {
    snackbar=Snackbar.make(rootView,"String_Node_Str",Snackbar.LENGTH_INDEFINITE);
    View view=snackbar.getView();
    TextView tv=(TextView)view.findViewById(android.support.design.R.id.snackbar_text);
    tv.setTextColor(Color.WHITE);
    snackbar.show();
  }
}
Program: 168364
Project: 168364
Buggy source:
public void synchronizePatient(){
  showProgressDialog(R.string.action_synchronize_patients,DialogAction.SYNCHRONIZE);
  new FindPatientsManager().getFullPatientData(FindPatientsHelper.createFullPatientDataListener(mPatient.getUuid(),this));
}

Fixed version (ground truth):
public void synchronizePatient(){
  if (NetworkUtils.isOnline()) {
    showProgressDialog(R.string.action_synchronize_patients,DialogAction.SYNCHRONIZE);
    new FindPatientsManager().getFullPatientData(FindPatientsHelper.createFullPatientDataListener(mPatient.getUuid(),this));
  }
 else   ToastUtil.error("String_Node_Str");
}
Program: 168365
Project: 168365
Buggy source:
public void stopLoader(boolean errorOccurred){
  mProgressDialog=false;
  mCustomFragmentDialog.dismiss();
  if (mDialogAction == DialogAction.SYNCHRONIZE) {
    mViewPager.setCurrentItem(DETAILS_TAB_POS);
    if (!errorOccurred) {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.SUCCESS,R.string.synchronize_patient_successful);
    }
 else {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.ERROR,R.string.synchronize_patient_error);
    }
  }
 else   if (mDialogAction == DialogAction.ADD_VISIT) {
    List<Fragment> fragments=getSupportFragmentManager().getFragments();
    recreateFragmentView(fragments.get(VISITS_TAB_POS));
    if (!errorOccurred) {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.SUCCESS,R.string.start_visit_successful);
    }
 else {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.ERROR,R.string.start_visit_error);
    }
  }
}

Fixed version (ground truth):
public void stopLoader(boolean errorOccurred){
  mProgressDialog=false;
  if (mCustomFragmentDialog != null)   mCustomFragmentDialog.dismiss();
  if (mDialogAction == DialogAction.SYNCHRONIZE) {
    mViewPager.setCurrentItem(DETAILS_TAB_POS);
    if (!errorOccurred) {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.SUCCESS,R.string.synchronize_patient_successful);
    }
 else {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.ERROR,R.string.synchronize_patient_error);
    }
  }
 else   if (mDialogAction == DialogAction.ADD_VISIT) {
    List<Fragment> fragments=getSupportFragmentManager().getFragments();
    recreateFragmentView(fragments.get(VISITS_TAB_POS));
    if (!errorOccurred) {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.SUCCESS,R.string.start_visit_successful);
    }
 else {
      ToastUtil.showShortToast(this,ToastUtil.ToastType.ERROR,R.string.start_visit_error);
    }
  }
}
Program: 168366
Project: 168366
Buggy source:
public void startFormEntry(String patientUUID,Long patientID){
  mSelectedPatientUUID=patientUUID;
  mSelectedPatientID=patientID;
  if (patientUUID != null) {
    startEncounterForPatient();
  }
 else   ToastUtil.error("String_Node_Str");
}

Fixed version (ground truth):
public void startFormEntry(String patientUUID,Long patientID){
  mSelectedPatientUUID=patientUUID;
  mSelectedPatientID=patientID;
  if (!StringUtils.isBlank(patientUUID)) {
    startEncounterForPatient();
  }
 else   ToastUtil.error("String_Node_Str");
}
Program: 168367
Project: 168367
Buggy source:
public boolean checkIfConnectionIsAvailable(){
  boolean connection=NetworkUtils.isNetworkAvailable();
  if (mIsConnectionAvailable) {
    FindPatientsManager fpm=new FindPatientsManager();
    fpm.getLastViewedPatient(mFpmResponseListener);
  }
  return connection;
}

Fixed version (ground truth):
public boolean checkIfConnectionIsAvailable(){
  boolean connection=NetworkUtils.isOnline();
  if (mIsConnectionAvailable) {
    FindPatientsManager fpm=new FindPatientsManager();
    fpm.getLastViewedPatient(mFpmResponseListener);
  }
  return connection;
}
Program: 168368
Project: 168368
Buggy source:
public void updateLastViewedList(){
  if (NetworkUtils.isNetworkAvailable()) {
    setRefreshing(true);
    mSwipeLayout.setRefreshing(true);
    mSwipeLayout.setEnabled(false);
    mEmptyList.setVisibility(View.GONE);
    patientsRecyclerView.setVisibility(View.GONE);
    mSpinner.setVisibility(View.GONE);
    if (mAdapter != null) {
      mAdapter.clear();
    }
    FindPatientsManager fpm=new FindPatientsManager();
    fpm.getLastViewedPatient(mFpmResponseListener);
  }
 else {
    mEmptyList.setText(getString(R.string.find_patient_no_connection));
    patientsRecyclerView.setVisibility(View.GONE);
    mEmptyList.setVisibility(View.VISIBLE);
    mSpinner.setVisibility(View.GONE);
    mSwipeLayout.setRefreshing(false);
  }
}

Fixed version (ground truth):
public void updateLastViewedList(){
  if (NetworkUtils.isOnline()) {
    setRefreshing(true);
    mSwipeLayout.setRefreshing(true);
    mSwipeLayout.setEnabled(false);
    mEmptyList.setVisibility(View.GONE);
    patientsRecyclerView.setVisibility(View.GONE);
    mSpinner.setVisibility(View.GONE);
    if (mAdapter != null) {
      mAdapter.clear();
    }
    FindPatientsManager fpm=new FindPatientsManager();
    fpm.getLastViewedPatient(mFpmResponseListener);
  }
 else {
    mEmptyList.setText(getString(R.string.find_patient_no_connection));
    patientsRecyclerView.setVisibility(View.GONE);
    mEmptyList.setVisibility(View.VISIBLE);
    mSpinner.setVisibility(View.GONE);
    mSwipeLayout.setRefreshing(false);
  }
}
Program: 168369
Project: 168369
Buggy source:
public List<InputField> getInputFields(){
  for (  InputField field : inputFields) {
    EditText ed=(EditText)getActivity().findViewById(field.getId());
    if (!isEmpty(ed))     field.setValue(Double.parseDouble(ed.getText().toString()));
  }
  return inputFields;
}

Fixed version (ground truth):
public List<InputField> getInputFields(){
  for (  InputField field : inputFields) {
    RangeEditText ed=(RangeEditText)getActivity().findViewById(field.getId());
    if (!isEmpty(ed))     field.setValue(Double.parseDouble(ed.getText().toString()));
  }
  return inputFields;
}
Program: 168371
Project: 168371
Buggy source:
public boolean checkfields(){
  for (  InputField field : inputFields) {
    EditText ed=(EditText)getActivity().findViewById(field.getId());
    if (isEmpty(ed)) {
      ToastUtil.error("String_Node_Str");
      return false;
    }
  }
  return true;
}

Fixed version (ground truth):
public boolean checkfields(){
  boolean emp=true;
  for (  InputField field : inputFields) {
    RangeEditText ed=(RangeEditText)getActivity().findViewById(field.getId());
    if (!isEmpty(ed)) {
      emp=false;
      Double inp=Double.parseDouble(ed.getText().toString());
      if (ed.getUpperlimit() != -1.0 && ed.getUpperlimit() != -1.0) {
        if (ed.getUpperlimit() < inp || ed.getLowerlimit() > inp) {
          ToastUtil.error("String_Node_Str" + ed.getName() + "String_Node_Str");
          return false;
        }
      }
    }
  }
  if (emp) {
    ToastUtil.error("String_Node_Str");
    return false;
  }
  return true;
}
Program: 168372
Project: 168372
Buggy source:
@Override public boolean onOptionsItemSelected(MenuItem item){
  int id=item.getItemId();
switch (id) {
case R.id.actionStartVisit:
    showStartVisitDialog();
default :
  return super.onOptionsItemSelected(item);
}
}

Fixed version (ground truth):
@Override public boolean onOptionsItemSelected(MenuItem item){
  int id=item.getItemId();
switch (id) {
case R.id.actionStartVisit:
    if (!StringUtils.isBlank(mPatient.getUuid()))     showStartVisitDialog();
 else     ToastUtil.error("String_Node_Str" + "String_Node_Str");
default :
  return super.onOptionsItemSelected(item);
}
}
Program: 168373
Project: 168373
Buggy source:
@Override public void onBindViewHolder(PatientViewHolder holder,final int position){
  final Patient patient=mItems.get(position);
  if (new VisitDAO().isPatientNowOnVisit(patient.getId())) {
    holder.mVisitStatusIcon.setImageBitmap(ImageUtils.decodeBitmapFromResource(mContext.getResources(),R.drawable.active_visit_dot,holder.mVisitStatusIcon.getLayoutParams().width,holder.mVisitStatusIcon.getLayoutParams().height));
    holder.mVisitStatus.setText(mContext.getString(R.string.active_visit_label_capture_vitals));
  }
  if (null != patient.getIdentifier()) {
    holder.mIdentifier.setText("String_Node_Str" + patient.getIdentifier().getIdentifier());
  }
  if (null != patient.getDisplay()) {
    holder.mDisplayName.setText(patient.getPerson().getName().getNameString());
  }
  if (null != patient.getPerson().getGender()) {
    holder.mGender.setText(patient.getPerson().getGender());
  }
  holder.mRowLayout.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(    View v){
      if (mContext instanceof PatientListActivity) {
        ((PatientListActivity)mContext).startFormEntry(mItems.get(position).getUuid(),mItems.get(position).getId());
      }
 else {
        throw new IllegalStateException("String_Node_Str");
      }
    }
  }
);
  holder.mBirthDate.setText(DateUtils.convertTime(DateUtils.convertTime(patient.getPerson().getBirthdate())));
  new AnimationUtils().setAnimation(holder.mRowLayout,mContext,position);
}

Fixed version (ground truth):
@Override public void onBindViewHolder(PatientViewHolder holder,final int position){
  final Patient patient=mItems.get(position);
  if (new VisitDAO().isPatientNowOnVisit(patient.getId())) {
    holder.mVisitStatusIcon.setImageBitmap(ImageUtils.decodeBitmapFromResource(mContext.getResources(),R.drawable.active_visit_dot,holder.mVisitStatusIcon.getLayoutParams().width,holder.mVisitStatusIcon.getLayoutParams().height));
    holder.mVisitStatus.setText(mContext.getString(R.string.active_visit_label_capture_vitals));
  }
  if (null != patient.getIdentifier()) {
    holder.mIdentifier.setText("String_Node_Str" + patient.getIdentifier().getIdentifier());
  }
  if (null != patient.getPerson().getName()) {
    holder.mDisplayName.setText(patient.getPerson().getName().getNameString());
  }
  if (null != patient.getPerson().getGender()) {
    holder.mGender.setText(patient.getPerson().getGender());
  }
  holder.mRowLayout.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(    View v){
      if (mContext instanceof PatientListActivity) {
        ((PatientListActivity)mContext).startFormEntry(mItems.get(position).getUuid(),mItems.get(position).getId());
      }
 else {
        throw new IllegalStateException("String_Node_Str");
      }
    }
  }
);
  holder.mBirthDate.setText(DateUtils.convertTime(DateUtils.convertTime(patient.getPerson().getBirthdate())));
  new AnimationUtils().setAnimation(holder.mRowLayout,mContext,position);
}
Program: 168374
Project: 168374
Buggy source:
private boolean isNetworkAvailable(){
  ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
  return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Fixed version (ground truth):
private boolean isNetworkAvailable(){
  ConnectivityManager connectivityManager=(ConnectivityManager)openMrs.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
  return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Program: 168375
Project: 168375
Buggy source:
public void setSelected(boolean value){
  if (value && !isSelected) {
    howManySelected++;
    holder.mRowLayout.setSelected(true);
    holder.mRowLayout.setBackgroundColor(ContextCompat.getColor(mContext,R.color.light_teal));
  }
 else   if (!value && isSelected) {
    howManySelected--;
    holder.mRowLayout.setSelected(false);
    holder.mRowLayout.setBackgroundColor(Color.TRANSPARENT);
  }
  isSelected=value;
}

Fixed version (ground truth):
public void setSelected(boolean value){
  if (value && !isSelected) {
    howManySelected++;
    holder.mRowLayout.setSelected(true);
    holder.mRowLayout.setBackgroundColor(ContextCompat.getColor(mContext,R.color.light_teal));
  }
 else   if (!value && isSelected) {
    howManySelected--;
    holder.mRowLayout.setSelected(false);
    holder.mRowLayout.setBackgroundResource(R.drawable.card);
  }
  isSelected=value;
}
Program: 168376
Project: 168376
Buggy source:
@Override public void onResponse(JSONObject response){
  mLogger.d(response.toString());
  try {
    String sessionToken=response.getString(SESSION_ID_KEY);
    Boolean isAuthenticated=Boolean.parseBoolean(response.getString(AUTHENTICATION_KEY));
    if (isAuthenticated) {
      if (mCallerManager.isDBCleaningRequired(mUsername,mServerURL)) {
        mOpenMRS.deleteDatabase(OpenMRSSQLiteOpenHelper.DATABASE_NAME);
        OpenMRS.getInstance().getContentResolver().delete(OpenMRSFormsProviderAPI.FormsColumns.CONTENT_URI,null,null);
        OpenMRS.getInstance().getContentResolver().delete(OpenMRSInstanceProviderAPI.InstanceColumns.CONTENT_URI,null,null);
        setData(sessionToken);
      }
 else       if (mCallerManager.isUserLoggedIn()) {
        setData(sessionToken);
      }
 else {
        mOpenMRS.setSessionToken(sessionToken);
      }
      new VisitsManager().getVisitType(VisitsHelper.createVisitTypeListener());
      UserManager userManager=new UserManager();
      userManager.getUserInformation(UserHelper.createUserInformationListener(mUsername,userManager));
      mCallerActivity.saveLocationsToDatabase();
      mCallerActivity.finish();
    }
 else {
      mCallerActivity.sendBroadcast(new Intent(ApplicationConstants.CustomIntentActions.ACTION_AUTH_FAILED_BROADCAST));
    }
  }
 catch (  JSONException e) {
    mLogger.d(e.toString());
  }
}

Fixed version (ground truth):
@Override public void onResponse(JSONObject response){
  mLogger.d(response.toString());
  try {
    String sessionToken=response.getString(SESSION_ID_KEY);
    Boolean isAuthenticated=Boolean.parseBoolean(response.getString(AUTHENTICATION_KEY));
    if (isAuthenticated) {
      if (mCallerManager.isDBCleaningRequired(mUsername,mServerURL)) {
        mOpenMRS.deleteDatabase(OpenMRSSQLiteOpenHelper.DATABASE_NAME);
        OpenMRS.getInstance().getContentResolver().delete(OpenMRSFormsProviderAPI.FormsColumns.CONTENT_URI,null,null);
        OpenMRS.getInstance().getContentResolver().delete(OpenMRSInstanceProviderAPI.InstanceColumns.CONTENT_URI,null,null);
        setData(sessionToken);
      }
 else       if (mCallerManager.isUserNameOrServerEmpty()) {
        setData(sessionToken);
      }
 else {
        mOpenMRS.setSessionToken(sessionToken);
      }
      new VisitsManager().getVisitType(VisitsHelper.createVisitTypeListener());
      UserManager userManager=new UserManager();
      userManager.getUserInformation(UserHelper.createUserInformationListener(mUsername,userManager));
      mCallerActivity.saveLocationsToDatabase();
      mCallerActivity.finish();
    }
 else {
      mCallerActivity.sendBroadcast(new Intent(ApplicationConstants.CustomIntentActions.ACTION_AUTH_FAILED_BROADCAST));
    }
  }
 catch (  JSONException e) {
    mLogger.d(e.toString());
  }
}
Program: 168377
Project: 168377
Buggy source:
public void updatePatientVisitsData(boolean errorOccurred){
  final List<Fragment> fragments=getSupportFragmentManager().getFragments();
  for (  final Fragment fragment : fragments) {
    this.runOnUiThread(new Runnable(){
      @Override public void run(){
        recreateFragmentView(fragment);
      }
    }
);
  }
  stopLoader(errorOccurred);
}

Fixed version (ground truth):
public void updatePatientVisitsData(boolean errorOccurred){
  final List<Fragment> fragments=getSupportFragmentManager().getFragments();
  for (  final Fragment fragment : fragments) {
    if (null != fragment) {
      this.runOnUiThread(new Runnable(){
        @Override public void run(){
          recreateFragmentView(fragment);
        }
      }
);
    }
  }
  stopLoader(errorOccurred);
}
Program: 168378
Project: 168378
Buggy source:
public void subtractExpectedResponses(boolean errorOccurred){
  mExpectedResponses--;
  if (errorOccurred) {
    mErrorOccurred=errorOccurred;
  }
  if (mExpectedResponses <= 0) {
    if (mContext instanceof PatientDashboardActivity) {
      ((PatientDashboardActivity)mContext).updatePatientVisitsData(mErrorOccurred);
    }
 else     if (mContext instanceof FindPatientsSearchActivity || mContext instanceof FindPatientsActivity) {
      ((ACBaseActivity)mContext).dismissProgressDialog(errorOccurred,R.string.find_patients_row_toast_patient_saved,R.string.find_patients_row_toast_patient_save_error);
    }
  }
}

Fixed version (ground truth):
public void subtractExpectedResponses(boolean errorOccurred){
  mExpectedResponses--;
  if (errorOccurred) {
    mErrorOccurred=errorOccurred;
  }
  if (mExpectedResponses <= 0) {
    if (mContext instanceof PatientDashboardActivity) {
      ((PatientDashboardActivity)OpenMRS.getInstance().getCurrentActivity()).updatePatientVisitsData(mErrorOccurred);
    }
 else     if (mContext instanceof FindPatientsSearchActivity || mContext instanceof FindPatientsActivity) {
      ((ACBaseActivity)mContext).dismissProgressDialog(errorOccurred,R.string.find_patients_row_toast_patient_saved,R.string.find_patients_row_toast_patient_save_error);
    }
  }
}
Program: 168379
Project: 168379
Buggy source:
/** 
 * Clear odk directories on the SDCard (or other external storage)
 * @throws RuntimeException if there is no SDCard or the directory exists as a non directory
 */
public static void clearODKDirs() throws RuntimeException {
  String cardstatus=Environment.getExternalStorageState();
  if (!cardstatus.equals(Environment.MEDIA_MOUNTED)) {
    throw new RuntimeException(Collect.getInstance().getString(R.string.sdcard_unmounted,cardstatus));
  }
  String[] dirs={ODK_ROOT};
  for (  String dirName : dirs) {
    File file=new File(dirName);
    if (file.exists()) {
      String deleteCmd="String_Node_Str" + dirName;
      Runtime runtime=Runtime.getRuntime();
      try {
        runtime.exec(deleteCmd);
      }
 catch (      IOException e) {
        RuntimeException ex=new RuntimeException("String_Node_Str" + dirName + "String_Node_Str");
      }
    }
  }
  createODKDirs();
}

Fixed version (ground truth):
/** 
 * Clear odk directories on the SDCard (or other external storage)
 * @throws RuntimeException if there is no SDCard or the directory exists as a non directory
 */
public static void clearODKDirs() throws RuntimeException {
  String cardstatus=Environment.getExternalStorageState();
  if (!cardstatus.equals(Environment.MEDIA_MOUNTED)) {
    throw new RuntimeException(Collect.getInstance().getString(R.string.sdcard_unmounted,cardstatus));
  }
  String[] dirs={ODK_ROOT};
  for (  String dirName : dirs) {
    File file=new File(dirName);
    if (file.exists()) {
      deleteRecursive(file);
    }
  }
  createODKDirs();
}
Program: 168380
Project: 168380
Buggy source:
@Override public void onResponse(JSONObject response){
  logger.d(response.toString());
  try {
    String sessionToken=response.getString(SESSION_ID_KEY);
    Boolean isAuthenticated=Boolean.parseBoolean(response.getString(AUTHENTICATION_KEY));
    if (isAuthenticated) {
      if (!mOpenMRS.getUsername().equals(username) || !mOpenMRS.getServerUrl().equals(serverURL)) {
        mOpenMRS.deleteDatabase(OpenMRSSQLiteOpenHelper.DATABASE_NAME);
        OpenMRS.clearODKDirs();
      }
      mOpenMRS.setServerUrl(serverURL);
      mOpenMRS.setSessionToken(sessionToken);
      mOpenMRS.setUsername(username);
      (new VisitsManager(mContext)).getVisitType();
      new UserManager(mContext).getUserInformation(username);
      new FormsManger(mContext).getAvailableFormsList();
      ((LoginActivity)mContext).saveLocationsToDatabase();
      ((LoginActivity)mContext).finish();
    }
 else {
      mContext.sendBroadcast(new Intent(ApplicationConstants.CustomIntentActions.ACTION_AUTH_FAILED_BROADCAST));
    }
  }
 catch (  JSONException e) {
    logger.d(e.toString());
  }
}

Fixed version (ground truth):
@Override public void onResponse(JSONObject response){
  logger.d(response.toString());
  try {
    String sessionToken=response.getString(SESSION_ID_KEY);
    Boolean isAuthenticated=Boolean.parseBoolean(response.getString(AUTHENTICATION_KEY));
    if (isAuthenticated) {
      if (isDBCleaningRequired(username,serverURL)) {
        mOpenMRS.deleteDatabase(OpenMRSSQLiteOpenHelper.DATABASE_NAME);
        OpenMRS.clearODKDirs();
      }
      mOpenMRS.setServerUrl(serverURL);
      mOpenMRS.setSessionToken(sessionToken);
      mOpenMRS.setUsername(username);
      (new VisitsManager(mContext)).getVisitType();
      new UserManager(mContext).getUserInformation(username);
      new FormsManger(mContext).getAvailableFormsList();
      ((LoginActivity)mContext).saveLocationsToDatabase();
      ((LoginActivity)mContext).finish();
    }
 else {
      mContext.sendBroadcast(new Intent(ApplicationConstants.CustomIntentActions.ACTION_AUTH_FAILED_BROADCAST));
    }
  }
 catch (  JSONException e) {
    logger.d(e.toString());
  }
}
Program: 168382
Project: 168382
Buggy source:
private void writeResponseToFile(String formName,String response) throws IOException {
  String rootName=formName.replaceAll("String_Node_Str","String_Node_Str");
  rootName=rootName.replaceAll("String_Node_Str","String_Node_Str");
  rootName=rootName.trim();
  String path=OpenMRS.FORMS_PATH + File.separator + rootName+ "String_Node_Str";
  int i=2;
  File file=new File(path);
  while (file.exists()) {
    path=OpenMRS.FORMS_PATH + File.separator + rootName+ "String_Node_Str"+ i+ "String_Node_Str";
    file=new File(path);
    i++;
  }
  try {
    FileWriter fw=new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw=new BufferedWriter(fw);
    bw.write(response);
    bw.close();
    fw.close();
  }
 catch (  IOException e) {
    mOpenMRS.getOpenMRSLogger().d(e.toString());
  }
  FormsLoaderUtil.saveOrUpdateForm(file);
}

Fixed version (ground truth):
private void writeResponseToFile(String formName,String response) throws IOException {
  String rootName=formName.replaceAll("String_Node_Str","String_Node_Str");
  rootName=rootName.replaceAll("String_Node_Str","String_Node_Str");
  rootName=rootName.trim();
  String path=OpenMRS.FORMS_PATH + File.separator + rootName+ "String_Node_Str";
  int i=2;
  File file=new File(path);
  while (file.exists()) {
    path=OpenMRS.FORMS_PATH + File.separator + rootName+ "String_Node_Str"+ i+ "String_Node_Str";
    file=new File(path);
    i++;
  }
  file.createNewFile();
  try {
    FileWriter fw=new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw=new BufferedWriter(fw);
    bw.write(response);
    bw.close();
    fw.close();
  }
 catch (  IOException e) {
    mOpenMRS.getOpenMRSLogger().d(e.toString());
  }
  FormsLoaderUtil.saveOrUpdateForm(file);
}
Program: 168383
Project: 168383
Buggy source:
public static List<ModuleInfo> getPage(int position){
  int from=position * ITEMS_PER_PAGE;
  int to=Math.min((position + 1) * ITEMS_PER_PAGE,mModules.size());
  Log.d(ScreenSlidePagerAdapter.class.getCanonicalName(),"String_Node_Str" + Integer.toString(from) + "String_Node_Str"+ Integer.toString(to)+ "String_Node_Str"+ Integer.toString(position));
  if (!(from < to)) {
    return null;
  }
  return mModules.subList(from,to);
}

Fixed version (ground truth):
public static List<ModuleInfo> getPage(int position){
  int from=position * ITEMS_PER_PAGE;
  int to=Math.min((position + 1) * ITEMS_PER_PAGE,mModules.size());
  Log.d(TAG,"String_Node_Str" + Integer.toString(from) + "String_Node_Str"+ Integer.toString(to)+ "String_Node_Str"+ Integer.toString(position));
  if (!(from < to)) {
    return null;
  }
  return mModules.subList(from,to);
}
Program: 168384
Project: 168384
Buggy source:
@Override public Fragment getItem(int position){
  ModulesFragment fragment=ModulesFragment.newInstance(position);
  return fragment;
}

Fixed version (ground truth):
@Override public Fragment getItem(int position){
  return ModulesFragment.newInstance(position);
}
Program: 168385
Project: 168385
Buggy source:
public static List<ModuleInfo> getActiveModules(){
  List<ModuleInfo> moduleList=new LinkedList<ModuleInfo>();
  return moduleList;
}

Fixed version (ground truth):
public static List<ModuleInfo> getActiveModules(){
  return new LinkedList<ModuleInfo>();
}
Program: 168386
Project: 168386
Buggy source:
@Override public void onItemSelected(AdapterView<?> parent,View view,int position,long id){
  onItemSelect(elements[position]);
  currentValue.set(elements[position]);
}

Fixed version (ground truth):
@Override public void onItemSelected(AdapterView<?> parent,View view,int position,long id){
  currentValue.set(elements[position]);
  onItemSelect(elements[position]);
}
Program: 168387
Project: 168387
Buggy source:
@Override public View onCreateView(DebugModule parent,LayoutInflater inflater,ViewGroup root){
  Context context=root.getContext();
  currentValue=new StringPreference(context.getSharedPreferences(parent.getTitle(),Context.MODE_PRIVATE),getKey());
  spinner=(Spinner)inflater.inflate(R.layout.debug_template_spinner,null);
  adapter=new ArrayAdapter<>(context,android.R.layout.simple_spinner_item,elements);
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner.setGravity(Gravity.START | Gravity.END | Gravity.CENTER_VERTICAL);
  spinner.setAdapter(adapter);
  if (currentValue.isSet() && rememberState) {
    spinner.setSelection(adapter.getPosition(currentValue.get()),false);
  }
 else {
    spinner.setSelection(0,false);
  }
  spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
    @Override public void onItemSelected(    AdapterView<?> parent,    View view,    int position,    long id){
      onItemSelect(elements[position]);
      currentValue.set(elements[position]);
    }
    @Override public void onNothingSelected(    AdapterView<?> parent){
    }
  }
);
  TextView nameView=new TextView(context);
  nameView.setText(name);
  return TextElement.createDefaultLayout(nameView,spinner);
}

Fixed version (ground truth):
@Override public View onCreateView(DebugModule parent,LayoutInflater inflater,ViewGroup root){
  Context context=root.getContext();
  currentValue=new StringPreference(context.getSharedPreferences(parent.getTitle(),Context.MODE_PRIVATE),getKey());
  spinner=(Spinner)inflater.inflate(R.layout.debug_template_spinner,null);
  adapter=new ArrayAdapter<>(context,android.R.layout.simple_spinner_item,elements);
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinner.setGravity(Gravity.START | Gravity.END | Gravity.CENTER_VERTICAL);
  spinner.setAdapter(adapter);
  if (currentValue.isSet() && rememberState) {
    spinner.setSelection(adapter.getPosition(currentValue.get()),false);
  }
 else {
    spinner.setSelection(0,false);
  }
  spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
    @Override public void onItemSelected(    AdapterView<?> parent,    View view,    int position,    long id){
      currentValue.set(elements[position]);
      onItemSelect(elements[position]);
    }
    @Override public void onNothingSelected(    AdapterView<?> parent){
    }
  }
);
  TextView nameView=new TextView(context);
  nameView.setText(name);
  return TextElement.createDefaultLayout(nameView,spinner);
}
Program: 168388
Project: 168388
Buggy source:
/** 
 * Dismisses all tooltips currently being displayed.
 * @param animate True to animate the transition.
 */
public void dismiss(boolean animate){
  if (animate) {
    List<Animator> a=new ArrayList<>();
    for (int i=0; i < getChildCount(); i++) {
      a.add(ObjectAnimator.ofFloat(getChildAt(i),View.ALPHA,0));
    }
    AnimatorSet s=new AnimatorSet();
    s.playTogether(a);
    s.addListener(new AnimatorListener(){
      @Override public void onAnimationStart(      Animator animation){
      }
      @Override public void onAnimationEnd(      Animator animation){
        removeAllViews();
        mToolTips.clear();
      }
      @Override public void onAnimationCancel(      Animator animation){
      }
      @Override public void onAnimationRepeat(      Animator animation){
      }
    }
);
    s.start();
  }
 else {
    removeAllViews();
    mToolTips.clear();
  }
}

Fixed version (ground truth):
/** 
 * Dismisses all tooltips currently being displayed.
 * @param animate True to animate the transition.
 */
public void dismiss(boolean animate){
  mToolTips.clear();
  if (animate) {
    final List<View> viewsToRemove=new ArrayList<>();
    List<Animator> a=new ArrayList<>();
    for (int i=0; i < getChildCount(); i++) {
      a.add(ObjectAnimator.ofFloat(getChildAt(i),View.ALPHA,0));
      viewsToRemove.add(getChildAt(i));
    }
    AnimatorSet s=new AnimatorSet();
    s.playTogether(a);
    s.addListener(new AnimatorListener(){
      @Override public void onAnimationStart(      Animator animation){
      }
      @Override public void onAnimationEnd(      Animator animation){
        for (        View v : viewsToRemove) {
          removeView(v);
        }
      }
      @Override public void onAnimationCancel(      Animator animation){
      }
      @Override public void onAnimationRepeat(      Animator animation){
      }
    }
);
    s.start();
  }
 else {
    removeAllViews();
  }
}
Program: 168389
Project: 168389
Buggy source:
@Override public void onAnimationEnd(Animator animation){
  removeAllViews();
  mToolTips.clear();
}

Fixed version (ground truth):
@Override public void onAnimationEnd(Animator animation){
  for (  View v : viewsToRemove) {
    removeView(v);
  }
}
Program: 168390
Project: 168390
Buggy source:
/** 
 * Stores the lap data in the exercise and calculate the missing values.
 */
private void storeLaps(){
  int lapDistanceSum=0;
  List<Lap> lLaps=new LinkedList<>();
  long startTime=Date310Utils.getMilliseconds(exercise.getDateTime());
  for (  FitLap fitLap : lFitLaps) {
    Lap lap=fitLap.getLap();
    lLaps.add(lap);
    long lapSplitDateTimeMillis=Date310Utils.getMilliseconds(fitLap.getSplitDatTime());
    lap.setTimeSplit((int)((lapSplitDateTimeMillis - startTime) / 100));
    ExerciseSample sampleAtLapEnd=getExerciseSampleForLapEnd(lap);
    lap.setHeartRateSplit(sampleAtLapEnd.getHeartRate());
    if (lap.getSpeed() != null) {
      lapDistanceSum+=lap.getSpeed().getDistance();
      lap.getSpeed().setDistance(lapDistanceSum);
      lap.getSpeed().setSpeedEnd(sampleAtLapEnd.getSpeed());
      lap.getSpeed().setCadence(sampleAtLapEnd.getCadence());
    }
    if (lap.getAltitude() != null) {
      lap.setAltitude(lap.getAltitude().copy((short)sampleAtLapEnd.getAltitude(),lap.getAltitude().getAscent()));
    }
    if (temperatureAvailable) {
      lap.setTemperature(new LapTemperature(sampleAtLapEnd.getTemperature()));
    }
  }
  exercise.getLapList().addAll(lLaps);
}

Fixed version (ground truth):
/** 
 * Stores the lap data in the exercise and calculate the missing values.
 */
private void storeLaps(){
  int lapDistanceSum=0;
  List<Lap> lLaps=new LinkedList<>();
  long startTime=Date310Utils.getMilliseconds(exercise.getDateTime());
  for (  FitLap fitLap : lFitLaps) {
    Lap lap=fitLap.getLap();
    lLaps.add(lap);
    long lapSplitDateTimeMillis=Date310Utils.getMilliseconds(fitLap.getSplitDatTime());
    lap.setTimeSplit((int)((lapSplitDateTimeMillis - startTime) / 100));
    ExerciseSample sampleAtLapEnd=getExerciseSampleForLapEnd(lap);
    lap.setHeartRateSplit(sampleAtLapEnd.getHeartRate());
    if (lap.getSpeed() != null) {
      lapDistanceSum+=lap.getSpeed().getDistance();
      lap.getSpeed().setDistance(lapDistanceSum);
      lap.getSpeed().setSpeedEnd(sampleAtLapEnd.getSpeed() == null ? 0 : sampleAtLapEnd.getSpeed());
      lap.getSpeed().setCadence(sampleAtLapEnd.getCadence());
    }
    if (lap.getAltitude() != null) {
      lap.setAltitude(lap.getAltitude().copy((short)sampleAtLapEnd.getAltitude(),lap.getAltitude().getAscent()));
    }
    if (temperatureAvailable) {
      lap.setTemperature(new LapTemperature(sampleAtLapEnd.getTemperature()));
    }
  }
  exercise.getLapList().addAll(lLaps);
}
Program: 168391
Project: 168391
Buggy source:
/** 
 * Calculates the min, max and average altitude (if available) from the sample data.
 */
private void calculateAltitudeSummary(){
  if (exercise.getRecordingMode().isAltitude() && exercise.getSampleList().size() > 0) {
    short altMin=Short.MAX_VALUE;
    short altMax=Short.MIN_VALUE;
    int altitudeSum=0;
    for (    ExerciseSample sample : exercise.getSampleList()) {
      altMin=(short)Math.min(sample.getAltitude(),altMin);
      altMax=(short)Math.max(sample.getAltitude(),altMax);
      altitudeSum+=sample.getAltitude();
    }
    exercise.getAltitude().setAltitudeMin(altMin);
    exercise.getAltitude().setAltitudeMax(altMax);
    exercise.getAltitude().setAltitudeAvg((short)(Math.round(altitudeSum / (double)exercise.getSampleList().size())));
  }
}

Fixed version (ground truth):
/** 
 * Calculates the min, max and average altitude (if available) from the sample data.
 */
private void calculateAltitudeSummary(){
  if (exercise.getRecordingMode().isAltitude() && exercise.getSampleList().size() > 0) {
    short altMin=Short.MAX_VALUE;
    short altMax=Short.MIN_VALUE;
    int altitudeSum=0;
    for (    ExerciseSample sample : exercise.getSampleList()) {
      short sampleAltitude=sample.getAltitude() == null ? 0 : sample.getAltitude();
      altMin=(short)Math.min(sampleAltitude,altMin);
      altMax=(short)Math.max(sampleAltitude,altMax);
      altitudeSum+=sampleAltitude;
    }
    exercise.getAltitude().setAltitudeMin(altMin);
    exercise.getAltitude().setAltitudeMax(altMax);
    exercise.getAltitude().setAltitudeAvg((short)(Math.round(altitudeSum / (double)exercise.getSampleList().size())));
  }
}
Program: 168392
Project: 168392
Buggy source:
private String readDatabaseSchema() throws STException {
  try {
    final List<String> lines=Files.readAllLines(Paths.get(this.getClass().getResource(SCHEMA_FILE).toURI()));
    return lines.stream().collect(Collectors.joining("String_Node_Str"));
  }
 catch (  IOException|URISyntaxException e) {
    throw new STException(STExceptionID.SQLITE_EXPORT,"String_Node_Str" + SCHEMA_FILE + "String_Node_Str",e);
  }
}

Fixed version (ground truth):
private String readDatabaseSchema() throws STException {
  try (BufferedReader reader=new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(SCHEMA_FILE)))){
    StringBuffer fileContent=new StringBuffer();
    String line;
    while ((line=reader.readLine()) != null) {
      fileContent.append(line).append('\n');
    }
    return fileContent.toString();
  }
 catch (  IOException e) {
    throw new STException(STExceptionID.SQLITE_EXPORT,"String_Node_Str" + SCHEMA_FILE + "String_Node_Str",e);
  }
}
Program: 168393
Project: 168393
Buggy source:
/** 
 * Reads HRM device information from the specified DeviceInfoMesg message.
 * @param mesg device info message
 */
private void readDeviceInfoMessage(DeviceInfoMesg mesg){
  final Integer garminProductId=mesg.getGarminProduct();
  if (garminProductId != null && garminProductId.intValue() != 0) {
    String deviceName="String_Node_Str" + getGarminProductConstantName(garminProductId);
    exercise.setDeviceName(deviceName);
  }
}

Fixed version (ground truth):
/** 
 * Reads HRM device information from the specified DeviceInfoMesg message.
 * @param mesg device info message
 */
private void readDeviceInfoMessage(DeviceInfoMesg mesg){
  final Integer garminProductId=mesg.getGarminProduct();
  if (garminProductId != null && garminProductId.intValue() > 100) {
    String productName=getGarminProductConstantName(garminProductId);
    if (productName != null) {
      exercise.setDeviceName("String_Node_Str" + productName);
    }
  }
}
Program: 168396
Project: 168396
Buggy source:
private void setupMapViewer(){
  mapKit=new JXMapKit();
  mapKit.setDefaultProvider(JXMapKit.DefaultProviders.OpenStreetMaps);
  mapKit.setBorder(new javax.swing.border.EmptyBorder(8,8,8,8));
  mouseMotionListener=new MouseMotionAdapter(){
    @Override public void mouseMoved(    MouseEvent e){
      lookupNearbySampleAndCreateToolTip(e);
    }
  }
;
  mapKit.getMainMap().addMouseMotionListener(mouseMotionListener);
  snMapViewer.setContent(mapKit);
}

Fixed version (ground truth):
private void setupMapViewer(){
  mapKit=new JXMapKit();
  mapKit.setDefaultProvider(JXMapKit.DefaultProviders.OpenStreetMaps);
  mapKit.setBorder(new javax.swing.border.EmptyBorder(8,8,8,8));
  mouseMotionListener=new MouseMotionAdapter(){
    @Override public void mouseMoved(    MouseEvent e){
      lookupNearbySampleAndCreateToolTip(e);
    }
  }
;
  mapKit.getMainMap().addMouseMotionListener(mouseMotionListener);
  mapKit.setVisible(false);
  snMapViewer.setContent(mapKit);
}
Program: 168397
Project: 168397
Buggy source:
/** 
 * Sets the zoom level and map center position. The full track will be visible with as much details as possible. This implementations is a workaround for a bug in JXMapViewer.calculateZoomFrom(), which should do the same.
 * @param positions list of positions of the route
 */
private void setupZoomAndCenterPosition(List<GeoPosition> positions){
  Rectangle2D gpRectangle=createGeoPositionRectangle(positions);
  GeoPosition gpCenter=new GeoPosition(gpRectangle.getCenterX(),gpRectangle.getCenterY());
  mapKit.setCenterPosition(gpCenter);
  Bounds mapViewerBounds=snMapViewer.getLayoutBounds();
  int mapKitWidth=(int)mapViewerBounds.getWidth() - 30;
  int mapKitHeight=(int)mapViewerBounds.getHeight() - 30;
  boolean fullTrackVisible=false;
  int currentZoom=0;
  int maxZoom=mapKit.getMainMap().getTileFactory().getInfo().getMaximumZoomLevel();
  while (!fullTrackVisible && currentZoom < maxZoom) {
    currentZoom++;
    mapKit.setZoom(currentZoom);
    Point2D ptTopLeft=convertGeoPosToPixelPos(new GeoPosition(gpRectangle.getX(),gpRectangle.getY()));
    Point2D ptBottomRight=convertGeoPosToPixelPos(new GeoPosition(gpRectangle.getX() + gpRectangle.getWidth(),gpRectangle.getY() + gpRectangle.getHeight()));
    int trackPixelWidth=Math.abs((int)(ptBottomRight.getX() - ptTopLeft.getX()));
    int trackPixelHeight=Math.abs((int)(ptBottomRight.getY() - ptTopLeft.getY()));
    fullTrackVisible=trackPixelWidth < mapKitWidth && trackPixelHeight < mapKitHeight;
  }
}

Fixed version (ground truth):
/** 
 * Sets the zoom level and map center position. The full track will be visible with as much details as possible. This implementations is a workaround for a bug in JXMapViewer.calculateZoomFrom(), which should do the same.
 * @param positions list of positions of the route
 */
private void setupZoomAndCenterPosition(List<GeoPosition> positions){
  Rectangle2D gpRectangle=createGeoPositionRectangle(positions);
  GeoPosition gpCenter=new GeoPosition(gpRectangle.getCenterX(),gpRectangle.getCenterY());
  mapKit.setCenterPosition(gpCenter);
  Bounds mapViewerBounds=spTrack.getLayoutBounds();
  int mapKitWidth=(int)mapViewerBounds.getWidth() - 30;
  int mapKitHeight=(int)mapViewerBounds.getHeight() - 30;
  boolean fullTrackVisible=false;
  int currentZoom=0;
  int maxZoom=mapKit.getMainMap().getTileFactory().getInfo().getMaximumZoomLevel();
  while (!fullTrackVisible && currentZoom < maxZoom) {
    currentZoom++;
    mapKit.setZoom(currentZoom);
    Point2D ptTopLeft=convertGeoPosToPixelPos(new GeoPosition(gpRectangle.getX(),gpRectangle.getY()));
    Point2D ptBottomRight=convertGeoPosToPixelPos(new GeoPosition(gpRectangle.getX() + gpRectangle.getWidth(),gpRectangle.getY() + gpRectangle.getHeight()));
    int trackPixelWidth=Math.abs((int)(ptBottomRight.getX() - ptTopLeft.getX()));
    int trackPixelHeight=Math.abs((int)(ptBottomRight.getY() - ptTopLeft.getY()));
    fullTrackVisible=trackPixelWidth < mapKitWidth && trackPixelHeight < mapKitHeight;
  }
}