auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean checkPermission(final Subject subject, final Permission permission, String errorMessage) throws PermissionException { try { Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() { public Object run() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(permission); } return null; } }, null); } catch (SecurityException ex) { throw new PermissionException(errorMessage); } return true; }

Target:
private boolean checkPermission(final Subject subject, final Permission permission, String errorMessage) throws PermissionException { try { Subject.doAsPrivileged(subject, (PrivilegedAction<Object>) () -> { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(permission); } return null; }, null); } catch (SecurityException ex) { throw new PermissionException(errorMessage); } return true; }
Source:
public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); relationshipDelete( relId ); count.increment(); } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); }

Target:
public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); if ( relationshipDelete( relId ) ) { count.increment(); } } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); }
Source:
public void nodeChildrenChanged(final String path) { waitUntilStarted(); if (path.equals(aclZNode)) { if (childrenChangedFuture != null && !childrenChangedFuture.isDone()) { boolean cancelled = childrenChangedFuture.cancel(true); if (!cancelled) { if (!childrenChangedFuture.isDone()) { LOG.warn("Could not cancel processing node children changed event, " + "please file a JIRA and attach logs if possible."); } } } childrenChangedFuture = asyncProcessNodeUpdate(() -> { try { final List<ZKUtil.NodeAndData> nodeList = ZKUtil.getChildDataAndWatchForNewChildren(watcher, aclZNode); refreshNodes(nodeList); } catch (KeeperException ke) { LOG.error("Error reading data from zookeeper for path " + path, ke); watcher.abort("ZooKeeper error get node children for path " + path, ke); } }); } }

Target:
public void nodeChildrenChanged(final String path) { waitUntilStarted(); if (path.equals(aclZNode)) { if (childrenChangedFuture != null && !childrenChangedFuture.isDone()) { boolean cancelled = childrenChangedFuture.cancel(true); if (!cancelled) { if (!childrenChangedFuture.isDone()) { LOG.warn("Could not cancel processing node children changed event, " + "please file a JIRA and attach logs if possible."); } } } childrenChangedFuture = asyncProcessNodeUpdate(() -> { try { final List<ZKUtil.NodeAndData> nodeList = ZKUtil.getChildDataAndWatchForNewChildren(watcher, aclZNode); refreshNodes(nodeList); } catch (KeeperException ke) { String msg = "ZooKeeper error while reading node children data for path " + path; LOG.error(msg, ke); watcher.abort(msg, ke); } }); } }
Source:
public boolean conforms() { return ((in().numDimensions() == 2) || ((in().numDimensions() == 3) && (in().dimension(2) == 3))); }

Target:
public boolean conforms() { return ((in().numDimensions() == 2) || (in().numDimensions() == 3)); }
Source:
public void onReceive(final Object message) throws Exception { if ("tick".equals(message)) { LOGGER.trace() .setMessage("Searching for added/updated hosts") .addData("actor", self()) .log(); LOGGER.debug() .setMessage("Calling Foreman API to get hosts") .log(); Patterns.pipe(_client.getHostPage(1).wrapped(), context().dispatcher()).to(self(), self()); } else if (message instanceof ForemanClient.HostPageResponse) { final ForemanClient.HostPageResponse response = (ForemanClient.HostPageResponse) message; final List<ForemanClient.ForemanHost> results = response.getResults(); for (ForemanClient.ForemanHost host : results) { final Host dh = new DefaultHost.Builder() .setHostname(host.getName()) .setMetricsSoftwareState(MetricsSoftwareState.UNKNOWN) .build(); _hostRepository.addOrUpdateHost(dh); } if (response.getTotal() > response.getPage() * response.getPerPage()) { Patterns.pipe(_client.getHostPage(response.getPage() + 1, response.getPerPage()).wrapped(), context().dispatcher()) .to(self(), self()); } } else { LOGGER.warn() .setMessage("unhandled message") .addData("akkaMessage", message) .log(); unhandled(message); } }

Target:
public void onReceive(final Object message) throws Exception { if (TICK.equals(message)) { LOGGER.trace() .setMessage("Searching for added/updated hosts") .addData("actor", self()) .log(); Patterns.pipe(_client.getHostPage(1).wrapped(), context().dispatcher()).to(self(), self()); } else if (message instanceof ForemanClient.HostPageResponse) { final ForemanClient.HostPageResponse response = (ForemanClient.HostPageResponse) message; final List<ForemanClient.ForemanHost> results = response.getResults(); for (final ForemanClient.ForemanHost host : results) { final Host dh = new DefaultHost.Builder() .setHostname(host.getName()) .setMetricsSoftwareState(MetricsSoftwareState.UNKNOWN) .build(); _hostRepository.addOrUpdateHost(dh); } if (response.getTotal() > response.getPage() * response.getPerPage()) { Patterns.pipe(_client.getHostPage(response.getPage() + 1, response.getPerPage()).wrapped(), context().dispatcher()) .to(self(), self()); } } else { LOGGER.warn() .setMessage("unhandled message") .addData("akkaMessage", message) .log(); unhandled(message); } }
Source:
public void testIsValid() { ZoneOffset offset = ZoneOffset.ofHours( 8 ); OffsetTime future = OffsetTime.now( offset ).plusHours( 1 ); OffsetTime past = OffsetTime.now( offset ).minusHours( 1 ); assertTrue( constraint.isValid( null, null ) ); assertTrue( constraint.isValid( past, null ) ); assertFalse( constraint.isValid( future, null ) ); }

Target:
public void testIsValid() { assertTrue( constraint.isValid( null, null ), "null fails validation." ); for ( int i = -18; i <= 18; i++ ) { ZoneOffset offset = ZoneOffset.ofHours( i ); OffsetTime now = OffsetTime.now( offset ); int currentHour = now.getHour(); int currentMinute = now.getMinute(); OffsetTime future = now.plusMinutes( 1 ); OffsetTime past = now.minusMinutes( 1 ); if (!(currentHour == 0 && currentMinute == 0)) { assertTrue( constraint.isValid( past, null ), "Past OffsetTime '" + past + "' fails validation."); } if (!(currentHour == 23 && currentMinute == 59)) { assertFalse( constraint.isValid( future, null ), "Future OffsetTime '" + future + "' validated as past."); } } }
Source:
public PolicyEventMapper() { this(null); nextEventIdCtxResolver = new EventInternalContextResolver<>(POLICY_NEXT_EVENT_CTX_IDS, () -> Collections.emptySet()); }

Target:
public PolicyEventMapper() { this(null); nextEventIdCtxResolver = new EventInternalContextResolver<>(POLICY_NEXT_EVENT_CTX_IDS, () -> emptySet()); }
Source:
private void undeployAddressesAndQueueNotInConfiguration(Configuration configuration) throws Exception { Set<String> addressesInConfig = configuration.getAddressConfigurations().stream() .map(CoreAddressConfiguration::getName) .collect(Collectors.toSet()); Set<String> queuesInConfig = configuration.getAddressConfigurations().stream() .map(CoreAddressConfiguration::getQueueConfigurations) .flatMap(List::stream).map(CoreQueueConfiguration::getName) .collect(Collectors.toSet()); for (SimpleString addressName : listAddressNames()) { AddressSettings addressSettings = getAddressSettingsRepository().getMatch(addressName.toString()); if (!addressesInConfig.contains(addressName.toString()) && addressSettings.getConfigDeleteAddresses() == DeletionPolicy.FORCE) { for (Queue queue : listQueues(addressName)) { ActiveMQServerLogger.LOGGER.undeployQueue(queue.getName()); queue.deleteQueue(true); } ActiveMQServerLogger.LOGGER.undeployAddress(addressName); try { removeAddressInfo(addressName, null); } catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToUndeployAddress(addressName, e.getMessage()); } } else if (addressSettings.getConfigDeleteQueues() == DeletionPolicy.FORCE) { for (Queue queue : listConfiguredQueues(addressName)) { if (!queuesInConfig.contains(queue.getName().toString())) { ActiveMQServerLogger.LOGGER.undeployQueue(queue.getName()); try { queue.deleteQueue(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToUndeployQueue(addressName, e.getMessage()); } } } } } }

Target:
private void undeployAddressesAndQueueNotInConfiguration(Configuration configuration) throws Exception { Set<String> addressesInConfig = configuration.getAddressConfigurations().stream() .map(CoreAddressConfiguration::getName) .collect(Collectors.toSet()); Set<String> queuesInConfig = configuration.getAddressConfigurations().stream() .map(CoreAddressConfiguration::getQueueConfigurations) .flatMap(List::stream).map(CoreQueueConfiguration::getName) .collect(Collectors.toSet()); for (SimpleString addressName : listAddressNames()) { AddressSettings addressSettings = getAddressSettingsRepository().getMatch(addressName.toString()); if (!addressesInConfig.contains(addressName.toString()) && addressSettings.getConfigDeleteAddresses() == DeletionPolicy.FORCE) { for (Queue queue : listQueues(addressName)) { ActiveMQServerLogger.LOGGER.undeployQueue(queue.getName()); try { queue.deleteQueue(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToUndeployQueue(addressName, e.getMessage()); } } ActiveMQServerLogger.LOGGER.undeployAddress(addressName); try { removeAddressInfo(addressName, null); } catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToUndeployAddress(addressName, e.getMessage()); } } else if (addressSettings.getConfigDeleteQueues() == DeletionPolicy.FORCE) { for (Queue queue : listConfiguredQueues(addressName)) { if (!queuesInConfig.contains(queue.getName().toString())) { ActiveMQServerLogger.LOGGER.undeployQueue(queue.getName()); try { queue.deleteQueue(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.unableToUndeployQueue(addressName, e.getMessage()); } } } } } }
Source:
public long countAllCheckTestEntries(final Integer studyId, final String programUuid, final Boolean checkOnly) { final List<Enumeration> entryTypes = this.entryTypeService.getEntryTypes(programUuid); if(checkOnly) { return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, Collections.singletonList(String.valueOf(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()))); } else { final List<String> checkEntryTypeIds = entryTypes.stream() .filter(enttryType -> enttryType.getId() != SystemDefinedEntryType.TEST_ENTRY.getEntryTypeCategoricalId()) .map(entryType -> String.valueOf(entryType.getId())).collect(Collectors.toList()); return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, checkEntryTypeIds); } }

Target:
public long countAllCheckTestEntries(final Integer studyId, final String programUuid, final Boolean checkOnly) { final List<Enumeration> entryTypes = this.entryTypeService.getEntryTypes(programUuid); if(checkOnly) { return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, Collections.singletonList(String.valueOf(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()))); } else { final List<String> checkEntryTypeIds = entryTypes.stream() .filter(entryType -> entryType.getId() != SystemDefinedEntryType.TEST_ENTRY.getEntryTypeCategoricalId()) .map(entryType -> String.valueOf(entryType.getId())).collect(Collectors.toList()); return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, checkEntryTypeIds); } }
Source:
private static DiskImage createDiskImage() { DiskImage disk = new DiskImage(); disk.setId(diskId); disk.setStorageIds(new ArrayList<Guid>(Arrays.asList(storageId))); return disk; }

Target:
private DiskImage createDiskImage() { DiskImage disk = new DiskImage(); disk.setId(diskId); Collections.singletonList(storageId); disk.setStorageIds(new ArrayList<Guid>(Collections.singletonList(storageId))); return disk; }
Source:
public Tuple<Optional<String>, Lock> resolveEvalWithLock(final int blockId) { checkInitialization(); waitBlockMigrationTobeFinished(blockId); final Lock readLock = routerLock.readLock(); readLock.lock(); final int memoryStoreId = blockLocations.get(blockId); if (memoryStoreId == localStoreId) { return new Tuple<>(Optional.empty(), readLock); } else { return new Tuple<>(Optional.of(getEvalId(memoryStoreId)), readLock); } }

Target:
public Tuple<Optional<String>, Lock> resolveEvalWithLock(final int blockId) { checkInitialization(); waitBlockMigrationToEnd(blockId); final Lock readLock = routerLock.readLock(); readLock.lock(); final int memoryStoreId = blockLocations.get(blockId); if (memoryStoreId == localStoreId) { return new Tuple<>(Optional.empty(), readLock); } else { return new Tuple<>(Optional.of(getEvalId(memoryStoreId)), readLock); } }
Source:
private boolean anyFileVideoPreviewing() { final HookActivity activity = (HookActivity) mContext; Fragment secondFragment = activity.getSupportFragmentManager().findFragmentByTag( TAG_SECOND_FRAGMENT); boolean videoPreviewing = false; if (secondFragment instanceof PreviewVideoFragment) { for (int i=0; !videoPreviewing && i < mFiles.size(); i++) { videoPreviewing = ((PreviewVideoFragment) secondFragment) .isFileToPreview(mFiles.get(i)); } }; return videoPreviewing; }

Target:
private boolean anyFileVideoPreviewing() { final FragmentActivity activity = (FragmentActivity) mContext; Fragment secondFragment = activity.getSupportFragmentManager().findFragmentByTag( TAG_SECOND_FRAGMENT); boolean videoPreviewing = false; if (secondFragment instanceof PreviewVideoFragment) { for (int i=0; !videoPreviewing && i < mFiles.size(); i++) { videoPreviewing = ((PreviewVideoFragment) secondFragment). getFile().equals(mFiles.get(i)); } }; return videoPreviewing; }
Source:
public ObservationDto() { super(); }

Target:
public ObservationDto() { }
Source:
public void testGetBorderPlanetsFactionBorders() { DateTime when = new DateTime(); List<Planet> planets = new ArrayList<>(); for (int x = -3; x <= 3; x += 2) { for (int y = -2; y <= 2; y += 2) { planets.add(createPlanet(x, y, factionThem)); } } planets.add(createPlanet(0, 0, factionUs)); FactionBorders us = new FactionBorders(factionUs, when, planets); FactionBorders them = new FactionBorders(factionThem, when, planets); List<Planet> border = us.getBorderPlanets(them, 1.1); assertEquals(border.size(), 2); for (Planet p : border) { assertEquals(Math.abs(p.getX()), 1, 0.001); assertEquals(p.getY(), 0, 0.001); } }

Target:
public void testGetBorderPlanetsFactionBorders() { DateTime when = new DateTime(); List<Planet> planets = new ArrayList<>(); for (int x = -3; x <= 3; x += 2) { for (int y = -2; y <= 2; y += 2) { planets.add(createPlanet(x, y, factionThem)); } } planets.add(createPlanet(0, 0, factionUs)); FactionBorders us = new FactionBorders(factionUs, when, planets); FactionBorders them = new FactionBorders(factionThem, when, planets); List<Planet> border = us.getBorderPlanets(them, 1.1); assertEquals(border.size(), 2); for (Planet p : border) { assertEquals(Math.abs(p.getX()), 1, RegionPerimeter.EPSILON); assertEquals(p.getY(), 0, RegionPerimeter.EPSILON); } }
Source:
public String readUTF() { int utflen = readInt(); byte[] bytearr = bytes; char[] chararr = new char[utflen]; utflen = pos + utflen; int c, char2, char3; int count = pos; int chararr_count=0; while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) break; count++; chararr[chararr_count++]=(char)c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: count++; chararr[chararr_count++]=(char)c; break; case 12: case 13: count += 2; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-1]; if ((char2 & 0xC0) != 0x80) throw new RuntimeException( "malformed input around byte " + count); chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: count += 3; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-2]; char3 = (int) bytearr[count-1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) throw new RuntimeException( "malformed input around byte " + (count-1)); chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; default: throw new RuntimeException( "malformed input around byte " + count); } } pos = count; return new String(chararr, 0, chararr_count); }

Target:
public String readUTF() { int utflen = readInt(); byte[] bytearr = bytes; char[] chararr = new char[utflen]; utflen = pos + utflen; int c, char2, char3; int count = pos; int chararr_count=0; while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) break; count++; chararr[chararr_count++]=(char)c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: count++; chararr[chararr_count++]=(char)c; break; case 12: case 13: count += 2; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-1]; if ((char2 & 0xC0) != 0x80) throw new RuntimeException( "malformed input around byte " + count); chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: count += 3; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-2]; char3 = (int) bytearr[count-1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) throw new RuntimeException( "malformed input around byte " + (count-1)); chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | (char3 & 0x3F)); break; default: throw new RuntimeException( "malformed input around byte " + count); } } pos = count; return new String(chararr, 0, chararr_count); }
Source:
public synchronized BinaryDequeReader openForRead(String cursorId) throws IOException { if (m_closed) { throw new IOException("Closed"); } if (!m_readCursors.containsKey(cursorId)) { ReadCursor cursor = new ReadCursor(cursorId); m_readCursors.put(cursorId, cursor); persistCursor(cursorId); } return m_readCursors.get(cursorId); }

Target:
public synchronized BinaryDequeReader openForRead(String cursorId) throws IOException { if (m_closed) { throw new IOException("Closed"); } ReadCursor reader = m_readCursors.get(cursorId); if (reader == null) { reader = new ReadCursor(cursorId, m_numDeleted); m_readCursors.put(cursorId, reader); persistCursor(cursorId); } return reader; }
Source:
public static ObjectId read(InputStream in) throws IOException { byte marker = (byte) in.read(); switch (marker) { case NULL_MARKER: return null; case NON_NULL_MARKER: final byte[] b = new byte[OBJECT_ID_LENGTH]; IO.readFully(in, b, 0, OBJECT_ID_LENGTH); return ObjectId.fromRaw(b); default: throw new IOException("Invalid flag before ObjectId: " + marker); } }

Target:
public static ObjectId read(InputStream in) throws IOException { byte marker = (byte) in.read(); switch (marker) { case NULL_MARKER: return null; case NON_NULL_MARKER: return readWithoutMarker(in); default: throw new IOException("Invalid flag before ObjectId: " + marker); } }
Source:
public void nonBinaryNoSourceImages() throws Exception { CollectionObject collObject = repoObjectFactory.createCollectionObject(null); final Map<String, Object> headers = createEvent(false, collObject.getPid(), Cdr.Collection.getURI(), Container.getURI()); template.sendBodyAndHeaders("", headers); NotifyBuilder notify1 = new NotifyBuilder(cdrEnhancements) .whenCompleted(1) .create(); boolean result1 = notify1.matches(5l, TimeUnit.SECONDS); assertTrue("Enhancement route not satisfied", result1); verify(addSmallThumbnailProcessor, never()).process(any(Exchange.class)); verify(addLargeThumbnailProcessor, never()).process(any(Exchange.class)); }

Target:
public void nonBinaryNoSourceImages() throws Exception { CollectionObject collObject = repoObjectFactory.createCollectionObject(null); final Map<String, Object> headers = createEvent(collObject.getPid(), Cdr.Collection.getURI(), Container.getURI()); template.sendBodyAndHeaders("", headers); NotifyBuilder notify1 = new NotifyBuilder(cdrEnhancements) .whenCompleted(1) .create(); boolean result1 = notify1.matches(5l, TimeUnit.SECONDS); assertTrue("Enhancement route not satisfied", result1); verify(addSmallThumbnailProcessor, never()).process(any(Exchange.class)); verify(addLargeThumbnailProcessor, never()).process(any(Exchange.class)); verify(solrIngestProcessor).process(any(Exchange.class)); }
Source:
private void addStyles() { importGlusterConfigurationEditor.addContentWidgetStyleName(style.editorContentWidget()); migrateOnErrorOption_NOEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_YESEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_HA_ONLYEditor.addContentWidgetStyleName(style.label()); optimizationNoneEditor.setContentWidgetStyleName(style.radioButtonPositioning()); optimizationForServerEditor.setContentWidgetStyleName(style.radioButtonPositioning()); optimizationForDesktopEditor.setContentWidgetStyleName(style.radioButtonPositioning()); optimizationCustomEditor.setContentWidgetStyleName(style.radioButtonPositioning()); countThreadsAsCoresEditor.setContentWidgetStyleName(style.fullWidth()); enableTrustedServiceEditor.setContentWidgetStyleName(style.fullWidth()); }

Target:
private void addStyles() { importGlusterConfigurationEditor.addContentWidgetStyleName(style.editorContentWidget()); migrateOnErrorOption_NOEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_YESEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_HA_ONLYEditor.addContentWidgetStyleName(style.label()); countThreadsAsCoresEditor.setContentWidgetStyleName(style.fullWidth()); enableTrustedServiceEditor.setContentWidgetStyleName(style.fullWidth()); }
Source:
public void testToCompletionStageTrampolining() { waitFor(2); Thread mainThread = Thread.currentThread(); Future<String> success = Future.succeededFuture("Yo"); success.toCompletionStage() .thenAccept(str -> { assertEquals("Yo", str); assertSame(mainThread, Thread.currentThread()); complete(); }); Future<String> failed = Future.failedFuture(new RuntimeException("Woops")); failed.toCompletionStage() .whenComplete((str, err) -> { assertNull(str); assertTrue(err instanceof RuntimeException); assertEquals("Woops", err.getMessage()); assertSame(mainThread, Thread.currentThread()); complete(); }); await(5, SECONDS); }

Target:
public void testToCompletionStageTrampolining() { waitFor(2); Thread mainThread = Thread.currentThread(); Future<String> success = Future.succeededFuture("Yo"); success.toCompletionStage() .thenAccept(str -> { assertEquals("Yo", str); assertSame(mainThread, Thread.currentThread()); complete(); }); Future<String> failed = Future.failedFuture(new RuntimeException("Woops")); failed.toCompletionStage() .whenComplete((str, err) -> { assertNull(str); assertTrue(err instanceof RuntimeException); assertEquals("Woops", err.getMessage()); assertSame(mainThread, Thread.currentThread()); complete(); }); await(); }
Source:
public Date getExpiresOn() { return new Date(mExpiresOn.getTime()); }

Target:
public Date getExpiresOn() { return Utility.getImmutableDateObject(mExpiresOn); }
Source:
public Map<String, String> getTemplateVars() { return templateVars; }

Target:
public ImmutableMap<String, String> getTemplateVars() { return templateVars; }
Source:
private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { } mMainAdbConnection = null; synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { while (!mDevices.isEmpty()) { Device device = mDevices.remove(0); removeDevice(device); mServer.deviceDisconnected(device); } } } } } }

Target:
private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { } mMainAdbConnection = null; synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { for (int n = mDevices.size() -1; n >= 0; n--) { Device device = mDevices.get(0); removeDevice(device); mServer.deviceDisconnected(device); } } } } } }
Source:
protected boolean parseArgs(final String[] argv) { commandLineParser = getCommandLineParser(); boolean ret = false; try { ret = commandLineParser.parseArguments(System.err, argv); } catch (CommandLineException e) { System.err.println(e.getMessage()); System.err.println(commandLineParser.usage(false,false)); ret = false; } commandLine = commandLineParser.getCommandLine(); if (!ret) { return false; } REFERENCE_SEQUENCE = referenceSequence.getReferenceFile(); final String[] customErrorMessages = customCommandLineValidation(); if (customErrorMessages != null) { for (final String msg : customErrorMessages) { System.err.println(msg); } System.err.print(commandLineParser.usage(false, false)); return false; } return true; }

Target:
protected boolean parseArgs(final String[] argv) { commandLineParser = getCommandLineParser(); boolean ret; try { ret = commandLineParser.parseArguments(System.err, argv); } catch (CommandLineException e) { System.err.println(commandLineParser.usage(false,false)); System.err.println(e.getMessage()); ret = false; } commandLine = commandLineParser.getCommandLine(); if (!ret) { return false; } REFERENCE_SEQUENCE = referenceSequence.getReferenceFile(); final String[] customErrorMessages = customCommandLineValidation(); if (customErrorMessages != null) { System.err.print(commandLineParser.usage(false, false)); for (final String msg : customErrorMessages) { System.err.println(msg); } return false; } return true; }
Source:
private void writeMetadata(File parent, String resourceFileName, Properties metadata) throws SynapseException { File metadataDir = new File(parent, METADATA_DIR_NAME); if (!metadataDir.exists() && !metadataDir.mkdirs()) { handleException("Unable to create metadata directory: " + metadataDir.getPath()); } File newMetadataFile = new File(metadataDir, resourceFileName + METADATA_FILE_SUFFIX); try (BufferedWriter metadataWriter = new BufferedWriter(new FileWriter(newMetadataFile))) { metadata.store(metadataWriter, null); if (log.isDebugEnabled()) { log.debug("Successfully written metadata to file: " + newMetadataFile.getPath()); } } catch (IOException e) { handleException("Couldn't write to metadata file: " + newMetadataFile.getPath(), e); } }

Target:
private void writeMetadata(File parent, String resourceFileName, Properties metadata) { File metadataDir = new File(parent, METADATA_DIR_NAME); if (!metadataDir.exists() && !metadataDir.mkdirs()) { handleException("Unable to create metadata directory: " + metadataDir.getPath()); } File newMetadataFile = new File(metadataDir, resourceFileName + METADATA_FILE_SUFFIX); try (BufferedWriter metadataWriter = new BufferedWriter(new FileWriter(newMetadataFile))) { metadata.store(metadataWriter, null); if (log.isDebugEnabled()) { log.debug("Successfully written metadata to file: " + newMetadataFile.getPath()); } } catch (IOException e) { handleException("Couldn't write to metadata file: " + newMetadataFile.getPath(), e); } }
Source:
public void trace(String component, String operation, Runnable runable) throws RuntimeException { try { startNewSpan(component, operation); runable.run(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { finishSpan(); } }

Target:
public void trace(String component, String operation, Runnable runable) { try { startNewSpan(component, operation); runable.run(); } finally { finishSpan(); } }
Source:
public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; for (EntityRef minion : entityManager.getEntitiesWith(BehaviorComponent.class)) { addEntity(minion, minion.getComponent(BehaviorComponent.class)); } for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } }

Target:
public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } }
Source:
public void run(DiscovererConfiguration configuration, Environment environment) { MongoClient mongoClient = new MongoClient(configuration.getDatabaseURL(), configuration.getDatabasePort()); Discoverer discoverer = new Discoverer(mongoClient, configuration.getActiveCrawlers()); environment.jersey().register(new FetchAPI(discoverer)); environment.jersey().register(new FetchAllAPI(discoverer)); environment.jersey().register(new DeleteAPI(discoverer)); environment.jersey().register(new StatisticsAPI(discoverer)); environment.jersey().register(new RefreshAPI(discoverer)); environment.jersey().register(new FetchIfAPI(discoverer)); }

Target:
public void run(DiscovererConfiguration configuration, Environment environment) { MongoClient mongoClient = new MongoClient(configuration.getDatabaseURL(), configuration.getDatabasePort()); Discoverer discoverer = new Discoverer(mongoClient, configuration.getActiveCrawlers()); environment.jersey().register(new DiscovererAPI(discoverer)); }
Source:
default V setDataSource( CallbackDataProvider.FetchCallback<T, Void> fetchCallback) { setDataSource(DataProvider.fromCallbacks(fetchCallback, query -> { throw new IllegalStateException( "Trying to use defined size with a lazy loading component" + " without either providing a count callback for the" + "component to fetch the size of the data or a data" + "provider that implements the size query. Provide the " + "callback for fetching size with%n" + "component.getLazyDataView().withDefinedSize(CallbackDataProvider.CountCallback);" + "%nor switch to undefined size with%n" + "component.getLazyDataView().withUndefinedSize();"); })); V lazyDataView = getLazyDataView(); lazyDataView.setRowCountUnknown(); return lazyDataView; }

Target:
default V setDataSource( CallbackDataProvider.FetchCallback<T, Void> fetchCallback) { setDataSource(DataProvider.fromCallbacks(fetchCallback, query -> { throw new IllegalStateException( "Trying to use exact size with a lazy loading component" + " without either providing a count callback for the" + " component to fetch the size of the data or a data" + " provider that implements the size query. Provide the " + "callback for fetching size with%n" + "component.getLazyDataView().withDefinedSize(CallbackDataProvider.CountCallback);" + "%nor switch to undefined size with%n" + "component.getLazyDataView().withUndefinedSize();"); })); V lazyDataView = getLazyDataView(); lazyDataView.setRowCountUnknown(); return lazyDataView; }
Source:
void testBuiltInListsIncludeAllBuiltInAbbreviations() { viewModel.addBuiltInList(); assertEquals(1, viewModel.journalFilesProperty().getSize()); viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0)); ObservableList<Abbreviation> expected = FXCollections.observableArrayList(repo.getBuiltin()); ObservableList<Abbreviation> actualAbbreviations = FXCollections .observableArrayList(viewModel.abbreviationsProperty().stream() .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList())); assertEquals(expected, actualAbbreviations); }

Target:
void testBuiltInListsIncludeAllBuiltInAbbreviations() { viewModel.addBuiltInList(); assertEquals(1, viewModel.journalFilesProperty().getSize()); viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0)); ObservableList<Abbreviation> expected = FXCollections.observableArrayList(repository.getAllLoaded()); ObservableList<Abbreviation> actualAbbreviations = FXCollections .observableArrayList(viewModel.abbreviationsProperty().stream() .map(AbbreviationViewModel::getAbbreviationObject) .collect(Collectors.toList())); assertEquals(expected, actualAbbreviations); }
Source:
private void waitForChanges(int direction) throws InterruptedException { if (direction != DIRECTION_DOWNLOAD && direction != DIRECTION_UPLOAD) { throw new IllegalArgumentException("Unknown direction: " + direction); } if (!isClosed) { String realmPath = configuration.getPath(); WaitForSessionWrapper wrapper = new WaitForSessionWrapper(); waitingForServerChanges.set(wrapper); boolean listenerRegistered = (direction == DIRECTION_DOWNLOAD) ? nativeWaitForDownloadCompletion(realmPath) : nativeWaitForUploadCompletion(realmPath); if (!listenerRegistered) { waitingForServerChanges.set(null); String errorMsg = ""; switch (direction) { case DIRECTION_DOWNLOAD: errorMsg = "It was not possible to download all remote changes."; break; case DIRECTION_UPLOAD: errorMsg = "It was not possible upload all local changes."; break; default: throw new IllegalArgumentException("Unknown direction: " + direction); } throw new ObjectServerError(ErrorCode.UNKNOWN, errorMsg + " Has the SyncClient been started?"); } try { wrapper.waitForServerChanges(); } catch(InterruptedException e) { waitingForServerChanges.set(null); throw e; } try { if (!isClosed) { if (!wrapper.isSuccess()) { wrapper.throwExceptionIfNeeded(); } } } finally { waitingForServerChanges.set(null); } } }

Target:
private void waitForChanges(int direction) throws InterruptedException { if (direction != DIRECTION_DOWNLOAD && direction != DIRECTION_UPLOAD) { throw new IllegalArgumentException("Unknown direction: " + direction); } if (!isClosed) { String realmPath = configuration.getPath(); WaitForSessionWrapper wrapper = new WaitForSessionWrapper(); waitingForServerChanges.set(wrapper); int callbackId = waitCounter.incrementAndGet(); boolean listenerRegistered = (direction == DIRECTION_DOWNLOAD) ? nativeWaitForDownloadCompletion(callbackId, realmPath) : nativeWaitForUploadCompletion(callbackId, realmPath); if (!listenerRegistered) { waitingForServerChanges.set(null); String errorMsg = ""; switch (direction) { case DIRECTION_DOWNLOAD: errorMsg = "It was not possible to download all remote changes."; break; case DIRECTION_UPLOAD: errorMsg = "It was not possible upload all local changes."; break; default: throw new IllegalArgumentException("Unknown direction: " + direction); } throw new ObjectServerError(ErrorCode.UNKNOWN, errorMsg + " Has the SyncClient been started?"); } try { wrapper.waitForServerChanges(); } catch(InterruptedException e) { waitingForServerChanges.set(null); throw e; } try { if (!isClosed) { if (!wrapper.isSuccess()) { wrapper.throwExceptionIfNeeded(); } } } finally { waitingForServerChanges.set(null); } } }
Source:
private static void setOMNodeSpecificConfigs( OzoneConfiguration ozoneConfiguration, String omServiceId, String omNodeId) { String[] confKeys = new String[] { OMConfigKeys.OZONE_OM_HTTP_ADDRESS_KEY, OMConfigKeys.OZONE_OM_HTTPS_ADDRESS_KEY, OMConfigKeys.OZONE_OM_HTTP_BIND_HOST_KEY, OMConfigKeys.OZONE_OM_HTTPS_BIND_HOST_KEY, OMConfigKeys.OZONE_OM_HTTP_KERBEROS_KEYTAB_FILE, OMConfigKeys.OZONE_OM_HTTP_KERBEROS_PRINCIPAL_KEY, OMConfigKeys.OZONE_OM_KERBEROS_KEYTAB_FILE_KEY, OMConfigKeys.OZONE_OM_KERBEROS_PRINCIPAL_KEY, OMConfigKeys.OZONE_OM_DB_DIRS, OMConfigKeys.OZONE_OM_ADDRESS_KEY, }; for (String confKey : confKeys) { String confValue = OmUtils.getConfSuffixedWithOMNodeId( ozoneConfiguration, confKey, omServiceId, omNodeId); if (confValue != null) { LOG.info("Setting configuration key with value of key {}: {}", confKey, OmUtils.addKeySuffixes(confKey, omNodeId), confValue); ozoneConfiguration.set(confKey, confValue); } } }

Target:
private static void setOMNodeSpecificConfigs( OzoneConfiguration ozoneConfiguration, String omServiceId, String omNodeId) { for (String confKey : genericConfigKeys) { String confValue = OmUtils.getConfSuffixedWithOMNodeId( ozoneConfiguration, confKey, omServiceId, omNodeId); if (confValue != null) { LOG.info("Setting configuration key with value of key {}: {}", confKey, OmUtils.addKeySuffixes(confKey, omNodeId), confValue); ozoneConfiguration.set(confKey, confValue); } } }
Source:
public void teardown() { WorkbenchShellHandler.getInstance().closeAllNonWorbenchShells(); ProjectExplorer pe = new ProjectExplorer(); pe.open(); for (Project p : pe.getProjects()) { p.delete(true); } new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); new DefaultEditor(CENTRAL_LABEL); }

Target:
public void teardown() { WorkbenchShellHandler.getInstance().closeAllNonWorbenchShells(); new ProjectExplorer().deleteAllProjects(); new DefaultToolItem(new WorkbenchShell(), CENTRAL_LABEL).click(); new DefaultEditor(CENTRAL_LABEL); }
Source:
public ChargeEntity markDelayedCaptureChargeAsCaptureApproved(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { ChargeStatus currentStatus = fromString(charge.getStatus()); if (chargeCanBeSkipped(charge)) { logger.info("Skipping charge [charge_external_id={}] with status from marking as CAPTURE APPROVED", currentStatus, externalId); return charge; } if (currentStatus == AWAITING_CAPTURE_REQUEST) { try { transitionChargeState(charge, CAPTURE_APPROVED); } catch (InvalidStateTransitionException e) { throw new ConflictRuntimeException(charge.getExternalId(), format("attempt to perform delayed capture on invalid charge state")); } } else { throw new ConflictRuntimeException(charge.getExternalId(), format("attempt to perform delayed capture on charge not in %s state.", AWAITING_CAPTURE_REQUEST)); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }

Target:
public ChargeEntity markDelayedCaptureChargeAsCaptureApproved(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { switch (fromString(charge.getStatus())) { case AWAITING_CAPTURE_REQUEST: try { transitionChargeState(charge, CAPTURE_APPROVED); } catch (InvalidStateTransitionException e) { throw new ConflictRuntimeException(charge.getExternalId(), "attempt to perform delayed capture on invalid charge state " + e.getMessage()); } return charge; case CAPTURE_APPROVED: case CAPTURE_APPROVED_RETRY: case CAPTURE_READY: case CAPTURE_SUBMITTED: case CAPTURED: return charge; default: throw new ConflictRuntimeException(charge.getExternalId(), format("attempt to perform delayed capture on charge not in %s state.", AWAITING_CAPTURE_REQUEST) ); } }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }
Source:
private int getSegment(Object key) { if (cacheMode.needsStateTransfer()) { return keyPartitioner.getSegment(key); } return 0; }

Target:
private int getSegment(Object key) { return keyPartitioner.getSegment(key); }
Source:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EmptyLineSeparatorCheck.class); final String[] expected = { "21: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "import"), "28: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, " "36: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "CLASS_DEF"), "39: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "VARIABLE_DEF"), "40: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "STATIC_INIT"), "44: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "INSTANCE_INIT"), "58: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "CTOR_DEF"), "63: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "METHOD_DEF"), "80: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "METHOD_DEF"), "111: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "INTERFACE_DEF"), }; verify(checkConfig, getPath("InputEmptyLineSeparator.java"), expected); }

Target:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EmptyLineSeparatorCheck.class); final String[] expected = { "21: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "import"), "38: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "CLASS_DEF"), "41: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "VARIABLE_DEF"), "42: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "STATIC_INIT"), "46: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "INSTANCE_INIT"), "60: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "CTOR_DEF"), "65: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "METHOD_DEF"), "82: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "METHOD_DEF"), "113: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "INTERFACE_DEF"), }; verify(checkConfig, getPath("InputEmptyLineSeparator.java"), expected); }
Source:
public void testHasItem() { VirtualFile myFile = myFixture.copyFileToProject("themeEditor/styles_1.xml", "res/values/styles.xml"); myFixture.copyFileToProject("themeEditor/attrs.xml", "res/values/attrs.xml"); Configuration configuration = myFacet.getConfigurationManager().getConfiguration(myFile); ThemeResolver themeResolver = new ThemeResolver(configuration); ThemeEditorStyle theme = themeResolver.getTheme("@style/AppTheme"); assertNotNull(theme); ThemeEditorStyle parent = theme.getParent(); assertNotNull(parent); ItemResourceValue hasItem = new ItemResourceValue("myColor", false, "?android:attr/colorBackground", false); ItemResourceValue hasNotItem = new ItemResourceValue("myHasNot", false, "?android:attr/colorBackground", false); ItemResourceValue hasInParent = new ItemResourceValue("editTextStyle", true, "?android:attr/colorBackground", true); assertEquals(true, theme.hasItem(new EditedStyleItem(hasItem, theme))); assertEquals(false, theme.hasItem(new EditedStyleItem(hasNotItem, theme))); assertEquals(true, theme.getParent().hasItem(new EditedStyleItem(hasInParent, parent))); assertEquals(false, theme.hasItem(new EditedStyleItem(hasInParent, parent))); }

Target:
public void testHasItem() { VirtualFile myFile = myFixture.copyFileToProject("themeEditor/styles_1.xml", "res/values/styles.xml"); myFixture.copyFileToProject("themeEditor/attrs.xml", "res/values/attrs.xml"); Configuration configuration = myFacet.getConfigurationManager().getConfiguration(myFile); ThemeResolver themeResolver = new ThemeResolver(configuration); ThemeEditorStyle theme = themeResolver.getTheme("@style/AppTheme"); assertNotNull(theme); ThemeEditorStyle parent = theme.getParent(); assertNotNull(parent); ItemResourceValue hasItem = new ItemResourceValue("myColor", false, "?android:attr/colorBackground", false); ItemResourceValue hasNotItem = new ItemResourceValue("myHasNot", false, "?android:attr/colorBackground", false); ItemResourceValue hasInParent = new ItemResourceValue("editTextStyle", true, "?android:attr/colorBackground", true); assertTrue(theme.hasItem(new EditedStyleItem(hasItem, theme))); assertFalse(theme.hasItem(new EditedStyleItem(hasNotItem, theme))); assertTrue(theme.getParent().hasItem(new EditedStyleItem(hasInParent, parent))); assertFalse(theme.hasItem(new EditedStyleItem(hasInParent, parent))); }
Source:
public void testReviewsWithSameChangeId() throws Exception { if (reviewHarness.getClient().isVersion29OrLater(new NullProgressMonitor())) { String branchName = "test_side_branch"; createBranchIfNonExistent(branchName); ReviewHarness reviewHarness2 = reviewHarness.duplicate(); reviewHarness2.init("HEAD:refs/for/" + branchName, PrivilegeLevel.USER, "otherTestFile.txt", true); reviewHarness.retrieve(); reviewHarness2.retrieve(); assertEquals(reviewHarness.getReview().getKey(), reviewHarness2.getReview().getKey()); assertThat(reviewHarness.getReview().getId(), is(not(reviewHarness2.getReview().getId()))); assertThat(reviewHarness.getReview().getSets().size(), is(1)); assertThat(reviewHarness.getReview().getSets().get(0).getId(), is("1")); PatchSetDetail detail = retrievePatchSetDetail(reviewHarness, "1"); assertThat(detail.getPatches().size(), is(2)); assertThat(detail.getPatches().get(0).getFileName(), is("/COMMIT_MSG")); assertThat(detail.getPatches().get(1).getFileName(), is("testFile1.txt")); assertThat(reviewHarness2.getReview().getSets().size(), is(1)); assertThat(reviewHarness2.getReview().getSets().get(0).getId(), is("1")); PatchSetDetail detail2 = retrievePatchSetDetail(reviewHarness2, "1"); assertThat(detail2.getPatches().size(), is(2)); assertThat(detail2.getPatches().get(0).getFileName(), is("/COMMIT_MSG")); assertThat(detail2.getPatches().get(1).getFileName(), is("otherTestFile.txt")); } }

Target:
public void testReviewsWithSameChangeId() throws Exception { if (!supportsBranchCreation()) { return; } String branchName = "test_side_branch"; createBranchIfNonExistent(branchName); ReviewHarness reviewHarness2 = reviewHarness.duplicate(); reviewHarness2.init("HEAD:refs/for/" + branchName, PrivilegeLevel.USER, "otherTestFile.txt", true); reviewHarness.retrieve(); reviewHarness2.retrieve(); assertEquals(reviewHarness.getReview().getKey(), reviewHarness2.getReview().getKey()); assertThat(reviewHarness.getReview().getId(), is(not(reviewHarness2.getReview().getId()))); assertThat(reviewHarness.getReview().getSets().size(), is(1)); assertThat(reviewHarness.getReview().getSets().get(0).getId(), is("1")); PatchSetDetail detail = retrievePatchSetDetail(reviewHarness, "1"); assertThat(detail.getPatches().size(), is(2)); assertThat(detail.getPatches().get(0).getFileName(), is("/COMMIT_MSG")); assertThat(detail.getPatches().get(1).getFileName(), is("testFile1.txt")); assertThat(reviewHarness2.getReview().getSets().size(), is(1)); assertThat(reviewHarness2.getReview().getSets().get(0).getId(), is("1")); PatchSetDetail detail2 = retrievePatchSetDetail(reviewHarness2, "1"); assertThat(detail2.getPatches().size(), is(2)); assertThat(detail2.getPatches().get(0).getFileName(), is("/COMMIT_MSG")); assertThat(detail2.getPatches().get(1).getFileName(), is("otherTestFile.txt")); }
Source:
private static Data getData(@NotNull PsiElement element) { if (!element.isValid() || !element.isWritable()) return null; GoAssignmentStatement assignment = getValidAssignmentParent(element); GoReferenceExpression selectedFieldReference = assignment != null ? getFieldReferenceExpression(element, assignment) : null; if (selectedFieldReference == null) return null; GoVarDefinition structDefinition = getDefinition(selectedFieldReference); GoStatement previousStatement = PsiTreeUtil.getPrevSiblingOfType(assignment, GoStatement.class); boolean needReplaceDeclarationWithShortVar = isUnassigned(getSingleVarSpecByDefinition(previousStatement, structDefinition)); GoCompositeLit compositeLit = needReplaceDeclarationWithShortVar ? createStructLiteral(structDefinition, previousStatement.getProject()) : getStructLiteralByReference(selectedFieldReference, assignment); if (compositeLit == null || structDefinition == null) return null; List<GoReferenceExpression> references = getUninitializedSingleFieldReferences(assignment, structDefinition, compositeLit); return !references.isEmpty() ? new Data(assignment, compositeLit, references, previousStatement, structDefinition.getText(), needReplaceDeclarationWithShortVar) : null; }

Target:
private static Data getData(@NotNull PsiElement element) { if (!element.isValid() || !element.isWritable()) return null; GoAssignmentStatement assignment = getValidAssignmentParent(element); GoStatement previousStatement = assignment != null ? PsiTreeUtil.getPrevSiblingOfType(assignment, GoStatement.class) : null; GoReferenceExpression selectedFieldReferenceExpression = previousStatement != null ? getFieldReferenceExpression(element, assignment, previousStatement) : null; if (selectedFieldReferenceExpression == null) return null; GoVarDefinition structDefinition = getDefinition(selectedFieldReferenceExpression); boolean needReplaceDeclarationWithShortVar = isUnassigned(getSingleVarSpecByDefinition(previousStatement, structDefinition)); GoCompositeLit compositeLit = structDefinition != null ? getStructLiteralByDefinition(structDefinition, previousStatement) : null; GoNamedElement field = ObjectUtils.tryCast(selectedFieldReferenceExpression.resolve(), GoNamedElement.class); if (compositeLit == null && !needReplaceDeclarationWithShortVar || !hasStructTypeWithField(structDefinition, field)) return null; List<GoReferenceExpression> references = getUninitializedSingleFieldReferences(assignment, previousStatement, structDefinition, compositeLit); return !references.isEmpty() ? new Data(assignment, compositeLit, references, previousStatement, structDefinition) : null; }