auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected SWTBotEditor openRepresentation(Session session, String representationDescriptionName, final String representationName, Class<? extends DRepresentation> expectedRepresentationClass, boolean disableSnapToGridOnThisEditor, boolean disableSnapToShapeOnThisEditor) { DRepresentation representation = getRepresentationWithName(session, representationDescriptionName, representationName); TestCase.assertTrue("This representation should be a " + expectedRepresentationClass.getSimpleName(), expectedRepresentationClass.isInstance(representation)); DialectUIManager.INSTANCE.openEditor(session, representation, new NullProgressMonitor()); SWTBotUtils.waitAllUiEvents(); SWTBotEditor swtBotEditor = null; String expectedTitle = representationName; if (TestsUtil.isLunaPlatform()) { expectedTitle = Objects.firstNonNull(representationName, "").trim(); } if (DDiagram.class.isAssignableFrom(expectedRepresentationClass)) { swtBotEditor = SWTBotSiriusHelper.getSiriusDiagramEditor(expectedTitle); if (disableSnapToGridOnThisEditor) { ((SWTBotSiriusDiagramEditor) swtBotEditor).setSnapToGrid(false); } if (disableSnapToShapeOnThisEditor) { ((SWTBotSiriusDiagramEditor) swtBotEditor).setSnapToShape(false); } } else { swtBotEditor = SWTBotSiriusHelper.getSiriusEditor(expectedTitle); } return swtBotEditor; }

Target:
protected SWTBotEditor openRepresentation(Session session, String representationDescriptionName, final String representationName, Class<? extends DRepresentation> expectedRepresentationClass, boolean disableSnapToGridOnThisEditor, boolean disableSnapToShapeOnThisEditor) { DRepresentation representation = getRepresentationWithName(session, representationDescriptionName, representationName); TestCase.assertTrue("This representation should be a " + expectedRepresentationClass.getSimpleName(), expectedRepresentationClass.isInstance(representation)); IEditorPart editorPart = DialectUIManager.INSTANCE.openEditor(session, representation, new NullProgressMonitor()); SWTBotUtils.waitAllUiEvents(); SWTBotEditor swtBotEditor = null; String expectedTitle = editorPart.getTitle(); if (TestsUtil.isLunaPlatform()) { expectedTitle = Objects.firstNonNull(representationName, "").trim(); } if (DDiagram.class.isAssignableFrom(expectedRepresentationClass)) { swtBotEditor = SWTBotSiriusHelper.getSiriusDiagramEditor(expectedTitle); if (disableSnapToGridOnThisEditor) { ((SWTBotSiriusDiagramEditor) swtBotEditor).setSnapToGrid(false); } if (disableSnapToShapeOnThisEditor) { ((SWTBotSiriusDiagramEditor) swtBotEditor).setSnapToShape(false); } } else { swtBotEditor = SWTBotSiriusHelper.getSiriusEditor(expectedTitle); } return swtBotEditor; }
Source:
protected String getDocumentSkinExtensionURL(DocumentReference documentReference, String documentName, String pluginName, XWikiContext context) { String queryString = String.format("%s&amp;%s&amp;%s%s", getLanguageQueryString(context), getDocumentVersionQueryString(documentReference, context), getWikiVersionQueryString(context), parametersAsQueryString(documentName, context)); return context.getWiki().getURL(documentReference, pluginName, queryString, "", context); }

Target:
protected String getDocumentSkinExtensionURL(DocumentReference documentReference, String documentName, String pluginName, XWikiContext context) { String queryString = String.format("%s&amp;%s%s", getLanguageQueryString(context), getDocumentVersionQueryString(documentReference, context), parametersAsQueryString(documentName, context)); return context.getWiki().getURL(documentReference, pluginName, queryString, "", context); }
Source:
public void setCustomHeader(String field, String value) { String lowerCaseField = field.toLowerCase(); if (lowerCaseField.equals("content-type") || lowerCaseField.equals("authorization")) { return; } customHeaders.put(field, value); }

Target:
public void setCustomHeader(String field, String value) { HttpCustomHeader header; int index = findCustomHeader(field.toLowerCase()); if (index >= 0) { header = customHeaders.get(index); header.setValue(value); } else { header = new HttpCustomHeader(field, value); customHeaders.add(header); } }
Source:
public void releaseStore(Store<?, ?> resource) throws CacheAccessException { Map.Entry<CachingTier.Provider, AuthoritativeTier.Provider> entry = providersMap.get(resource); if (entry == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } CacheStore cacheStore = (CacheStore) resource; cacheStore.flushAll((Store)cacheStore.realCachingTier); entry.getKey().releaseCachingTier(cacheStore.realCachingTier); entry.getValue().releaseAuthoritativeTier(cacheStore.authoritativeTier); }

Target:
public void releaseStore(Store<?, ?> resource) { Map.Entry<CachingTier.Provider, AuthoritativeTier.Provider> entry = providersMap.get(resource); if (entry == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } CacheStore cacheStore = (CacheStore) resource; entry.getKey().releaseCachingTier(cacheStore.realCachingTier); entry.getValue().releaseAuthoritativeTier(cacheStore.authoritativeTier); }
Source:
protected void handleDispose(DisposeEvent event) { editingDomainChange(getCompareConfiguration().getEditingDomain(), null); getCompareConfiguration().getEventBus().unregister(this); differenceGroupProvider.dispose(); super.handleDispose(event); }

Target:
protected void handleDispose(DisposeEvent event) { editingDomainChange(getCompareConfiguration().getEditingDomain(), null); getCompareConfiguration().getEventBus().unregister(this); if (differenceGroupProvider != null) { differenceGroupProvider.dispose(); } super.handleDispose(event); }
Source:
public void close() throws StoreException, InterruptedException { persistor.write(); try { hardDeleter.persistCleanupToken(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while persisting cleanup token ", e); } File cleanShutdownFile = new File(dataDir, Clean_Shutdown_Filename); try { cleanShutdownFile.createNewFile(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while creating clean shutdown file ", e); } }

Target:
public void close() throws StoreException { persistor.write(); try { hardDeleter.shutDown(); } catch (Exception e) { logger.error("Index : " + dataDir + " error while persisting cleanup token ", e); } File cleanShutdownFile = new File(dataDir, Clean_Shutdown_Filename); try { cleanShutdownFile.createNewFile(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while creating clean shutdown file ", e); } }
Source:
protected static File searchPath(String path, String... lookFor) { if (path == null) return null; for (String p : path.split(File.pathSeparator)) { for (String command : lookFor) { try { final File e = new File(p, command); if (e.isFile()) { return e.getAbsoluteFile(); } } catch (SecurityException e) { LOG.warn("The path '{}' isn't accessible. Skip it", command); } } } return null; }

Target:
protected static File searchPath(String path, String... lookFor) { if (path == null) return null; for (String p : path.split(File.pathSeparator)) { for (String command : lookFor) { final File file = new File(p, command); try { if (file.isFile()) { return file.getAbsoluteFile(); } } catch (SecurityException e) { LOG.warn("The path '{}' isn't accessible. Skip it", file.getPath()); } } } return null; }
Source:
public void init(ServletConfig config) throws ServletException { super.init(config); url = EngineLocalConfig.getInstance().expandString(config.getInitParameter(URL).replaceAll("%\\{", "\\${")); url404 = EngineLocalConfig.getInstance().expandString(config.getInitParameter(URL404).replaceAll("%\\{", "\\${")); }

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); url = EngineLocalConfig.getInstance().expandString(config.getInitParameter(URL).replaceAll("%\\{", "\\${")); url404 = EngineLocalConfig.getInstance().expandString(config.getInitParameter(URL404).replaceAll("%\\{", "\\${")); if (StringUtils.isEmpty(url404)) { url404 = url404Default; } }
Source:
protected RequestTemplate resolve(Object[] argv, RequestTemplate mutable, Map<String, Object> variables) { final HashMap<String, Boolean> variableToEncoded = new HashMap<String, Boolean>(); for (Entry<Integer, Boolean> entry : metadata.indexToEncoded().entrySet()) { final Collection<String> names = metadata.indexToName().get(entry.getKey()); for (String name : names) { variableToEncoded.put(name, entry.getValue()); } } return mutable.resolve(variables, variableToEncoded); }

Target:
protected RequestTemplate resolve(Object[] argv, RequestTemplate mutable, Map<String, Object> variables) { Map<String, Boolean> variableToEncoded = new LinkedHashMap<String, Boolean>(); for (Entry<Integer, Boolean> entry : metadata.indexToEncoded().entrySet()) { Collection<String> names = metadata.indexToName().get(entry.getKey()); for (String name : names) { variableToEncoded.put(name, entry.getValue()); } } return mutable.resolve(variables, variableToEncoded); }
Source:
private String getEntityRouting(Object entity) { ElasticsearchPersistentEntity<?> persistentEntity = getRequiredPersistentEntity(entity.getClass()); Iterable<ElasticsearchPersistentProperty> routingProperties = persistentEntity.getPersistentProperties(JoinTypeRelations.class); Iterator<ElasticsearchPersistentProperty> routingPropertyIterator = routingProperties.iterator(); String routingProp = null; if (routingPropertyIterator.hasNext()) { ElasticsearchPersistentProperty routingProperty = routingPropertyIterator.next(); if (routingProperty != null) { Object joinRouting = persistentEntity.getPropertyAccessor(entity) .getProperty(routingProperty); if (joinRouting instanceof JoinField) { JoinField<?> joinField = (JoinField<?>) joinRouting; routingProp = stringIdRepresentation(joinField.getParent()); } } } if (routingPropertyIterator.hasNext()) { throw new RuntimeException("No more than one routing field"); } return routingProp; }

Target:
private String getEntityRouting(Object entity) { ElasticsearchPersistentEntity<?> persistentEntity = getRequiredPersistentEntity(entity.getClass()); ElasticsearchPersistentProperty joinProperty = persistentEntity.getJoinFieldProperty(); if (joinProperty != null) { Object joinField = persistentEntity.getPropertyAccessor(entity).getProperty(joinProperty); if (joinField != null && JoinField.class.isAssignableFrom(joinField.getClass()) && ((JoinField<?>) joinField).getParent() != null) { return elasticsearchConverter.convertId(((JoinField<?>) joinField).getParent()); } } return null; }
Source:
private void tryEnqueueSubscriptionShutdownEvent(SubscriptionShutdownEvent subscriptionShutdownEvent) { try { parent.recordsDeliveryQueue .add(new RecordsRetrievedContext(Either.right(subscriptionShutdownEvent), this, Instant.now())); } catch (Exception e) { log.warn( "{}: Unable to enqueue the shutdown event due to capacity restrictions in delivery queue with remaining capacity {}. Ignoring. Last successful response: RequestId - {}, Timestamp - {}", parent.shardId, subscriptionShutdownEvent.getEventIdentifier(), parent.recordsDeliveryQueue.remainingCapacity(), subscriptionShutdownEvent.getShutdownEventThrowableOptional(), parent.getLastSuccessfulResponseRequestId(), parent.getLastSuccessfulResponseTimestamp()); } }

Target:
private void tryEnqueueSubscriptionShutdownEvent(SubscriptionShutdownEvent subscriptionShutdownEvent) { try { parent.recordsDeliveryQueue .add(new RecordsRetrievedContext(Either.right(subscriptionShutdownEvent), this, Instant.now())); } catch (Exception e) { log.warn( "{}: Unable to enqueue the shutdown event due to capacity restrictions in delivery queue with remaining capacity {}. Ignoring. Last successful request details -- {}", parent.shardId, subscriptionShutdownEvent.getEventIdentifier(), parent.recordsDeliveryQueue.remainingCapacity(), parent.lastSuccessfulRequestDetails, subscriptionShutdownEvent.getShutdownEventThrowableOptional()); } }
Source:
public String toString() { return "SpongeRegistryType{" + "root=" + root + ", location=" + location + '}'; }

Target:
public String toString() { return new StringJoiner(", ", SpongeRegistryType.class.getSimpleName() + "[", "]") .add("root=" + this.root) .add("location='" + this.location + "'") .toString(); }
Source:
public boolean hasDocString() { return doc_string!=null; }

Target:
public boolean hasDocString() { return doc_string != null && StringUtils.isNotEmpty(doc_string.getValue()); }
Source:
public void addTasksOnWakeup(Runnable task) { if (!lockAddNewTasks) { tasksOnWakeup.add(task); wakeUp(); } }

Target:
public void addTasksOnWakeup(Runnable task) { tasksOnWakeup.add(task); wakeUp(); }
Source:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity runtimeID) throws InfrastructureException { if (!trustedStoreInitialized) { return; } ConfigMap allCaCertsConfigMap = cheServerClientFactory .create() .configMaps() .inNamespace(installationLocationNamespace) .withName(caBundleConfigMap) .get(); if (allCaCertsConfigMap == null) { return; } KubernetesNamespace namespace = namespaceFactory.getOrCreate(runtimeID); k8sEnv .getConfigMaps() .put( configMapName, new ConfigMapBuilder() .withMetadata( new ObjectMetaBuilder() .withName(configMapName) .withAnnotations(allCaCertsConfigMap.getMetadata().getAnnotations()) .withLabels(configMapLabelKeyValue) .build()) .withApiVersion(allCaCertsConfigMap.getApiVersion()) .withData(allCaCertsConfigMap.getData()) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { if (pod.getRole() == PodRole.DEPLOYMENT) { if (pod.getSpec() .getVolumes() .stream() .noneMatch(v -> v.getName().equals(CHE_TRUST_STORE_VOLUME))) { pod.getSpec() .getVolumes() .add( new VolumeBuilder() .withName(CHE_TRUST_STORE_VOLUME) .withConfigMap( new ConfigMapVolumeSourceBuilder().withName(configMapName).build()) .build()); } } for (Container container : pod.getSpec().getInitContainers()) { provisionTrustStoreVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionTrustStoreVolumeMountIfNeeded(container); } } }

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity runtimeID) throws InfrastructureException { if (!trustedStoreInitialized) { return; } ConfigMap allCaCertsConfigMap = cheServerClientFactory .create() .configMaps() .inNamespace(installationLocationNamespace) .withName(caBundleConfigMap) .get(); if (allCaCertsConfigMap == null) { return; } k8sEnv .getConfigMaps() .put( configMapName, new ConfigMapBuilder() .withMetadata( new ObjectMetaBuilder() .withName(configMapName) .withAnnotations(allCaCertsConfigMap.getMetadata().getAnnotations()) .withLabels(configMapLabelKeyValue) .build()) .withApiVersion(allCaCertsConfigMap.getApiVersion()) .withData(allCaCertsConfigMap.getData()) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { if (pod.getRole() == PodRole.DEPLOYMENT) { if (pod.getSpec() .getVolumes() .stream() .noneMatch(v -> v.getName().equals(CHE_TRUST_STORE_VOLUME))) { pod.getSpec() .getVolumes() .add( new VolumeBuilder() .withName(CHE_TRUST_STORE_VOLUME) .withConfigMap( new ConfigMapVolumeSourceBuilder().withName(configMapName).build()) .build()); } } for (Container container : pod.getSpec().getInitContainers()) { provisionTrustStoreVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionTrustStoreVolumeMountIfNeeded(container); } } }
Source:
public static Map<String, String> toQueryParameters(String coverageId) { return Maps.of( "service", "WCS", "version", "2.0.1", "request", "DescribeCoverage", "coverageId", coverageId); }

Target:
public static Map<String, String> toQueryParameters(String coverageId) { return Maps.of( "service", "WCS", "version", WCS.VERSION_201, "request", "DescribeCoverage", "coverageId", coverageId); }
Source:
JarFileUtils(IPostProcessor processor, String xmlPathInJar, List<String> testNames) { this(processor, xmlPathInJar, testNames, null); }

Target:
JarFileUtils(IPostProcessor processor, String xmlPathInJar, List<String> testNames) { this(processor, xmlPathInJar, testNames, XmlSuite.ParallelMode.NONE); }
Source:
public boolean handleUri(String uriScheme, String uri) throws CoreException { IUriSchemeHandler handler = null; if (createdHandlers.containsKey(uriScheme)) { handler = createdHandlers.get(uriScheme); } else { handler = reader.getHandlerFromExtensionPoint(uriScheme); createdHandlers.put(uriScheme, handler); } if (handler != null) { handler.handle(uri); } return handler != null; }

Target:
public void handleUri(String uriScheme, String uri) throws CoreException { IUriSchemeHandler handler = null; handler = getHandler(uriScheme); if (handler != null) { handler.handle(uri); } }
Source:
public void channelInactiveTest() { HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); ChunkedWriteHandler chunkedWriteHandler = new ChunkedWriteHandler(); EmbeddedChannel channel = new EmbeddedChannel(chunkedWriteHandler); NettyResponseChannel nettyResponseChannel = new NettyResponseChannel(new MockChannelHandlerContext(channel), new NettyMetrics(new MetricRegistry()), new PerformanceConfig(new VerifiableProperties(new Properties()))); channel.disconnect().awaitUninterruptibly(); assertFalse("Channel should be closed", channel.isOpen()); Future<Long> future = nettyResponseChannel.write(Unpooled.buffer(1), null); try { future.get(); } catch (InterruptedException | ExecutionException e) { assertTrue("Should be ClosedChannelException", e.getCause() instanceof ClosedChannelException); } }

Target:
public void channelInactiveTest() { HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); ChunkedWriteHandler chunkedWriteHandler = new ChunkedWriteHandler(); EmbeddedChannel channel = new EmbeddedChannel(chunkedWriteHandler); NettyResponseChannel nettyResponseChannel = new NettyResponseChannel(new MockChannelHandlerContext(channel), new NettyMetrics(new MetricRegistry()), new PerformanceConfig(new VerifiableProperties(new Properties()))); channel.disconnect().awaitUninterruptibly(); assertFalse("Channel should be closed", channel.isOpen()); Future<Long> future = nettyResponseChannel.write(Unpooled.buffer(1), null); try { future.get(); fail("Future.get() should throw exception."); } catch (InterruptedException | ExecutionException e) { assertTrue("Should be ClosedChannelException", e.getCause() instanceof ClosedChannelException); } }
Source:
private void handleNavIntent() { Log.d(TAG, "handleNavIntent()"); Intent intent = getIntent(); if (intent.hasExtra(EXTRA_FEED_ID) || intent.hasExtra(EXTRA_REFRESH_ON_START) || (intent.hasExtra(EXTRA_NAV_TYPE) && (intent.hasExtra(EXTRA_NAV_INDEX) || intent.hasExtra(EXTRA_FRAGMENT_TAG)))) { int index = intent.getIntExtra(EXTRA_NAV_INDEX, -1); String tag = intent.getStringExtra(EXTRA_FRAGMENT_TAG); Bundle args = intent.getBundleExtra(EXTRA_FRAGMENT_ARGS); boolean refreshOnStart = intent.getBooleanExtra(EXTRA_REFRESH_ON_START, false); if (refreshOnStart) { tag = QueueFragment.TAG; args = new Bundle(); args.putBoolean(QueueFragment.ARG_REFRESH_ON_START, true); } long feedId = intent.getLongExtra(EXTRA_FEED_ID, 0); if (index >= 0) { loadFragment(index, args); } else if (tag != null) { loadFragment(tag, args); } else if(feedId > 0) { loadFeedFragmentById(feedId, args); } } setIntent(new Intent(MainActivity.this, MainActivity.class)); }

Target:
private void handleNavIntent() { Intent intent = getIntent(); if (intent.hasExtra(EXTRA_FEED_ID) || intent.hasExtra(EXTRA_FRAGMENT_TAG) || intent.hasExtra(EXTRA_REFRESH_ON_START)) { Log.d(TAG, "handleNavIntent()"); String tag = intent.getStringExtra(EXTRA_FRAGMENT_TAG); Bundle args = intent.getBundleExtra(EXTRA_FRAGMENT_ARGS); boolean refreshOnStart = intent.getBooleanExtra(EXTRA_REFRESH_ON_START, false); if (refreshOnStart) { AutoUpdateManager.runImmediate(this); } long feedId = intent.getLongExtra(EXTRA_FEED_ID, 0); if (tag != null) { loadFragment(tag, args); } else if (feedId > 0) { loadFeedFragmentById(feedId, args); } } else if (intent.getBooleanExtra(EXTRA_OPEN_PLAYER, false)) { sheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); bottomSheetCallback.onSlide(null, 1.0f); } setIntent(new Intent(MainActivity.this, MainActivity.class)); }
Source:
public void testBuilderWithUnsanitisedFieldValues() { AccountAttributes observedAccountAttributes = AccountAttributes.builder() .withGoogleId("googleId@gmail.com") .withName(" random name with extra spaces ") .withEmail(" email ") .withInstitute(" random institute name with extra spaces ") .withStudentProfileAttributes(StudentProfileAttributes.builder("googleId@gmail.com") .build()) .build(); assertEquals("googleId", observedAccountAttributes.getGoogleId()); assertEquals("random name with extra spaces", observedAccountAttributes.getName()); assertEquals("email", observedAccountAttributes.getEmail()); assertEquals("random institute name with extra spaces", observedAccountAttributes.getInstitute()); assertEquals("googleId", observedAccountAttributes.studentProfile.googleId); }

Target:
public void testBuilderWithUnsanitisedFieldValues() { AccountAttributes observedAccountAttributes = AccountAttributes.builder() .withGoogleId("googleId@gmail.com") .withName(" random name with extra spaces ") .withEmail(" email@example.com ") .withInstitute(" random institute name with extra spaces ") .withStudentProfileAttributes(StudentProfileAttributes.builder("googleId@gmail.com") .build()) .build(); assertEquals("googleId", observedAccountAttributes.getGoogleId()); assertEquals("random name with extra spaces", observedAccountAttributes.getName()); assertEquals("email@example.com", observedAccountAttributes.getEmail()); assertEquals("random institute name with extra spaces", observedAccountAttributes.getInstitute()); assertEquals("googleId", observedAccountAttributes.studentProfile.googleId); }
Source:
public synchronized List<String> getGroups(String user) throws IOException { Set<String> groupSet = new TreeSet<String>(); List<String> groups = Collections.emptyList(); for (GroupMappingServiceProvider provider : providersList) { try { groups = provider.getGroups(user); } catch (Exception e) { LOG.warn("Unable to get groups for user via because: {}", user, provider.getClass().getSimpleName(), e.toString()); LOG.debug("Stacktrace: ", e); } if (!groups.isEmpty()) { groupSet.addAll(groups); if (!combined) break; } } return Collections.unmodifiableList(new ArrayList<>(groupSet)); }

Target:
public synchronized List<String> getGroups(String user) throws IOException { Set<String> groupSet = new TreeSet<String>(); for (GroupMappingServiceProvider provider : providersList) { List<String> groups = Collections.emptyList(); try { groups = provider.getGroups(user); } catch (Exception e) { LOG.warn("Unable to get groups for user via because: {}", user, provider.getClass().getSimpleName(), e.toString()); LOG.debug("Stacktrace: ", e); } if (!groups.isEmpty()) { groupSet.addAll(groups); if (!combined) break; } } return new ArrayList<>(groupSet); }
Source:
public void testAllMethods() throws Exception { accountService = new InMemoryUnknownAccountServiceFactory(null, null, null).getAccountService(); Account refAccount = new AccountBuilder((short) 1, "a", Account.AccountStatus.INACTIVE, null).build(); assertEquals("Wrong account", Account.UNKNOWN_ACCOUNT, accountService.getAccountById(Utils.getRandomShort(random))); assertEquals("Wrong account", Account.UNKNOWN_ACCOUNT, accountService.getAccountById((short) -1)); assertEquals("Wrong account", Account.UNKNOWN_ACCOUNT, accountService.getAccountByName(UtilsTest.getRandomString(10))); assertEquals("Wrong size of account collection", 1, accountService.getAllAccounts().size()); assertFalse("Wrong return value from an unsuccessful update operation", accountService.updateAccounts(Collections.singletonList(refAccount))); assertEquals("Wrong size of account collection", 1, accountService.getAllAccounts().size()); accountService.close(); }

Target:
public void testAllMethods() throws Exception { accountService = new InMemoryUnknownAccountServiceFactory(null, null, null).getAccountService(); assertEquals("Wrong account", Account.UNKNOWN_ACCOUNT, accountService.getAccountById(Utils.getRandomShort(random))); assertEquals("Wrong account", Account.UNKNOWN_ACCOUNT, accountService.getAccountById((short) -1)); assertEquals("Wrong account", Account.UNKNOWN_ACCOUNT, accountService.getAccountByName(UtilsTest.getRandomString(10))); assertEquals("Wrong size of account collection", 1, accountService.getAllAccounts().size()); Account account = new AccountBuilder((short) 1, "a", Account.AccountStatus.INACTIVE, null).build(); assertFalse("Wrong return value from an unsuccessful update operation", accountService.updateAccounts(Collections.singletonList(account))); assertEquals("Wrong size of account collection", 1, accountService.getAllAccounts().size()); try { accountService.getAllAccounts().add(account); fail("Should have thrown."); } catch (UnsupportedOperationException e) { } accountService.close(); }
Source:
public void writeIdsToCqlStore( HttpServletRequest request, HttpServletResponse response ) { messageConsumerFactory.createConsumer( new CqlWritingConsumer(), JacksonMessageSerializer.forType(ResourceUpdatedMessage.class), KAFKA_TOPIC_NAME, KAFKA_CONSUMER_GROUP ).withFailedMessagePersistence(mongo); response.setStatus(200); try { response.getWriter().write("Started Mongo to CQL consumer"); } catch (IOException e) { throw Throwables.propagate(e); } }

Target:
public void writeIdsToCqlStore( HttpServletRequest request, HttpServletResponse response ) { if (this.cqlConsumer == null) { this.cqlConsumer = messageConsumerFactory.createConsumer( new CqlWritingConsumer(), JacksonMessageSerializer.forType(ResourceUpdatedMessage.class), KAFKA_TOPIC_NAME, KAFKA_CONSUMER_GROUP ).withFailedMessagePersistence(mongo) .build(); } cqlConsumer.startAsync().awaitRunning(); response.setStatus(200); try { response.getWriter().write("Started Mongo to CQL consumer"); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
public void testAddPatientCorrelationPLQ() throws Exception { PatientCorrelationProxyWebServiceUnsecuredImpl impl = getPatientCorrelationProxyWebServiceUnsecuredImpl(); impl.addPatientCorrelationPLQ(mockPLQrec, mockAssertion); when(mockWebProxy.getUrlLocalHomeCommunity(NhincConstants.PATIENT_CORRELATION_SERVICE_NAME)).thenReturn(""); verify(mockClient).invokePort(any(Class.class), any(String.class), any(Object.class)); verify(mockCONNECTClientFactory).getCONNECTClientUnsecured(any(ServicePortDescriptor.class), any(String.class), any(AssertionType.class)); }

Target:
public void testAddPatientCorrelationPLQ() throws Exception { PatientCorrelationProxyWebServiceUnsecuredImpl impl = getPatientCorrelationProxyWebServiceUnsecuredImpl(); impl.addPatientCorrelationPLQ(mockPLQrec, mockAssertion); verify(mockClient).invokePort(any(Class.class), any(String.class), any(AddPatientCorrelationPLQRequestType.class)); verify(mockCONNECTClientFactory).getCONNECTClientUnsecured(any(ServicePortDescriptor.class), any(String.class), any(AssertionType.class)); }
Source:
public void onBrowserEvent(final Event event) { switch (DOM.eventGetType(event)) { case Event.ONCLICK: { final Element td = getEventTargetCell(event); if (td == null) { break; } final int row = rowOf(td); if (getRowItem(row) != null) { onCellSingleClick(rowOf(td), columnOf(td)); return; } break; } case Event.ONDBLCLICK: { Element td = getEventTargetCell(event); if (td == null) { return; } onCellDoubleClick(rowOf(td), columnOf(td)); return; } } }

Target:
public void onBrowserEvent(final Event event) { switch (DOM.eventGetType(event)) { case Event.ONCLICK: { final Element td = getEventTargetCell(event); if (td == null) { break; } final int row = rowOf(td); if (getRowItem(row) != null) { onCellSingleClick(rowOf(td), columnOf(td)); return; } break; } case Event.ONDBLCLICK: { Element td = getEventTargetCell(event); if (td == null) { return; } onCellDoubleClick(rowOf(td), columnOf(td)); return; } } super.onBrowserEvent(event); }
Source:
private static void enableModernTLS(OkHttpClient.Builder builder) { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; SSLSocketFactory sslSocketFactory = TLSSocketFactoryCompat.getInstance(); builder.sslSocketFactory(sslSocketFactory, trustManager); List<CipherSuite> cipherSuites = new ArrayList<>(); cipherSuites.addAll(ConnectionSpec.MODERN_TLS.cipherSuites()); cipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA); cipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA); ConnectionSpec legacyTLS = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(cipherSuites.toArray(new CipherSuite[0])) .build(); builder.connectionSpecs(Arrays.asList(legacyTLS, ConnectionSpec.CLEARTEXT)); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { e.printStackTrace(); } }

Target:
private static void enableModernTLS(OkHttpClient.Builder builder) { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; SSLSocketFactory sslSocketFactory = TLSSocketFactoryCompat.getInstance(); builder.sslSocketFactory(sslSocketFactory, trustManager); List<CipherSuite> cipherSuites = new ArrayList<>(); cipherSuites.addAll(ConnectionSpec.MODERN_TLS.cipherSuites()); cipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA); cipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA); ConnectionSpec legacyTLS = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(cipherSuites.toArray(new CipherSuite[0])) .build(); builder.connectionSpecs(Arrays.asList(legacyTLS, ConnectionSpec.CLEARTEXT)); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { if (DEBUG) e.printStackTrace(); } }
Source:
private Vector calculateDistributedGradient(SparseDistributedMatrix data, Vector weights) { SparseDistributedMatrixMapReducer mapReducer = new SparseDistributedMatrixMapReducer(data); return mapReducer.mapReduce( (matrix, args) -> { Matrix inputs = extractInputs(matrix); Vector groundTruth = extractGroundTruth(matrix); return lossGradient.compute(inputs, groundTruth, args); }, gradients -> { Vector resultGradient = new DenseLocalOnHeapVector(data.columnSize()); int count = 0; for (Vector gradient : gradients) { if (gradient != null) { resultGradient = resultGradient.plus(gradient); count++; } } return resultGradient.divide(count); }, weights); }

Target:
private Vector calculateDistributedGradient(SparseDistributedMatrix data, Vector weights) { SparseDistributedMatrixMapReducer mapReducer = new SparseDistributedMatrixMapReducer(data); return mapReducer.mapReduce( (matrix, args) -> { Matrix inputs = extractInputs(matrix); Vector groundTruth = extractGroundTruth(matrix); return lossGradient.compute(inputs, groundTruth, args); }, gradients -> { int cnt = 0; Vector resGradient = new DenseLocalOnHeapVector(data.columnSize()); for (Vector gradient : gradients) { if (gradient != null) { resGradient = resGradient.plus(gradient); cnt++; } } return resGradient.divide(cnt); }, weights); }
Source:
private void collectStatementsFromUrl(URI uri, StatementCollector collector) throws RetryableException { RDFParser parser = Rio.createParser(RDFFormat.TURTLE); parser.setRDFHandler(new NormalizingRdfHandler(collector)); HttpGet request = new HttpGet(uri); request.setConfig(configWithTimeout); log.debug("Fetching rdf from {}", uri); try { try (CloseableHttpResponse response = client.execute(request)) { if (response.getStatusLine().getStatusCode() == 404) { return; } if (response.getStatusLine().getStatusCode() == 204) { log.debug("No content, we're done"); return; } if (response.getStatusLine().getStatusCode() >= 300) { throw new ContainedException("Unexpected status code fetching RDF for " + uri + ": " + response.getStatusLine().getStatusCode()); } InputStream in = getInputStream(response); if (in == null) { log.debug("Empty response, we're done"); return; } parser.parse(new InputStreamReader(in, Charsets.UTF_8), uri.toString()); in.close(); } } catch (UnknownHostException | SocketException | SSLHandshakeException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RetryableException("Error fetching RDF for " + uri, e); } catch (RDFParseException | RDFHandlerException e) { throw new ContainedException("RDF parsing error for " + uri, e); } }

Target:
private void collectStatementsFromUrl(URI uri, StatementCollector collector) throws RetryableException { RDFParser parser = Rio.createParser(RDFFormat.TURTLE); parser.setRDFHandler(new NormalizingRdfHandler(collector)); HttpGet request = new HttpGet(uri); request.setConfig(configWithTimeout); log.debug("Fetching rdf from {}", uri); try { try (CloseableHttpResponse response = client.execute(request)) { if (response.getStatusLine().getStatusCode() == 404) { return; } if (response.getStatusLine().getStatusCode() == 204) { log.debug("No content, we're done"); return; } if (response.getStatusLine().getStatusCode() >= 300) { throw new ContainedException("Unexpected status code fetching RDF for " + uri + ": " + response.getStatusLine().getStatusCode()); } try(InputStream in = getInputStream(response)) { if (in == null) { log.debug("Empty response, we're done"); return; } parser.parse(new InputStreamReader(in, Charsets.UTF_8), uri.toString()); } } } catch (UnknownHostException | SocketException | SSLHandshakeException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RetryableException("Error fetching RDF for " + uri, e); } catch (RDFParseException | RDFHandlerException e) { throw new ContainedException("RDF parsing error for " + uri, e); } }
Source:
public CommonProtos.ContentGroup serialize(T contentGroup) { CommonProtos.ContentGroup.Builder builder = CommonProtos.ContentGroup.newBuilder(); builder.setDescribed(new DescribedSerializer<ContentGroup>().serialize(contentGroup)); if (contentGroup.getType() != null) { builder.setType(contentGroup.getType().toString()); } if (contentGroup.getContents() != null) { builder.addAllContent(contentGroup.getContents().stream() .map(content -> new ContentRefSerializer(null).serialize(content).build()) .collect(Collectors.toList())); } return builder.build(); }

Target:
public CommonProtos.ContentGroup serialize(T contentGroup) { CommonProtos.ContentGroup.Builder builder = CommonProtos.ContentGroup.newBuilder(); builder.setDescribed(describedSerializer.serialize(contentGroup)); if (contentGroup.getType() != null) { builder.setType(contentGroup.getType().toString()); } if (contentGroup.getContents() != null) { builder.addAllContent(contentGroup.getContents().stream() .map(content -> contentRefSerializer.serialize(content).build()) .collect(Collectors.toList())); } return builder.build(); }
Source:
private SolShip cloneAndModifyShip(SolShip originalShip, String newShipID) { HullConfig newHullConfig; try { newHullConfig = game.getHullConfigManager().getConfig(newShipID); } catch (RuntimeException e) { return null; } SolShip newShip = game.getShipBuilder().build(game, originalShip.getPosition(), originalShip.getVelocity(), originalShip.getAngle(), originalShip.getRotationSpeed(), originalShip.getPilot(), originalShip.getItemContainer(), newHullConfig, newHullConfig.getMaxLife(), originalShip.getHull().getGun(false), originalShip.getHull().getGun(true), null, newHullConfig.getEngineConfig().exampleEngine.copy(), new ShipRepairer(), originalShip.getMoney(), null, originalShip.getShield(), originalShip.getArmor()); return newShip; }

Target:
private Optional<SolShip> cloneAndModifyShip(SolShip originalShip, String newShipID) { boolean isARealShip = false; for (ResourceUrn urn : Assets.getAssetHelper().list(Json.class)) { if((urn.getModuleName() + ":" + urn.getResourceName()).equals(newShipID)) { isARealShip = true; break; } } if(!isARealShip) { return Optional.empty(); } HullConfig newHullConfig = game.getHullConfigManager().getConfig(newShipID); SolShip newShip = game.getShipBuilder().build(game, originalShip.getPosition(), originalShip.getVelocity(), originalShip.getAngle(), originalShip.getRotationSpeed(), originalShip.getPilot(), originalShip.getItemContainer(), newHullConfig, newHullConfig.getMaxLife(), originalShip.getHull().getGun(false), originalShip.getHull().getGun(true), null, newHullConfig.getEngineConfig().exampleEngine.copy(), new ShipRepairer(), originalShip.getMoney(), null, originalShip.getShield(), originalShip.getArmor()); return Optional.of(newShip); }
Source:
public static void executeBuild() throws Exception { preparer = new InstallIntoLocalRepoAndCollectFromThereTest().getVerifier("p2Repository.localrepo.source", false); preparer.getSystemProperties().put("e352-repo", P2Repositories.ECLIPSE_352.toString()); preparer.executeGoal("install"); preparer.verifyErrorFreeLog(); verifier = new InstallIntoLocalRepoAndCollectFromThereTest().getVerifier("p2Repository.localrepo", false); verifier.executeGoal("verify"); verifier.verifyErrorFreeLog(); p2Repository = P2RepositoryTool.forEclipseRepositoryModule(new File(verifier.getBasedir())); }

Target:
public static void executeBuild() throws Exception { preparer = new InstallIntoLocalRepoAndCollectFromThereTest().getVerifier("p2Repository.localrepo.source", false); preparer.getSystemProperties().put("e352-repo", P2Repositories.ECLIPSE_352.toString()); preparer.executeGoal("install"); preparer.verifyErrorFreeLog(); verifier = new InstallIntoLocalRepoAndCollectFromThereTest().getVerifier("p2Repository.localrepo", false, false); verifier.getSystemProperties().put("e352-repo", P2Repositories.ECLIPSE_352.toString()); verifier.executeGoal("verify"); verifier.verifyErrorFreeLog(); p2Repository = P2RepositoryTool.forEclipseRepositoryModule(new File(verifier.getBasedir())); }
Source:
private void addResponseHeaders() { RequestContext context = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = context.getResponse(); List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders(); @SuppressWarnings("unchecked") List<String> rd = (List<String>) RequestContext.getCurrentContext() .get("routingDebug"); if (rd != null) { StringBuilder debugHeader = new StringBuilder(); for (String it : rd) { debugHeader.append("[[[" + it + "]]]"); } if (INCLUDE_DEBUG_HEADER.get()) { servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString()); } } if (zuulResponseHeaders != null) { for (Pair<String, String> it : zuulResponseHeaders) { servletResponse.addHeader(it.first(), it.second()); } } RequestContext ctx = RequestContext.getCurrentContext(); Long contentLength = ctx.getOriginContentLength(); if (SET_CONTENT_LENGTH.get()) { if ( contentLength != null && !ctx.getResponseGZipped()) { try { HttpServletResponse.class.getMethod("setContentLengthLong"); servletResponse.setContentLengthLong(contentLength); } catch (NoSuchMethodException e) { if(isLongSafe(contentLength)) { servletResponse.setContentLength(contentLength.intValue()); } } } } }

Target:
private void addResponseHeaders() { RequestContext context = RequestContext.getCurrentContext(); HttpServletResponse servletResponse = context.getResponse(); List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders(); @SuppressWarnings("unchecked") List<String> rd = (List<String>) RequestContext.getCurrentContext() .get("routingDebug"); if (rd != null) { StringBuilder debugHeader = new StringBuilder(); for (String it : rd) { debugHeader.append("[[[" + it + "]]]"); } if (INCLUDE_DEBUG_HEADER.get()) { servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString()); } } if (zuulResponseHeaders != null) { for (Pair<String, String> it : zuulResponseHeaders) { servletResponse.addHeader(it.first(), it.second()); } } RequestContext ctx = RequestContext.getCurrentContext(); Long contentLength = ctx.getOriginContentLength(); if (SET_CONTENT_LENGTH.get()) { if ( contentLength != null && !ctx.getResponseGZipped()) { if(useServlet31) { servletResponse.setContentLengthLong(contentLength); } else { if (isLongSafe(contentLength)) { servletResponse.setContentLength(contentLength.intValue()); } } } } }
Source:
public void writeAdditionalItemData(NBTTagCompound nbt) { nbt.setTag("spells", NBTExtras.listToNBT(getSpells(), spell -> new NBTTagString(spell.getRegistryName().toString()))); super.writeAdditionalItemData(nbt); }

Target:
public void writeAdditionalItemData(NBTTagCompound nbt) { nbt.setTag("spells", NBTHelper.getTagList(getSpells(), spell -> new NBTTagString(spell.getRegistryName().toString()))); super.writeAdditionalItemData(nbt); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StorageDomainStatic other = (StorageDomainStatic) obj; return (ObjectUtils.objectsEqual(id, other.id) && autoRecoverable == other.autoRecoverable && containsUnregisteredEntities == other.containsUnregisteredEntities && ObjectUtils.objectsEqual(connection, other.connection) && ObjectUtils.objectsEqual(name, other.name) && ObjectUtils.objectsEqual(storage, other.storage) && storageFormat == other.storageFormat && storagePoolType == other.storagePoolType && storageType == other.storageType && sanState != other.sanState && ObjectUtils.objectsEqual(description, other.description)); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StorageDomainStatic other = (StorageDomainStatic) obj; return (ObjectUtils.objectsEqual(id, other.id) && autoRecoverable == other.autoRecoverable && containsUnregisteredEntities == other.containsUnregisteredEntities && ObjectUtils.objectsEqual(connection, other.connection) && ObjectUtils.objectsEqual(name, other.name) && ObjectUtils.objectsEqual(storage, other.storage) && storageFormat == other.storageFormat && storagePoolType == other.storagePoolType && storageType == other.storageType && sanState == other.sanState && ObjectUtils.objectsEqual(description, other.description)); }
Source:
private void getRandomPage() { new RandomSummaryClient().request(WikipediaApp.getInstance().getWikiSite(), new RandomSummaryClient.Callback() { @Override public void onSuccess(@NonNull Call<RbPageSummary> call, @NonNull RbPageSummary pageSummary) { loadComplete = true; if (getActivity() != null) { parent().onChildLoaded(); } if (!isAdded()) { return; } setContents(pageSummary); } @Override public void onError(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) { if (!isAdded()) { return; } setErrorState(t); } }); }

Target:
private void getRandomPage() { new RandomSummaryClient().request(WikipediaApp.getInstance().getWikiSite(), new RandomSummaryClient.Callback() { @Override public void onSuccess(@NonNull Call<RbPageSummary> call, @NonNull RbPageSummary pageSummary) { loadComplete = true; if (!isAdded()) { return; } setContents(pageSummary); parent().onChildLoaded(); } @Override public void onError(@NonNull Call<RbPageSummary> call, @NonNull Throwable t) { if (!isAdded()) { return; } setErrorState(t); } }); }
Source:
public String getUrl() { return "<LINK_0>" + spreadsheetId + "/edit#gid=0"; }

Target:
public String getUrl() throws UnsupportedEncodingException { String urlString= "<LINK_0>" + spreadsheetId + "/edit#gid=0"; return URLEncoder.encode(urlString, "UTF-8"); }
Source:
public final void write(final int major, final OutputStream outputStream) throws IOException { if (major >= CramVersions.CRAM_v3.major) { final CRC32OutputStream crc32OutputStream = new CRC32OutputStream(outputStream); doWrite(crc32OutputStream); outputStream.write(crc32OutputStream.getCrc32_LittleEndian()); } else { doWrite(outputStream); } }

Target:
public final void write(final int major, final OutputStream outputStream) { try { if (major >= CramVersions.CRAM_v3.major) { final CRC32OutputStream crc32OutputStream = new CRC32OutputStream(outputStream); doWrite(crc32OutputStream); outputStream.write(crc32OutputStream.getCrc32_LittleEndian()); } else { doWrite(outputStream); } } catch (final IOException e) { throw new RuntimeIOException(e); } }
Source:
private <T> List<Page<SearchHit<T>>> doMultiSearch(List<? extends Query> queries, Class<T> clazz, MultiSearchRequest request) { MultiSearchResponse.Item[] items = getMultiSearchResult(request); List<Page<SearchHit<T>>> res = new ArrayList<>(queries.size()); int c = 0; for (Query query : queries) { res.add(elasticsearchConverter.mapResults(SearchDocumentResponse.from(items[c++].getResponse()), clazz, query.getPageable())); } return res; }

Target:
private <T> List<AggregatedPage<SearchHit<T>>> doMultiSearch(List<? extends Query> queries, Class<T> clazz, MultiSearchRequest request) { MultiSearchResponse.Item[] items = getMultiSearchResult(request); List<AggregatedPage<SearchHit<T>>> res = new ArrayList<>(queries.size()); int c = 0; for (Query query : queries) { res.add(elasticsearchConverter.mapResults(SearchDocumentResponse.from(items[c++].getResponse()), clazz, query.getPageable())); } return res; }
Source:
public FilterRegistrationBean flowIdRequestFilter() { return createFilterRegistrationBean(new FlowIdRequestFilter(), Ordered.HIGHEST_PRECEDENCE + 2); }

Target:
public FilterRegistrationBean flowIdRequestFilter() { return createFilterRegistrationBean(new FlowIdRequestFilter(), Ordered.HIGHEST_PRECEDENCE + 1); }
Source:
public boolean set(@Nullable V value) { return super.set(value); }

Target:
protected boolean set(@Nullable V value) { return super.set(value); }
Source:
public static List<List<ImapResponse>> createMultipleImapResponses(List<String>... responses) throws IOException { List<List<ImapResponse>> imapResponses = new ArrayList<>(); for (List<String> response : responses) { imapResponses.add(createImapResponse(response)); } return imapResponses; }

Target:
public static List<List<ImapResponse>> createMultipleImapResponses(List<String>... responses) throws IOException { List<List<ImapResponse>> imapResponses = new ArrayList<>(); for (List<String> response : responses) { imapResponses.add(createImapResponseList(response)); } return imapResponses; }
Source:
public void testTxTimeoutOnSuspend() throws Exception { executeTestForAllCaches(new CI2Exc<Ignite, IgniteCache<Integer, Integer>>() { @Override public void applyx(Ignite ignite, final IgniteCache<Integer, Integer> cache) throws Exception { for (TransactionIsolation isolation : TransactionIsolation.values()) { final Transaction tx = ignite.transactions().txStart(transactionConcurrency(), isolation, TX_TIMEOUT, 0); cache.put(1, 1); tx.suspend(); GridTestUtils.runAsync(() -> { tx.resume(); cache.put(1, 1); cache.put(2, 2); tx.suspend(); }).get(FUT_TIMEOUT); tx.resume(); cache.put(1, 1); cache.put(2, 2); cache.put(3, 3); U.sleep(TX_TIMEOUT + 100L); GridTestUtils.assertThrowsWithCause(new Callable<Object>() { @Override public Object call() throws Exception { tx.suspend(); return null; } }, TransactionTimeoutException.class); assertTrue(GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { return tx.state() == ROLLED_BACK; } }, getTestTimeout())); assertEquals(ROLLED_BACK, tx.state()); tx.close(); assertNull(cache.get(1)); assertNull(cache.get(2)); assertNull(cache.get(3)); } } }); }

Target:
public void testTxTimeoutOnSuspend() throws Exception { executeTestForAllCaches(new CI2Exc<Ignite, IgniteCache<Integer, Integer>>() { @Override public void applyx(Ignite ignite, final IgniteCache<Integer, Integer> cache) throws Exception { for (TransactionIsolation isolation : TransactionIsolation.values()) { final Transaction tx = initTxWithTimeout(ignite, cache, isolation, false); while (tx.startTime() + TX_TIMEOUT >= U.currentTimeMillis()) U.sleep(100L); GridTestUtils.assertThrowsWithCause(tx::suspend, TransactionTimeoutException.class); assertTrue(GridTestUtils.waitForCondition(() -> tx.state() == ROLLED_BACK, getTestTimeout())); assertEquals(ROLLED_BACK, tx.state()); tx.close(); assertNull(cache.get(1)); assertNull(cache.get(2)); assertNull(cache.get(3)); } } }); }