auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Mono<ServiceMessage> invokeOne( ServiceMessage message, BiFunction<ServiceMessage, Class<?>, ServiceMessage> dataDecoder) { Supplier<Mono<ServiceMessage>> invoke = () -> { Object request = toRequest(message, dataDecoder); return Mono.from(invoke(request)).map(this::toResponse); }; return Mono.defer(invoke) .onErrorResume(throwable -> Mono.just(errorMapper.toMessage(throwable))); }

Target:
public Mono<ServiceMessage> invokeOne( ServiceMessage message, BiFunction<ServiceMessage, Class<?>, ServiceMessage> dataDecoder) { return Mono.defer(() -> Mono.from(invoke(toRequest(message, dataDecoder)))) .map(this::toResponse) .onErrorResume(throwable -> Mono.just(errorMapper.toMessage(throwable))); }
Source:
public void testPersistWithEmbeddedList() throws Exception { final Session session = openSession(); Transaction transaction = session.beginTransaction(); User wombatSoftware = new User( "2", "Wombat Software 2" ); wombatSoftware.setList( new EmbeddedList( "New List", Arrays.asList( "1", "2" ))); session.persist( wombatSoftware ); transaction.commit(); session.clear(); transaction = session.beginTransaction(); User loadedUser = (User) session.get( User.class, wombatSoftware.getId() ); assertThat( loadedUser ).as( "Cannot load persisted object with nested embeddedables" ).isNotNull(); assertThat( loadedUser.getList() ).isNotNull(); assertThat( loadedUser.getList().getName() ).isEqualTo( wombatSoftware.getList().getName() ); assertThat( loadedUser.getList().getList() ).containsOnly( "1", "2" ); session.delete( loadedUser ); transaction.commit(); session.clear(); transaction = session.beginTransaction(); assertThat( session.get( User.class, wombatSoftware.getId() ) ).isNull(); transaction.commit(); session.close(); }

Target:
public void testPersistWithEmbeddedList() throws Exception { final Session session = openSession(); Transaction transaction = session.beginTransaction(); List<String> alternativePhones = Arrays.asList( "+1-222-555-0222", "+1-202-555-0333" ); AccountWithPhone account = new AccountWithPhone( "2", "Mobile account 2" ); account.setPhoneNumber( new PhoneNumber( "+1-222-555-0111", alternativePhones ) ); session.persist( account ); transaction.commit(); session.clear(); transaction = session.beginTransaction(); AccountWithPhone loadedUser = (AccountWithPhone) session.get( AccountWithPhone.class, account.getId() ); assertThat( loadedUser ).as( "Cannot load persisted object with nested embeddedables" ).isNotNull(); assertThat( loadedUser.getPhoneNumber() ).isNotNull(); assertThat( loadedUser.getPhoneNumber().getMain() ).isEqualTo( account.getPhoneNumber().getMain() ); assertThat( loadedUser.getPhoneNumber().getAlternatives() ).containsOnly( alternativePhones.toArray( new Object[alternativePhones.size()] ) ); session.delete( loadedUser ); transaction.commit(); session.clear(); transaction = session.beginTransaction(); assertThat( session.get( AccountWithPhone.class, account.getId() ) ).isNull(); transaction.commit(); session.close(); }
Source:
public void begin(RepositorySessionBeginDelegate delegate) throws InvalidSessionTransitionException { Cursor cur; try { Logger.debug(LOG_TAG, "Check and build special GUIDs."); dataAccessor.checkAndBuildSpecialGuids(); cur = dataAccessor.getGuidsIDsForFolders(); Logger.debug(LOG_TAG, "Got GUIDs for folders."); } catch (android.database.sqlite.SQLiteConstraintException e) { Logger.error(LOG_TAG, "Got sqlite constraint exception working with Fennec bookmark DB.", e); delegate.onBeginFailed(e); return; } catch (NullCursorException e) { delegate.onBeginFailed(e); return; } catch (Exception e) { delegate.onBeginFailed(e); return; } Logger.debug(LOG_TAG, "Preparing folder ID mappings."); Logger.debug(LOG_TAG, "Tracking places root as ID 0."); parentIDToGuidMap.put(0L, "places"); parentGuidToIDMap.put("places", 0L); try { cur.moveToFirst(); while (!cur.isAfterLast()) { String guid = getGUID(cur); long id = RepoUtils.getLongFromCursor(cur, BrowserContract.Bookmarks._ID); parentGuidToIDMap.put(guid, id); parentIDToGuidMap.put(id, guid); Logger.debug(LOG_TAG, "GUID " + guid + " maps to " + id); cur.moveToNext(); } } finally { cur.close(); } deletionManager = new BookmarksDeletionManager(dataAccessor, DEFAULT_DELETION_FLUSH_THRESHOLD); Set<String> guidsKnownBeforeInsertions = new HashSet<String>(parentGuidToIDMap.keySet()); insertionManager = new AndroidBrowserBookmarksInsertionManager(DEFAULT_INSERTION_FLUSH_THRESHOLD, guidsKnownBeforeInsertions); Logger.debug(LOG_TAG, "Done with initial setup of bookmarks session."); super.begin(delegate); }

Target:
public void begin(RepositorySessionBeginDelegate delegate) throws InvalidSessionTransitionException { Cursor cur; try { Logger.debug(LOG_TAG, "Check and build special GUIDs."); dataAccessor.checkAndBuildSpecialGuids(); cur = dataAccessor.getGuidsIDsForFolders(); Logger.debug(LOG_TAG, "Got GUIDs for folders."); } catch (android.database.sqlite.SQLiteConstraintException e) { Logger.error(LOG_TAG, "Got sqlite constraint exception working with Fennec bookmark DB.", e); delegate.onBeginFailed(e); return; } catch (NullCursorException e) { delegate.onBeginFailed(e); return; } catch (Exception e) { delegate.onBeginFailed(e); return; } Logger.debug(LOG_TAG, "Preparing folder ID mappings."); Logger.debug(LOG_TAG, "Tracking places root as ID 0."); parentIDToGuidMap.put(0L, "places"); parentGuidToIDMap.put("places", 0L); try { cur.moveToFirst(); while (!cur.isAfterLast()) { String guid = getGUID(cur); long id = RepoUtils.getLongFromCursor(cur, BrowserContract.Bookmarks._ID); parentGuidToIDMap.put(guid, id); parentIDToGuidMap.put(id, guid); Logger.debug(LOG_TAG, "GUID " + guid + " maps to " + id); cur.moveToNext(); } } finally { cur.close(); } deletionManager = new BookmarksDeletionManager(dataAccessor, DEFAULT_DELETION_FLUSH_THRESHOLD); insertionManager = new BookmarksInsertionManager(DEFAULT_INSERTION_FLUSH_THRESHOLD, parentGuidToIDMap.keySet(), this); Logger.debug(LOG_TAG, "Done with initial setup of bookmarks session."); super.begin(delegate); }
Source:
private synchronized void deleteFailedCommand(Command command) { int indexOfCommand = mCommandList.indexOf(command); mCommandList.remove(indexOfCommand); mCommandCounter--; mCommandIndex--; if (mCommandCounter == 1) { UndoRedoManager.getInstance().update( UndoRedoManager.StatusMode.DISABLE_UNDO); } }

Target:
private synchronized void deleteFailedCommand(Command command) { int indexOfCommand = mCommandList.indexOf(command); ((BaseCommand) mCommandList.remove(indexOfCommand)).freeResources(); mCommandCounter--; mCommandIndex--; if (mCommandCounter == 1) { UndoRedoManager.getInstance().update( UndoRedoManager.StatusMode.DISABLE_UNDO); } }
Source:
public EventResult onImpulse(ImpulseEvent event, EntityRef entity) { float mass = entity.getComponent(BodyLinked.class).get().getMass(); float damage = event.getMagnitude() / mass; if (entity.hasComponent(Durability.class)) { entity.getComponent(Durability.class).get().getDurability(); } entitySystemManager.sendEvent(new DamageEvent((int) damage), entity); return EventResult.CONTINUE; }

Target:
public EventResult onImpulse(ImpulseEvent event, EntityRef entity) { float mass = entity.getComponent(BodyLinked.class).get().getMass(); float damage = event.getMagnitude() / mass; if (entity.hasComponent(Durability.class)) { float durability = entity.getComponent(Durability.class).get().getDurability(); damage /= durability; } entitySystemManager.sendEvent(new DamageEvent(damage), entity); return EventResult.CONTINUE; }
Source:
public void testProcessSingle() { Trace trace = new Trace(); trace.setId("btxnId"); trace.setBusinessTransaction("btxnName"); trace.setStartTime(100); Consumer c = new Consumer(); c.setUri("uri"); c.setBaseTime(1); c.setDuration(200000000); c.getProperties().add(new Property(Constants.PROP_FAULT, "myFault")); c.setEndpointType("HTTP"); trace.getNodes().add(c); FragmentCompletionTimeDeriver deriver = new FragmentCompletionTimeDeriver(); CompletionTime ct = null; try { ct = deriver.processOneToOne(null, trace); } catch (Exception e) { fail("Failed: " + e); } assertNotNull(ct); assertEquals(trace.getId(), ct.getId()); assertEquals(trace.getBusinessTransaction(), ct.getBusinessTransaction()); assertEquals(c.getEndpointType(), ct.getEndpointType()); assertFalse(ct.isInternal()); assertEquals(trace.getStartTime(), ct.getTimestamp()); assertEquals(c.getUri(), ct.getUri()); assertEquals(200000000, ct.getDuration()); assertEquals(c.getProperties(Constants.PROP_FAULT), ct.getProperties(Constants.PROP_FAULT)); }

Target:
public void testProcessSingle() { Trace trace = new Trace(); trace.setId("btxnId"); trace.setBusinessTransaction("btxnName"); trace.setStartTime(100000); Consumer c = new Consumer(); c.setUri("uri"); c.setBaseTime(1); c.setDuration(200000); c.getProperties().add(new Property(Constants.PROP_FAULT, "myFault")); c.setEndpointType("HTTP"); trace.getNodes().add(c); FragmentCompletionTimeDeriver deriver = new FragmentCompletionTimeDeriver(); CompletionTime ct = null; try { ct = deriver.processOneToOne(null, trace); } catch (Exception e) { fail("Failed: " + e); } assertNotNull(ct); assertEquals(trace.getId(), ct.getId()); assertEquals(trace.getBusinessTransaction(), ct.getBusinessTransaction()); assertEquals(c.getEndpointType(), ct.getEndpointType()); assertFalse(ct.isInternal()); assertEquals(trace.getStartTime(), ct.getTimestamp()); assertEquals(c.getUri(), ct.getUri()); assertEquals(200000, ct.getDuration()); assertEquals(c.getProperties(Constants.PROP_FAULT), ct.getProperties(Constants.PROP_FAULT)); }
Source:
public void setRetentionTimeout(int retentionTimeout) { if (retentionTimeout < DEFAULT_RETENTION_TIMEOUT_MINUTES) { this.retentionTimeout = DEFAULT_RETENTION_TIMEOUT_MINUTES; } else { this.retentionTimeout = retentionTimeout; } }

Target:
public void setRetentionTimeout(int retentionTimeout) { this.retentionTimeout = Math.max(DEFAULT_RETENTION_TIMEOUT_MINUTES, retentionTimeout); }
Source:
public Future<BlobInfo> getBlobInfo(String blobId) { FutureResult<BlobInfo> futureResult = new FutureResult<BlobInfo>(); OperationController oc = getOperationController(); if (oc == null) { completeOperation(futureResult, null, null, ROUTER_CLOSED_EXCEPTION); } else { oc.getBlobInfo(blobId, futureResult, null); } return futureResult; }

Target:
public Future<BlobInfo> getBlobInfo(String blobId) { return getBlobInfo(blobId, null); }
Source:
void remove(DfsPackFile pack) { packCache.remove(pack.getPackDescription()); removeRef(pack.key); }

Target:
void remove(DfsPackFile pack) { packCache.remove(pack.getPackDescription()); }
Source:
public DatabaseInfo getDatabaseInfo() throws IOException { LOG.info("Geting database information from database: " + mGlueDbName + "."); try { GetDatabaseRequest dbRequest = new GetDatabaseRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withName(mGlueDbName); GetDatabaseResult dbResult = mGlueClient.getDatabase(dbRequest); Database glueDatabase = dbResult.getDatabase(); String glueDbLocation = glueDatabase.getLocationUri(); String glueDbDescription = glueDatabase.getDescription(); Map<String, String> glueParameters = new HashMap<>(); if (glueDatabase.getParameters() != null) { glueParameters = glueDatabase.getParameters(); } return new DatabaseInfo( glueDbLocation, mOwnerName, mOwnerType, glueDbDescription, glueParameters); } catch (EntityNotFoundException e) { throw new IOException("Cannot find glue database" + mGlueDbName + "." + e.getMessage(), e); } }

Target:
public DatabaseInfo getDatabaseInfo() throws IOException { try { GetDatabaseRequest dbRequest = new GetDatabaseRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withName(mGlueDbName); GetDatabaseResult dbResult = mGlueClient.getDatabase(dbRequest); Database glueDatabase = dbResult.getDatabase(); String glueDbLocation = glueDatabase.getLocationUri(); String glueDbDescription = glueDatabase.getDescription(); Map<String, String> glueParameters = new HashMap<>(); Map<String, String> parameters = glueDatabase.getParameters(); if (parameters != null) { for (Map.Entry parameter : parameters.entrySet()) { glueParameters.put(parameter.getKey().toString(), parameter.getValue().toString()); } } return new DatabaseInfo( glueDbLocation, mOwnerName, mOwnerType, glueDbDescription, glueParameters); } catch (EntityNotFoundException e) { throw new IOException("Cannot find glue database: " + mGlueDbName + "Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ". " + e.getMessage(), e); } }
Source:
private void segmentInsert(final int index, final SequenceSegment segment) { for (int height = 0; height < segment.getSources().size(); height++) { if (index + height < lanes.size()) { lanes.set(index + height, segment.getUnifiedEnd()); } else { lanes.add(index + height, segment.getUnifiedEnd()); } } }

Target:
private void segmentInsert(final int index, final SequenceSegment segment) { for (int height = 0; height < segment.getSources().size(); height++) { int position = index + height; if (position < lanes.size()) { lanes.set(position, segment.getUnifiedEnd()); } else { lanes.add(position, segment.getUnifiedEnd()); } } }
Source:
private ResponseEntity<Object> listStudySubjects(String studyOid, String siteOid, HttpServletRequest request) throws Exception { ResponseEntity<Object> response = null; try { StudyBean study = null; try { study = this.getRestfulServiceHelper().setSchema(studyOid, request); study = participantService.validateRequestAndReturnStudy(studyOid, siteOid,request); } catch (OpenClinicaSystemException e) { String errorMsg = e.getErrorCode(); HashMap<String, String> map = new HashMap<>(); map.put("studyOid", studyOid); map.put("siteOid", siteOid); ParameterizedErrorVM responseDTO =new ParameterizedErrorVM(errorMsg, map); response = new ResponseEntity(responseDTO, HttpStatus.BAD_REQUEST); return response; } if(study != null) { ResponseSuccessListAllParticipantsByStudyDTO responseSuccess = new ResponseSuccessListAllParticipantsByStudyDTO(); ArrayList<StudyParticipantDTO> studyParticipantDTOs = getStudyParticipantDTOs(studyOid, siteOid,study); responseSuccess.setStudyParticipants(studyParticipantDTOs); responseSuccess.setSiteOID(siteOid); if (siteOid != null) { StudyBean site = this.getStudyDAO().findByOid(siteOid); responseSuccess.setSiteID(site.getId()); responseSuccess.setSiteName(site.getName()); } else { responseSuccess.setSiteID(0); responseSuccess.setSiteName(null); } response = new ResponseEntity(responseSuccess, org.springframework.http.HttpStatus.OK); } } catch (Exception eee) { eee.printStackTrace(); throw eee; } return response; }

Target:
private ResponseEntity<Object> listStudySubjects(String studyOid, String siteOid, HttpServletRequest request) throws Exception { ResponseEntity<Object> response = null; try { StudyBean study = null; try { study = this.getRestfulServiceHelper().setSchema(studyOid, request); study = participantService.validateRequestAndReturnStudy(studyOid, siteOid,request); } catch (OpenClinicaSystemException e) { String errorMsg = e.getErrorCode(); HashMap<String, String> map = new HashMap<>(); map.put("studyOid", studyOid); map.put("siteOid", siteOid); ParameterizedErrorVM responseDTO =new ParameterizedErrorVM(errorMsg, map); response = new ResponseEntity(responseDTO, HttpStatus.BAD_REQUEST); return response; } if(study != null) { ResponseSuccessListAllParticipantsByStudyDTO responseSuccess = new ResponseSuccessListAllParticipantsByStudyDTO(); ArrayList<StudyParticipantDTO> studyParticipantDTOs = getStudyParticipantDTOs(studyOid, siteOid,study); responseSuccess.setStudyParticipants(studyParticipantDTOs); responseSuccess.setSiteOID(siteOid); if (siteOid != null) { StudyBean site = this.getStudyDAO().findByOid(siteOid); responseSuccess.setSiteID(site.getId()); responseSuccess.setSiteName(site.getName()); } response = new ResponseEntity(responseSuccess, org.springframework.http.HttpStatus.OK); } } catch (Exception eee) { eee.printStackTrace(); throw eee; } return response; }
Source:
public Frame clone() { Frame newFrame = new Frame(); newFrame.imageWidth = imageWidth; newFrame.imageHeight = imageHeight; newFrame.imageDepth = imageDepth; newFrame.imageChannels = imageChannels; newFrame.imageStride = imageStride; newFrame.keyFrame = keyFrame; newFrame.streamIndex = streamIndex; newFrame.opaque = new Pointer[3]; if (image != null) { newFrame.image = new Buffer[image.length]; ((Pointer[])newFrame.opaque)[0] = cloneBufferArray(image, newFrame.image); } newFrame.audioChannels = audioChannels; newFrame.sampleRate = sampleRate; if (samples != null) { newFrame.samples = new Buffer[samples.length]; ((Pointer[])newFrame.opaque)[1] = cloneBufferArray(samples, newFrame.samples); } if (data != null) { newFrame.data = ByteBuffer.allocate(data.capacity()); BytePointer pointer = new BytePointer(data.capacity()); newFrame.data = pointer.limit(pointer.position() + data.limit()) .asByteBuffer().put((ByteBuffer)data); pointer.position(pointer.limit()); data.rewind(); newFrame.data.rewind(); ((Pointer[])newFrame.opaque)[2] = pointer; } newFrame.timestamp = timestamp; return newFrame; }

Target:
public Frame clone() { Frame newFrame = new Frame(); newFrame.imageWidth = imageWidth; newFrame.imageHeight = imageHeight; newFrame.imageDepth = imageDepth; newFrame.imageChannels = imageChannels; newFrame.imageStride = imageStride; newFrame.keyFrame = keyFrame; newFrame.streamIndex = streamIndex; newFrame.opaque = new Pointer[3]; if (image != null) { newFrame.image = new Buffer[image.length]; ((Pointer[])newFrame.opaque)[0] = cloneBufferArray(image, newFrame.image); } newFrame.audioChannels = audioChannels; newFrame.sampleRate = sampleRate; if (samples != null) { newFrame.samples = new Buffer[samples.length]; ((Pointer[])newFrame.opaque)[1] = cloneBufferArray(samples, newFrame.samples); } if (data != null) { ByteBuffer[] dst = new ByteBuffer[1]; ((Pointer[])newFrame.opaque)[2] = cloneBufferArray(new ByteBuffer[]{data}, dst); newFrame.data = dst[0]; } newFrame.timestamp = timestamp; return newFrame; }
Source:
public Optional<TokenCredentials> extract(WebContext context) { final String header = context.getRequestHeader(this.headerName); if (header == null) { return Optional.empty(); } if (!header.startsWith(this.prefixHeader)) { throw new CredentialsException("Wrong prefix for header: " + this.headerName); } final String headerWithoutPrefix = header.substring(this.prefixHeader.length()); return Optional.of(new TokenCredentials(headerWithoutPrefix)); }

Target:
public Optional<TokenCredentials> extract(WebContext context) { final Optional<String> header = context.getRequestHeader(this.headerName); if (!header.isPresent()) { return Optional.empty(); } if (!header.get().startsWith(this.prefixHeader)) { throw new CredentialsException("Wrong prefix for header: " + this.headerName); } final String headerWithoutPrefix = header.get().substring(this.prefixHeader.length()); return Optional.of(new TokenCredentials(headerWithoutPrefix)); }
Source:
public void testToJSONWithRawJSONData() throws IOException { long timestampMillis = 1496712943487L; Position position = new Position(new BinlogPosition(1L, "binlog-0001"), 0L); RowMap rowMap = new RowMap("insert", "MyDatabase", "MyTable", timestampMillis, null, position); rowMap.putData("id", "9001"); rowMap.putData("first_name", "foo"); rowMap.putData("middle_name", "buzz"); rowMap.putData("last_name", "bar"); rowMap.putData("salary", "4000"); rowMap.putData("department", "science"); rowMap.putData("rawJSON", new RawJSONString("{\"database\":\"MyDatabase\",\"table\":\"User\",\"type\":\"insert\",\"ts\":1486439516,\"xid\":5694,\"commit\":true,\"data\":{\"UserID\":20,\"FirstName\":\"Fiz\",\"MiddleName\":null,\"LastName\":\"Buz\",\"Version\":1486703131000}}\n")); MaxwellOutputConfig outputConfig = getMaxwellOutputConfig(); Assert.assertEquals("{\"database\":\"MyDatabase\",\"table\":\"MyTable\",\"type\":\"insert\",\"ts\":1496712943,\"position\":\"binlog-0001:1\",\"gtid\":null,\"data\":{\"id\":\"9001\",\"salary\":\"4000\",\"department\":\"science\",\"rawJSON\":{\"database\":\"MyDatabase\",\"table\":\"User\",\"type\":\"insert\",\"ts\":1486439516,\"xid\":5694,\"commit\":true,\"data\":{\"UserID\":20,\"FirstName\":\"Fiz\",\"MiddleName\":null,\"LastName\":\"Buz\",\"Version\":1486703131000}}\n" + "}}", rowMap.toJSON(outputConfig)); }

Target:
public void testToJSONWithRawJSONData() throws IOException { RowMap rowMap = new RowMap("insert", "MyDatabase", "MyTable", TIMESTAMP_MILLISECONDS, new ArrayList<String>(), POSITION); rowMap.setServerId(7653213L); rowMap.setThreadId(6532312L); rowMap.putData("id", "9001"); rowMap.putData("first_name", "foo"); rowMap.putData("last_name", "bar"); rowMap.putData("rawJSON", new RawJSONString("{\"UserID\":20}")); MaxwellOutputConfig outputConfig = getMaxwellOutputConfig(); Assert.assertEquals("{\"database\":\"MyDatabase\",\"table\":\"MyTable\",\"type\":\"insert\"," + "\"ts\":1496712943,\"position\":\"binlog-0001:1\",\"gtid\":null,\"server_id\":7653213,\"thread_id\":6532312," + "\"data\":{\"id\":\"9001\",\"first_name\":\"foo\",\"last_name\":\"bar\",\"rawJSON\":{\"UserID\":20}}}", rowMap.toJSON(outputConfig)); }
Source:
private void assertCounts(int totalConnectionsCount, int availableCount) { Assert.assertEquals(totalConnectionsCount, connectionTracker.getTotalConnectionsCount()); Assert.assertEquals(availableCount, connectionTracker.getAvailableConnectionsCount()); }

Target:
private void assertCounts(int totalConnectionsCount, int availableCount) { Assert.assertEquals("total connections should match", totalConnectionsCount, connectionTracker.getTotalConnectionsCount()); Assert.assertEquals("available connections should match", availableCount, connectionTracker.getAvailableConnectionsCount()); }
Source:
public void testNaughtyClassFieldOfDescription() throws Exception { Description description = mock(Description.class); String className = "Illegal Class Name!"; when(description.getClassName()).thenReturn(className); Map<String, String> fakeSuites = mock(Map.class); when(fakeSuites.containsKey(anyString())).thenReturn(false); when(runListener.getSuites()).thenReturn(fakeSuites); ArgumentCaptor<Description> generatedDescription = ArgumentCaptor.forClass(Description.class); doNothing().when(runListener).testSuiteStarted(any(Description.class)); runListener.getSuiteUid(description); verify(runListener).testSuiteStarted(generatedDescription.capture()); Assert.assertEquals(className, generatedDescription.getValue().getClassName()); }

Target:
public void testNaughtyClassFieldOfDescription() throws Exception { Description description = mock(Description.class); String className = "Illegal Class Name!"; when(description.getClassName()).thenReturn(className); Map<String, String> fakeSuites = mock(Map.class); when(fakeSuites.containsKey(anyString())).thenReturn(false); when(runListener.getSuites()).thenReturn(fakeSuites); ArgumentCaptor<Description> generatedDescription = ArgumentCaptor.forClass(Description.class); doNothing().when(runListener).testSuiteStarted(any(Description.class)); runListener.getSuiteUid(description); verify(runListener).testSuiteStarted(generatedDescription.capture()); assertThat(generatedDescription.getValue().getClassName(), equalTo(className)); }
Source:
public void claimTaskTest() { final TaskSummary task = TaskSummary.builder().id(TASK_ID).deploymentId(TASK_DEPLOYMENT_ID).status("Ready").build(); getPresenter().claimTask(task); verify(taskService).claimTask("", TASK_DEPLOYMENT_ID, TASK_ID); }

Target:
public void claimTaskTest() { final TaskSummary task = TaskSummary.builder().id(TASK_ID).deploymentId(TASK_DEPLOYMENT_ID).build(); getPresenter().claimTask(task); verify(taskService).claimTask("", TASK_DEPLOYMENT_ID, TASK_ID); verify(viewMock).displayNotification(any()); }
Source:
public void setPriority(int priority) { int new_nice = NICE_VALUES[priority - 1]; Process.setThreadPriority(new_nice); }

Target:
public void setPriority(int priority) { if (priority < 1) { priority = 1; } else if (priority > 10) { priority = 10; } Process.setThreadPriority(NICE_VALUES[priority - 1]); }
Source:
public Object getMsgHandlerInstance(ForkliftMessage msg) throws InvocationTargetException, IOException, InstantiationException, IllegalAccessException { Object instance = this.constructMessageHandlerInstance(msg, new ArrayList<>()); inject(msg, instance); return instance; }

Target:
public Object getMsgHandlerInstance(ForkliftMessage msg) { Object instance = null; try { instance = this.constructMessageHandlerInstance(msg, new ArrayList<>()); inject(msg, instance); } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler Constructor"); } return instance; }
Source:
private void printHeadlines( GenericMessageEvent event, String category ) { SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = null; try { feed = input.build( new XmlReader( newsFeedsByCategory.get( category ) ) ); } catch ( FeedException | IOException e ) { logger.error( e.getMessage() ); logger.error( "Error opening RSS feed" ); } List<SyndEntry> entries = feed.getEntries(); for ( int i = 0; i < NUM_HEADLINES; i++ ) { event.respondWith( entries.get( i ).getTitle() + " -> " + entries.get( i ).getLink() ); } }

Target:
private void printHeadlines( GenericMessageEvent event, String category ) { SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = null; try { feed = input.build( new XmlReader( newsFeedsByCategory.get( category ) ) ); } catch ( FeedException | IOException e ) { String errorMsg = "Error opening RSS feed"; logger.error( e.getMessage() ); logger.error( errorMsg ); event.respondWith( errorMsg ); } List<SyndEntry> entries = feed.getEntries(); for ( int i = 0; i < NUM_HEADLINES; i++ ) { event.respondWith( entries.get( i ).getTitle() + " -> " + entries.get( i ).getLink() ); } }
Source:
public void define(NewController context) { WebService.NewAction action = context.createAction(ACTION_DELETE) .setSince("6.6") .setDescription("Delete a non-main branch of a project") .setResponseExample(Resources.getResource(getClass(), "list-example.json")) .setInternal(true) .setPost(true) .setHandler(this); action .createParam(PARAM_PROJECT) .setDescription("Project key") .setExampleValue(KEY_PROJECT_EXAMPLE_001) .setRequired(true); action .createParam(PARAM_BRANCH) .setDescription("Name of the branch to delete. Can't be the main branch of the project.") .setExampleValue("branch1") .setRequired(true); }

Target:
public void define(NewController context) { WebService.NewAction action = context.createAction(ACTION_DELETE) .setSince("6.6") .setDescription("Delete a non-main branch of a project. Requires permission to administer the project.") .setResponseExample(Resources.getResource(getClass(), "list-example.json")) .setInternal(true) .setPost(true) .setHandler(this); action .createParam(PARAM_PROJECT) .setDescription("Project key") .setExampleValue(KEY_PROJECT_EXAMPLE_001) .setRequired(true); action .createParam(PARAM_BRANCH) .setDescription("Name of the branch to delete. Can't be the main branch of the project.") .setExampleValue("branch1") .setRequired(true); }
Source:
public void cherryPick() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master%topic=someTopic"); CherryPickInput in = new CherryPickInput(); in.destination = "foo"; in.message = "it goes to stable branch"; gApi.projects() .name(project.get()) .branch(in.destination) .create(new BranchInput()); ChangeApi orig = gApi.changes() .id("p~master~" + r.getChangeId()); assertThat((Iterable<?>)orig.get().messages).hasSize(1); ChangeApi cherry = orig.revision(r.getCommit().name()) .cherryPick(in); assertThat((Iterable<?>)orig.get().messages).hasSize(2); Iterator<ChangeMessageInfo> origIt = orig.get().messages.iterator(); origIt.next(); assertThat(origIt.next().message) .startsWith("Patch Set 1: Cherry Picked\n\nThis patchset was cherry picked to branch foo as commit "); assertThat(cherry.get().subject).contains(in.message); assertThat(cherry.get().topic).isEqualTo("someTopic"); cherry.current().review(ReviewInput.approve()); cherry.current().submit(); }

Target:
public void cherryPick() throws Exception { PushOneCommit.Result r = pushTo("refs/for/master%topic=someTopic"); CherryPickInput in = new CherryPickInput(); in.destination = "foo"; in.message = "it goes to stable branch"; gApi.projects() .name(project.get()) .branch(in.destination) .create(new BranchInput()); ChangeApi orig = gApi.changes() .id("p~master~" + r.getChangeId()); assertThat((Iterable<?>)orig.get().messages).hasSize(1); ChangeApi cherry = orig.revision(r.getCommit().name()) .cherryPick(in); assertThat((Iterable<?>)orig.get().messages).hasSize(2); String cherryPickedRevision = cherry.get().currentRevision; String expectedMessage = String.format( "Patch Set 1: Cherry Picked\n\n" + "This patchset was cherry picked to branch %s as commit %s", in.destination, cherryPickedRevision); Iterator<ChangeMessageInfo> origIt = orig.get().messages.iterator(); origIt.next(); assertThat(origIt.next().message).isEqualTo(expectedMessage); assertThat(cherry.get().subject).contains(in.message); assertThat(cherry.get().topic).isEqualTo("someTopic"); cherry.current().review(ReviewInput.approve()); cherry.current().submit(); }
Source:
public void checkStoreSchema(ResourceSchema.ResourceFieldSchema schema) throws IOException { switch (schema.getType()) { case DataType.CHARARRAY: case DataType.INTEGER: case DataType.LONG: case DataType.FLOAT: case DataType.DOUBLE: return; } throw new IOException("Pig type '" + DataType.findTypeName(schema.getType()) + "' unsupported"); }

Target:
public void checkStoreSchema(ResourceSchema.ResourceFieldSchema schema) throws IOException { switch (schema.getType()) { case DataType.CHARARRAY: case DataType.INTEGER: case DataType.LONG: case DataType.FLOAT: case DataType.DOUBLE: case DataType.BOOLEAN: return; } throw new IOException("Pig type '" + DataType.findTypeName(schema.getType()) + "' unsupported"); }
Source:
public Map<String, String> devfileFileLocations() { return singletonMap(null, devfileFileLocation); }

Target:
public List<DevfileLocation> devfileFileLocations() { return singletonList( new DevfileLocation() { @Override public Optional<String> filename() { return Optional.empty(); } @Override public String location() { return devfileFileLocation; } }); }
Source:
public Component getFilter(final String componentId, FilterForm<?> form) { final IModel<OProperty> propertyModel = getCriteryModel(); UIVisualizersRegistry registry = OrienteerWebApplication.lookupApplication().getUIVisualizersRegistry(); IVisualizer visualizer = registry.getComponentFactory(propertyModel.getObject().getType(), "default"); IFilterStateLocator<IODataFilter<ODocument, String>> stateLocator = (IFilterStateLocator<IODataFilter<ODocument, String>>) form.getStateLocator(); IODataFilter<ODocument, String> filterState = stateLocator.getFilterState(); IModel<?> valueModel = filterState.getFilteredValueByProperty(propertyModel.getObject().getName()); return visualizer.createComponentForFiltering(componentId, propertyModel, valueModel); }

Target:
public Component getFilter(final String componentId, FilterForm<?> form) { IModel<OProperty> propertyModel = getCriteryModel(); OProperty property = propertyModel.getObject(); Component component = null; if (property != null) { IFilterStateLocator<IODataFilter<ODocument, String>> stateLocator = (IFilterStateLocator<IODataFilter<ODocument, String>>) form.getStateLocator(); IODataFilter<ODocument, String> filterState = stateLocator.getFilterState(); IModel<?> valueModel = filterState.getFilteredValueByProperty(propertyModel.getObject().getName()); component = getComponentForFiltering(componentId, propertyModel, valueModel); } return component; }
Source:
public void executeCommand(Command command, ExecutionHandlerContext context) { byte[] channelName = command.getProcessedCommand().get(1); byte[] message = command.getProcessedCommand().get(2); long publishCount = context.getPubSub().publish(new String(channelName), new String(message)); writeResponse(command, context, publishCount); }

Target:
public void executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> args = command.getProcessedCommand(); if (args.size() != 3) { command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.PUBLISH)); return; } String channelName = new String(args.get(1)); String message = new String(args.get(2)); long publishCount = context.getPubSub().publish(channelName, message); writeResponse(command, context, publishCount); }
Source:
public boolean deployContainer(String deployConf) { String deploymentURI = String.format( "%s/api/v1/namespaces/default/pods", this.kubernetesURI); HttpURLConnection conn = NetworkUtils.getHttpConnection(deploymentURI); if (conn == null) { LOG.log(Level.SEVERE, "Failed to find k8s deployment API"); return false; } try { if (!NetworkUtils.sendHttpPostRequest(conn, NetworkUtils.JSON_TYPE, deployConf.getBytes())) { LOG.log(Level.SEVERE, "Failed to send post to k8s deployment api"); return false; } boolean success = NetworkUtils.checkHttpResponseCode(conn, HttpURLConnection.HTTP_CREATED); if (success) { LOG.log(Level.INFO, "Topology Deployment submitted to k8s deployment API successfully"); } else { LOG.log(Level.SEVERE, "Failed to submit Deployment to k8s"); byte[] bytes = NetworkUtils.readHttpResponse(conn); LOG.log(Level.INFO, Arrays.toString(bytes)); return false; } } finally { conn.disconnect(); } return true; }

Target:
protected void deployContainer(String deployConf) throws IOException { HttpJsonClient jsonAPIClient = new HttpJsonClient(this.baseUriPath); try { jsonAPIClient.post(deployConf, HttpURLConnection.HTTP_CREATED); } catch (IOException ioe) { throw ioe; } }
Source:
static List<FolderSelectedStateCommand> splitCommand(FolderSelectedStateCommand command, int lengthLimit) { List<FolderSelectedStateCommand> commands = new ArrayList<>(); if (command.getIdSet() != null || command.getIdGroups() != null) { command = optimizeGroupings(command); Set<Long> idSet = command.getIdSet(); List<ContiguousIdGroup> idGroups = command.getIdGroups(); while ((idSet != null && !idSet.isEmpty()) || (idGroups != null && !idGroups.isEmpty())) { Builder builder = command.newBuilder() .idSet(null) .idRanges(null); int length = builder.build().createCommandString().length(); while (length < lengthLimit) { if (idSet != null && !idSet.isEmpty()) { Long first = idSet.iterator().next(); length += (String.valueOf(first).length() + 1); if (length < lengthLimit) { builder.addId(first); idSet.remove(first); } else { break; } } else if (idGroups != null && !idGroups.isEmpty()) { ContiguousIdGroup first = command.idGroups.iterator().next(); length += (first.toString().length() + 1); if (length < lengthLimit) { builder.addIdGroup(first.getStart(), first.getEnd()); idGroups.remove(first); } else { break; } } else { break; } } commands.add(builder.build()); } } else { throw new IllegalStateException("The constructed command is too long but does not contain ids"); } return commands; }

Target:
static List<String> splitCommand(FolderSelectedStateCommand command, int lengthLimit) { if (command.getIdSet().isEmpty() && command.getIdGroups().isEmpty()) { throw new IllegalStateException("The constructed command is too long but does not contain ids"); } List<String> commands = new ArrayList<>(); Set<Long> idSet = new TreeSet<>(command.getIdSet()); List<ContiguousIdGroup> idGroups = new ArrayList<>(command.getIdGroups()); while (!idSet.isEmpty() || !idGroups.isEmpty()) { command.clearIds(); int length = command.createCommandString().length(); while (length < lengthLimit) { if (!idSet.isEmpty()) { Long first = idSet.iterator().next(); length += (String.valueOf(first).length() + 1); if (length < lengthLimit) { command.addId(first); idSet.remove(first); } else { break; } } else if (!idGroups.isEmpty()) { ContiguousIdGroup first = idGroups.iterator().next(); length += (first.toString().length() + 1); if (length < lengthLimit) { command.addIdGroup(first.getStart(), first.getEnd()); idGroups.remove(first); } else { break; } } else { break; } } commands.add(command.createCommandString()); } return commands; }
Source:
protected void configure() { optionallyMapResourceParameterAsVolume(MY_CNF_CONFIG_OVERRIDE_PARAM_NAME, "/etc/mysql/conf.d", "mysql-default-conf"); addExposedPort(MYSQL_PORT); addEnv("MYSQL_DATABASE", databaseName); addEnv("MYSQL_USER", username); if(password != null && !password.isEmpty()){ addEnv("MYSQL_PASSWORD", password); addEnv("MYSQL_ROOT_PASSWORD", password); } else { if("root".equalsIgnoreCase(username)){ addEnv("MYSQL_ALLOW_EMPTY_PASSWORD", "yes"); } else { throw new RuntimeException("Empty password can be used only with the root user"); } } setStartupAttempts(3); }

Target:
protected void configure() { optionallyMapResourceParameterAsVolume(MY_CNF_CONFIG_OVERRIDE_PARAM_NAME, "/etc/mysql/conf.d", "mysql-default-conf"); addExposedPort(MYSQL_PORT); addEnv("MYSQL_DATABASE", databaseName); addEnv("MYSQL_USER", username); if (password != null && !password.isEmpty()) { addEnv("MYSQL_PASSWORD", password); addEnv("MYSQL_ROOT_PASSWORD", password); } else if (MYSQL_ROOT_USER.equalsIgnoreCase(username)) { addEnv("MYSQL_ALLOW_EMPTY_PASSWORD", "yes"); } else { throw new ContainerLaunchException("Empty password can be used only with the root user"); } setStartupAttempts(3); }
Source:
private void saveWorkspace() { final Catalog catalog = getCatalog(); NamespaceInfo namespaceInfo = (NamespaceInfo) nsModel.getObject(); WorkspaceInfo workspaceInfo = (WorkspaceInfo) wsModel.getObject(); namespaceInfo.setIsolated(workspaceInfo.isIsolated()); namespaceInfo.setPrefix(workspaceInfo.getName()); catalog.validate(workspaceInfo, false).throwIfInvalid(); catalog.validate(namespaceInfo, false).throwIfInvalid(); catalog.save(workspaceInfo); catalog.save(namespaceInfo); if (basicInfoPanel.defaultWs) { catalog.setDefaultWorkspace(workspaceInfo); } GeoServer geoServer = getGeoServer(); Settings set = settingsPanel.set; if (set.enabled) { if (set.model instanceof NewSettingsModel) { geoServer.add(set.model.getObject()); } else { geoServer.save(set.model.getObject()); } } else { if (set.model instanceof ExistingSettingsModel) { geoServer.remove(set.model.getObject()); } } for (Service s : servicesPanel.services) { if (s.enabled) { if (s.model instanceof ExistingServiceModel) { continue; } geoServer.add(s.model.getObject()); } else { if (s.model instanceof ExistingServiceModel) { geoServer.remove(s.model.getObject()); } } } try { accessdataPanel.save(); } catch (Exception e) { LOGGER.log( Level.INFO, "Error saving access rules associated to workspace " + workspaceInfo.getName(), e); error(e.getMessage() == null ? e.toString() : e.getMessage()); } doReturn(WorkspacePage.class); }

Target:
private void saveWorkspace() { final Catalog catalog = getCatalog(); NamespaceInfo namespaceInfo = (NamespaceInfo) nsModel.getObject(); WorkspaceInfo workspaceInfo = (WorkspaceInfo) wsModel.getObject(); namespaceInfo.setIsolated(workspaceInfo.isIsolated()); namespaceInfo.setPrefix(workspaceInfo.getName()); catalog.validate(workspaceInfo, false).throwIfInvalid(); catalog.validate(namespaceInfo, false).throwIfInvalid(); catalog.save(workspaceInfo); catalog.save(namespaceInfo); if (basicInfoPanel.defaultWs) { catalog.setDefaultWorkspace(workspaceInfo); } GeoServer geoServer = getGeoServer(); Settings set = settingsPanel.set; if (set.enabled) { if (set.model instanceof NewSettingsModel) { geoServer.add(set.model.getObject()); } else { geoServer.save(set.model.getObject()); } } else { if (set.model instanceof ExistingSettingsModel) { geoServer.remove(set.model.getObject()); } } for (Service s : servicesPanel.services) { if (s.enabled) { if (s.model instanceof ExistingServiceModel) { continue; } geoServer.add(s.model.getObject()); } else { if (s.model instanceof ExistingServiceModel) { geoServer.remove(s.model.getObject()); } } } try { if (accessDataPanel != null) accessDataPanel.save(); doReturn(WorkspacePage.class); } catch (Exception e) { LOGGER.log( Level.INFO, "Error saving access rules associated to workspace " + workspaceInfo.getName(), e); error(e.getMessage() == null ? e.toString() : e.getMessage()); } }
Source:
public HDFSFileOutputOperator() { setExpireStreamAfterAccessMillis(24 * 60 * 60 * 1000L); setMaxOpenFiles(1000); setRotationWindows(2 * 60 * 60 * 20); }

Target:
public HDFSFileOutputOperator() { setExpireStreamAfterAccessMillis(STREAM_EXPIRY_ACCESS_MILL); setMaxOpenFiles(1000); setRotationWindows(ROTATION_WINDOWS); }
Source:
public void updateShouldUpdateEmailMeStateToFalse() throws Exception { User user = new User("user-1"); user.enable(); user.setEmailMe(true); addUser(user); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); userService.save(user, TriState.UNSET, TriState.FALSE, null, null, result); assertThat(result.isSuccessful(), is(true)); assertThat(user.isEmailMe(), is(false)); ; }

Target:
public void updateShouldUpdateEmailMeStateToFalse() throws Exception { User user = new User("user-1"); user.enable(); user.setEmailMe(true); addUser(user); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); userService.save(user, TriState.UNSET, TriState.FALSE, null, null, result); assertThat(result.isSuccessful(), is(true)); assertThat(user.isEmailMe(), is(false)); }
Source:
public static void setUp() { MetricsTestUtility.initServiceProvider(); testUtil = new MetricsTestUtility( SERVICE_PROVIDER.getInstance(MetricsManager.class).getRegistry()); metrics = SERVICE_PROVIDER.getInstance(CommonMetrics.class); }

Target:
public void setUp() { final MetricRegistry metricRegistry = new MetricRegistry(); this.testUtil = new MetricsTestUtility(metricRegistry); this.metrics = new CommonMetrics(metricRegistry); }
Source:
public BasicIssue createIssue(String projectKey, String description, String assignee, Iterable<String> components, String summary, @Nonnull Long issueTypeId, @Nullable Long priorityId) { IssueInputBuilder builder = new IssueInputBuilder(); builder.setProjectKey(projectKey) .setDescription(description) .setIssueTypeId(issueTypeId) .setSummary(summary); if (priorityId != null) { builder.setPriorityId(priorityId); } if (!assignee.equals("")) { builder.setFieldInput(new FieldInput(IssueFieldId.ASSIGNEE_FIELD, ComplexIssueInputFieldValue.with("id", assignee))); } if (Iterators.size(components.iterator()) > 0){ builder.setComponentsNames(components); } final IssueInput issueInput = builder.build(); try { return jiraRestClient.getIssueClient().createIssue(issueInput).get(timeout, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.log(WARNING, "JIRA REST createIssue error: " + e.getMessage(), e); return null; } }

Target:
public BasicIssue createIssue(String projectKey, String description, String assignee, Iterable<String> components, String summary, @Nonnull Long issueTypeId, @Nullable Long priorityId) { IssueInputBuilder builder = new IssueInputBuilder(); builder.setProjectKey(projectKey) .setDescription(description) .setIssueTypeId(issueTypeId) .setSummary(summary); if (priorityId != null) { builder.setPriorityId(priorityId); } if (StringUtils.isNotBlank(assignee)) { builder.setFieldInput(new FieldInput(IssueFieldId.ASSIGNEE_FIELD, ComplexIssueInputFieldValue.with("accountId", assignee))); } if (Iterators.size(components.iterator()) > 0){ builder.setComponentsNames(components); } final IssueInput issueInput = builder.build(); try { return jiraRestClient.getIssueClient().createIssue(issueInput).get(timeout, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.log(WARNING, "JIRA REST createIssue error: " + e.getMessage(), e); return null; } }
Source:
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable { if (!ctx.isInTxScope()) throw new IllegalStateException("Locks should only be acquired within the scope of a transaction!"); if (command.isUnlock()) { if (ctx.isOriginLocal()) { throw new AssertionError( "There's no advancedCache.unlock so this must have originated remotely."); } return false; } if (hasSkipLocking(command) || areAllKeysAlreadyLocked(ctx, command.getKeys())) { if (trace) { log.tracef("Skip locking or keys already locked. Skipping command %s", command); } return false; } else if (isLocalOnly(command)) { lockOrRegisterBackupLock(ctx, command.getKeys(), getLockTimeoutMillis(command)); ctx.addAffectedKey(command.getKeys()); return invokeNext(ctx, command); } else { return ctx.isOriginLocal() ? handleLocalLockCommand(ctx, command) : handleRemoteLockCommand(ctx, command); } }

Target:
public Object visitLockControlCommand(TxInvocationContext ctx, LockControlCommand command) throws Throwable { assert ctx.isInTxScope() : "Locks should only be acquired within the scope of a transaction!"; if (command.isUnlock()) { assert !ctx.isOriginLocal() : "There's no advancedCache.unlock so this must have originated remotely."; return false; } if (hasSkipLocking(command)) { throw log.lockCommandWithSkipLocking(); } if (hasSkipLocking(command) || areAllKeysAlreadyLocked(ctx, command.getKeys())) { if (trace) { log.tracef("Skip locking or keys already locked. Skipping command %s", command); } return false; } else if (isLocalOnly(command)) { lockOrRegisterBackupLock(ctx, command.getKeys(), getLockTimeoutMillis(command)); ctx.addAffectedKey(command.getKeys()); return invokeNext(ctx, command); } else { return ctx.isOriginLocal() ? handleLocalLockCommand(ctx, command) : handleRemoteLockCommand(ctx, command); } }
Source:
private boolean isStaged(Repository repository, IPath location, boolean checkIndex) { if (location == null || location.toFile().isDirectory()) { return false; } String resRelPath = null; RepositoryMapping mapping = RepositoryMapping.getMapping(location); if (mapping != null) { resRelPath = mapping.getRepoRelativePath(location); } else { IPath workDir = new Path( repository.getWorkTree().getAbsolutePath()); resRelPath = location.makeRelativeTo(workDir).toString(); } if (resRelPath == null || resRelPath.length() == 0) { return false; } if (!checkIndex) { return true; } try { FileTreeIterator fileTreeIterator = new FileTreeIterator(repository); IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, fileTreeIterator); indexDiff.setFilter(PathFilterGroup.createFromStrings(Collections.singletonList(resRelPath))); indexDiff.diff(); return indexDiff.getAdded().contains(resRelPath) || indexDiff.getChanged().contains(resRelPath) || indexDiff.getRemoved().contains(resRelPath); } catch (IOException e) { Activator.error(NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, location.toString()), e); return false; } }

Target:
private boolean isStaged(Repository repository, IPath location, boolean checkIndex) { if (location == null || location.toFile().isDirectory() || repository.isBare()) { return false; } File workTree = repository.getWorkTree(); if (workTree == null) { return false; } IPath workDir = new Path(workTree.getAbsolutePath()); String resRelPath = location.makeRelativeTo(workDir).toString(); if (resRelPath.length() == 0 || resRelPath.equals(location)) { return false; } if (!checkIndex) { return true; } try { FileTreeIterator fileTreeIterator = new FileTreeIterator(repository); IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, fileTreeIterator); indexDiff.setFilter(PathFilterGroup.createFromStrings(Collections.singletonList(resRelPath))); indexDiff.diff(); return indexDiff.getAdded().contains(resRelPath) || indexDiff.getChanged().contains(resRelPath) || indexDiff.getRemoved().contains(resRelPath); } catch (IOException e) { Activator.error(NLS.bind(UIText.GitHistoryPage_errorLookingUpPath, location.toString()), e); return false; } }