auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public WebResponse getResponse(final Ds3Request request) throws IOException, SignatureException { assertThat(request.getVerb(), is(this.verb)); assertThat(request.getPath(), is(this.path)); if (this.queryParams != null) { this.assertMapsEqual(this.queryParams, request.getQueryParams()); } if(this.requestHeaders != null){ assertThat(this.requestHeaders.size(), is(request.getHeaders().size())); assertTrue(Iterables.elementsEqual(this.requestHeaders.keySet(), request.getHeaders().keySet())); for (String key : this.requestHeaders.keySet()){ assertThat(this.requestHeaders.get(key), is(notNullValue())); assertThat(request.getHeaders().get(key), is(notNullValue())); assertTrue(Iterables.elementsEqual(this.requestHeaders.get(key), request.getHeaders().get(key))); } } if (this.requestContent != null) { final InputStream stream = request.getStream(); assertThat(stream, is(notNullValue())); assertThat(IOUtils.toString(stream), is(this.requestContent)); } return new MockedWebResponse(this.responseContent, this.statusCode, this.headers); }

Target:
public WebResponse getResponse(final Ds3Request request) throws IOException, SignatureException { assertThat(request.getVerb(), is(this.verb)); assertThat(request.getPath(), is(this.path)); if (this.queryParams != null) { this.assertMapsEqual(this.queryParams, request.getQueryParams()); } if(this.requestHeaders != null){ assertThat(this.requestHeaders.size(), is(request.getHeaders().size())); assertTrue(Iterables.elementsEqual(this.requestHeaders.keySet(), request.getHeaders().keySet())); for (final String key : this.requestHeaders.keySet()){ assertThat(this.requestHeaders.get(key), is(notNullValue())); assertThat(request.getHeaders().get(key), is(notNullValue())); assertTrue(Iterables.elementsEqual(this.requestHeaders.get(key), request.getHeaders().get(key))); } } if (this.requestContent != null) { final InputStream stream = request.getStream(); assertThat(stream, is(notNullValue())); assertThat(IOUtils.toString(stream), is(this.requestContent)); } return new MockedWebResponse(this.responseContent, this.statusCode, this.headers); }
Source:
public Object getPayload(CorfuRuntime runtime) { Object value = payload.get(); if (value == null) { synchronized (this.payload) { value = this.payload.get(); if (value == null) { if (data == null) { this.payload.set(null); } else { try { ByteBuf copyBuf = Unpooled.wrappedBuffer(data); final Object actualValue = Serializers.CORFU.deserialize(copyBuf, runtime); if (actualValue instanceof LogEntry) { ((LogEntry) actualValue).setGlobalAddress(getGlobalAddress()); ((LogEntry) actualValue).setRuntime(runtime); } value = actualValue == null ? this.payload : actualValue; this.payload.set(value); copyBuf.release(); lastKnownSize = data.length; data = null; } catch (Throwable throwable) { log.error("Exception caught at address {}, {}, {}", getGlobalAddress(), getStreams(), getType()); throw throwable; } } } } } return value; }

Target:
public Object getPayload(CorfuRuntime runtime) { Object value = payload.get(); if (value == null) { synchronized (this.payload) { value = this.payload.get(); if (value == null) { if (data == null) { this.payload.set(null); } else { ByteBuf copyBuf = Unpooled.wrappedBuffer(data); final Object actualValue; try { actualValue = Serializers.CORFU.deserialize(copyBuf, runtime); } catch (Throwable throwable) { log.error("Exception caught at address {}, {}, {}", getGlobalAddress(), getStreams(), getType()); copyBuf.release(); data = null; throw throwable; } if (actualValue instanceof LogEntry) { ((LogEntry) actualValue).setGlobalAddress(getGlobalAddress()); ((LogEntry) actualValue).setRuntime(runtime); } value = actualValue == null ? this.payload : actualValue; this.payload.set(value); copyBuf.release(); lastKnownSize = data.length; data = null; } } } } return value; }
Source:
public void addMetric(final IMetric<?> metric) { if (metric != null && getMetricFromName(metric.getName()) == null) { _logger.debug(String.format("Adding %s metric in Metric Manager", metric.getName())); _metrics.add(metric); metric.updateMetricManager(this); } else { _logger.error("Failed to add metric"); } }

Target:
public void addMetric(final IMetric<?> metric) { if(metric == null) throw new IllegalArgumentException("Cannot add a null metric"); if (getMetricFromName(metric.getName()) == null) { logger.debug(String.format("Adding %s metric in Metric Manager", metric.getName())); metrics.add(metric); metric.updateMetricManager(this); } else { logger.error("Failed to add metric"); } }
Source:
public void testHandle() throws Exception { Callback[] callbackList = new Callback[1]; SAMLCallback samlCallback = new SAMLCallback(); callbackList[0] = samlCallback; final Message message = mock(Message.class); AssertionType assertionType = mock(AssertionType.class); HOKSAMLAssertionBuilder builder = mock(HOKSAMLAssertionBuilder.class); PropertyAccessor accessor = mock(PropertyAccessor.class); CXFSAMLCallbackHandler callbackHandler = new CXFSAMLCallbackHandler(builder) { @Override protected Message getCurrentMessage() { return message; } }; when(message.get("assertion")).thenReturn(assertionType); when(message.get(Message.INBOUND_MESSAGE)).thenReturn(false); when(message.get(NhincConstants.WS_SOAP_TARGET_HOME_COMMUNITY_ID)).thenReturn("1.1"); when(message.get(NhincConstants.TARGET_API_LEVEL)).thenReturn("G0"); when(message.get(NhincConstants.ACTION_PROP)).thenReturn("Soap Action"); when(builder.build(any(CallbackProperties.class))).thenReturn(assertionElement); callbackHandler.handle(callbackList); assertEquals(samlCallback.getSamlVersion(), org.opensaml.saml.common.SAMLVersion.VERSION_20); assertEquals(samlCallback.getAssertionElement().getTextContent(), ASSERTION); }

Target:
public void testHandle() throws Exception { Callback[] callbackList = new Callback[1]; SAMLCallback samlCallback = new SAMLCallback(); callbackList[0] = samlCallback; final Message message = mock(Message.class); AssertionType assertionType = mock(AssertionType.class); HOKSAMLAssertionBuilder builder = mock(HOKSAMLAssertionBuilder.class); CXFSAMLCallbackHandler callbackHandler = new CXFSAMLCallbackHandler(builder) { @Override protected Message getCurrentMessage() { return message; } }; when(message.get("assertion")).thenReturn(assertionType); when(message.get(Message.INBOUND_MESSAGE)).thenReturn(false); when(message.get(NhincConstants.WS_SOAP_TARGET_HOME_COMMUNITY_ID)).thenReturn("1.1"); when(message.get(NhincConstants.TARGET_API_LEVEL)).thenReturn("G0"); when(message.get(NhincConstants.ACTION_PROP)).thenReturn("Soap Action"); when(builder.build(any(CallbackProperties.class))).thenReturn(assertionElement); callbackHandler.handle(callbackList); assertEquals(samlCallback.getSamlVersion(), org.opensaml.saml.common.SAMLVersion.VERSION_20); assertEquals(samlCallback.getAssertionElement().getTextContent(), ASSERTION); }
Source:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); return isBaseMetric(metricField, cls) ? new EntityMetric( metricField, metaData == null || metaData.longName().isEmpty() ? metricField : metaData.longName(), metaData == null || metaData.description().isEmpty() ? metricField : metaData.description(), fieldType, extractDefaultAggregation(metricField, cls), extractNonDefaultAggregations(metricField, cls) ) : new EntityMetric( metricField, metaData == null || metaData.longName().isEmpty() ? metricField : metaData.longName(), metaData == null || metaData.description().isEmpty() ? metricField : metaData.description(), fieldType, extractDefaultAggregation(metricField, cls), extractNonDefaultAggregations(metricField, cls), getExpandedMetricExpression(metricField, cls, new HashSet<>()) ); }

Target:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = Arrays.stream( entityDictionary.getAttributeOrRelationAnnotation( cls, MetricAggregation.class, metricField ).aggregations() ) .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); return new AggregatedMetric( metricField, metaData, fieldType, aggregations ); }
Source:
public void testDaemonShouldWaitForBuildSuccess() throws TimeoutException, InterruptedException { DaemonBuild daemonBuild = EmbeddedMaven .forProject(pathToJarSamplePom) .setGoals("package") .useAsDaemon() .withWaitUntilOutputLineMathes(".*BUILD SUCCESS.*") .build(); int timeout = 0; while (daemonBuild.isAlive() && timeout <= 20) { Thread.sleep(500); } Assertions.assertThat(timeout) .as("The build should have finish (not to be alive) within 10 seconds") .isLessThanOrEqualTo(10); Assertions.assertThat(daemonBuild.getBuiltProject()).isNotNull(); verifyJarSampleSimpleBuild(daemonBuild.getBuiltProject()); verifyJarSampleContainsOnlyOneJar(daemonBuild.getBuiltProject()); }

Target:
public void testDaemonShouldWaitForBuildSuccess() throws TimeoutException, InterruptedException { final DaemonBuild daemonBuild = EmbeddedMaven .forProject(pathToJarSamplePom) .setGoals("package") .useAsDaemon() .withWaitUntilOutputLineMathes(".*BUILD SUCCESS.*") .build(); Awaitility.await("Wait till thread is not be alive").atMost(20, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !daemonBuild.isAlive(); } }); Assertions.assertThat(daemonBuild.getBuiltProject()).isNotNull(); verifyJarSampleSimpleBuild(daemonBuild.getBuiltProject()); verifyJarSampleContainsOnlyOneJar(daemonBuild.getBuiltProject()); }
Source:
public HttpClient build(String name) { final BasicHttpParams params = createHttpParams(name); final InstrumentedClientConnManager manager = createConnectionManager(registry, name); final InstrumentedHttpClient client = new InstrumentedHttpClient(metricRegistry, manager, params, name); client.setCredentialsProvider(credentialsProvider); setStrategiesForClient(client); return client; }

Target:
public HttpClient build(String name) { final BasicHttpParams params = createHttpParams(name); final InstrumentedClientConnManager manager = createConnectionManager(registry, name); final InstrumentedHttpClient client = new InstrumentedHttpClient(metricRegistry, manager, params, name); setStrategiesForClient(client); return client; }
Source:
public void cluster_state_dump() throws Exception { put(0, "pets", "pet1", "Cubitus"); Properties properties = new Properties(); properties.setProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, "5000"); properties.setProperty(ConnectionPropertyNames.CONNECTION_NAME, "diagnostic"); properties.setProperty(PROP_REQUEST_TIMEOUT, "5000"); properties.setProperty(PROP_REQUEST_TIMEOUTMESSAGE, "5000"); URI uri = URI.create("diagnostic://" + voltron.getConnectionURI().getAuthority()); try (Connection connection = ConnectionFactory.connect(uri, properties)) { EntityRef<Diagnostics, Object, Void> ref = connection.getEntityRef(Diagnostics.class, 1, "root"); Diagnostics diagnostics = ref.fetchEntity(null); String dump = diagnostics.getClusterState(); try (Stream<String> lines = Files.lines(Paths.get(getClass().getResource("/sate-dump-partial.txt").toURI()))) { lines.forEach(line -> { assertThat(dump, dump, containsString(line)); }); } } }

Target:
public void cluster_state_dump() throws Exception { put(0, "pets", "pet1", "Cubitus"); Properties properties = new Properties(); properties.setProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, "5000"); properties.setProperty(ConnectionPropertyNames.CONNECTION_NAME, "diagnostic"); properties.setProperty(PROP_REQUEST_TIMEOUT, "5000"); properties.setProperty(PROP_REQUEST_TIMEOUTMESSAGE, "5000"); URI uri = URI.create("diagnostic://" + voltron.getConnectionURI().getAuthority()); try (Connection connection = ConnectionFactory.connect(uri, properties)) { EntityRef<Diagnostics, Object, Void> ref = connection.getEntityRef(Diagnostics.class, 1, "root"); Diagnostics diagnostics = ref.fetchEntity(null); String dump = diagnostics.getClusterState(); System.out.println(dump); try (Stream<String> lines = Files.lines(Paths.get(getClass().getResource("/sate-dump-partial.txt").toURI()))) { lines.forEach(line -> { assertThat(dump, dump, containsString(line)); }); } } }
Source:
private synchronized Subject getSubject(String ipAddress) { Subject subject = cachedGuestSubjectMap.get(ipAddress); if (subject == null) { GuestAuthenticationToken token = new GuestAuthenticationToken(ipAddress); LOGGER.debug("Getting new Guest user token for {}", ipAddress); try { subject = securityManager.getSubject(token); cachedGuestSubjectMap.put(ipAddress, subject); } catch (SecurityServiceException sse) { LOGGER.info("Unable to request subject for guest user.", sse); } } else { LOGGER.debug("Using cached Guest user token for {}", ipAddress); } return subject; }

Target:
private synchronized Subject getSubject(String ipAddress) { Subject subject = guestSubjectCache.getIfPresent(ipAddress); if (subject == null) { GuestAuthenticationToken token = new GuestAuthenticationToken(ipAddress); LOGGER.debug("Getting new Guest user token for {}", ipAddress); try { subject = securityManager.getSubject(token); guestSubjectCache.put(ipAddress, subject); } catch (SecurityServiceException sse) { LOGGER.info("Unable to request subject for guest user.", sse); } } else { LOGGER.debug("Using cached Guest user token for {}", ipAddress); } return subject; }
Source:
public void failure(RetrofitError retrofitError) { if (isCancelled || getContext() == null) { return; } finishLoading(); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getUrl()); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getMessage()); if (onFailure(retrofitError)) { return; } if (errorDelegate == null) { Log.d(APIHelpers.LOG_TAG, "WARNING: No ErrorDelegate Provided "); return; } CanvasError canvasError; switch (retrofitError.getKind()) { case CONVERSION: canvasError = CanvasError.createError("Conversion Error", "An exception was thrown while (de)serializing a body"); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; case HTTP: handleHTTPError(retrofitError); break; case NETWORK: statusDelegate.onNoNetwork(); errorDelegate.noNetworkError(retrofitError, getContext()); break; case UNEXPECTED: canvasError = CanvasError.createError("Unexpected Error", "An internal error occurred while attempting to execute a request."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; } }

Target:
public void failure(RetrofitError retrofitError) { if (isCancelled || getContext() == null) { return; } finishLoading(); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getUrl()); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getMessage()); if (onFailure(retrofitError)) { return; } if (errorDelegate == null) { Log.d(APIHelpers.LOG_TAG, "WARNING: No ErrorDelegate Provided "); return; } CanvasError canvasError; switch (retrofitError.getKind()) { case CONVERSION: canvasError = CanvasError.createError("Conversion Error", "An exception was thrown while (de)serializing a body"); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; case HTTP: handleHTTPError(retrofitError); break; case NETWORK: statusDelegate.onNoNetwork(); errorDelegate.noNetworkError(retrofitError, getContext()); break; case UNEXPECTED: canvasError = CanvasError.createError("Unexpected Error", "An internal error occurred while attempting to execute a request."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; default: canvasError = CanvasError.createError("Unexpected Error", "An unexpected error occurred."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; } }
Source:
private ExtensionsManager() { for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { loadDirectory(directory); } }

Target:
private ExtensionsManager() { for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { load(file); } } } } } }
Source:
public void testUpgradingv1Tov2() throws IOException { final ClassLoader classLoader = this.getClass().getClassLoader(); try (final InputStream v1InputStream = classLoader.getResource("loadv1.schematic").openStream(); final InputStream v2InputStream = classLoader.getResource("loadv2.schematic").openStream()) { final DataContainer v1Container = DataFormats.NBT.readFrom(new GZIPInputStream(v1InputStream)); final Schematic v1Schem = DataTranslators.SCHEMATIC.translate(v1Container); final DataContainer v2Container = DataFormats.NBT.readFrom(new GZIPInputStream(v2InputStream)); final Schematic v2Schem = DataTranslators.SCHEMATIC.translate(v2Container); assertEquals(v1Schem, v2Schem); } }

Target:
public void testUpgradingv1Tov2() throws IOException { final ClassLoader classLoader = this.getClass().getClassLoader(); try (final InputStream v1InputStream = classLoader.getResource("loadv1.schematic").openStream(); final InputStream v2InputStream = classLoader.getResource("loadv2.schematic").openStream(); final GZIPInputStream v1GzipInputStream = new GZIPInputStream(v1InputStream); final GZIPInputStream v2GzipInputStream = new GZIPInputStream(v2InputStream)){ final DataContainer v1Container = DataFormats.NBT.readFrom(v1GzipInputStream); final Schematic v1Schem = DataTranslators.SCHEMATIC.translate(v1Container); final DataContainer v2Container = DataFormats.NBT.readFrom(v2GzipInputStream); final Schematic v2Schem = DataTranslators.SCHEMATIC.translate(v2Container); assertEquals(v1Schem, v2Schem); } }
Source:
public void insertToRealm_CyclicType() { CyclicType oneCyclicType = new CyclicType(); oneCyclicType.setName("One"); CyclicType anotherCyclicType = new CyclicType(); anotherCyclicType.setName("Two"); oneCyclicType.setObject(anotherCyclicType); anotherCyclicType.setObject(oneCyclicType); realm.beginTransaction(); realm.insert(oneCyclicType); realm.commitTransaction(); CyclicType realmObject = realm.where(CyclicType.class).findFirst(); assertEquals("One", realmObject.getName()); assertEquals("Two", realmObject.getObject().getName()); assertEquals(2, realm.where(CyclicType.class).count()); }

Target:
public void insertToRealm_CyclicType() { CyclicType oneCyclicType = new CyclicType(); oneCyclicType.setName("One"); CyclicType anotherCyclicType = new CyclicType(); anotherCyclicType.setName("Two"); oneCyclicType.setObject(anotherCyclicType); anotherCyclicType.setObject(oneCyclicType); realm.beginTransaction(); realm.insert(Arrays.asList(oneCyclicType, anotherCyclicType)); realm.commitTransaction(); RealmResults<CyclicType> realmObjects = realm.where(CyclicType.class).findAllSorted(CyclicType.FIELD_NAME); assertNotNull(realmObjects); assertEquals(2, realmObjects.size()); assertEquals("One", realmObjects.get(0).getName()); assertEquals("Two", realmObjects.get(0).getObject().getName()); }
Source:
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) { String v = diagnostics.getDiagnostics().get(0).getMessage(); this.observer.notify(v); if(v.equals("VALID")) { System.out.println("String is VALID"); } else if (v.equals("INVALID")) { System.out.println("String is INVALID"); } }

Target:
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) { observer.diagnostic(diagnostics.getDiagnostics()); Runnable completionTask = () -> { CompletionParams completionParams = new CompletionParams(); Position position = new Position(); position.setLine(0); position.setCharacter(cursor); completionParams.setPosition(position); try { Either<List<CompletionItem>, CompletionList> completion = serverProxy.getTextDocumentService().completion(completionParams).get(); observer.completion(completion); } catch (Exception e) { e.printStackTrace(); } }; Runnable syntaxHighlightingTask = () -> { DocumentColorParams colorParams = new DocumentColorParams(); try { List<ColorInformation> colors = serverProxy.getTextDocumentService().documentColor(colorParams).get(); } catch (Exception e) { e.printStackTrace(); } }; threadPoolExecutor.execute(syntaxHighlightingTask); }
Source:
public void normalClearFromDataStore() { accessor.invoke(() -> feed(false)); dataStore1.invoke(() -> verifyRegionSize(false, NUM_ENTRIES)); dataStore2.invoke(() -> verifyRegionSize(false, NUM_ENTRIES)); dataStore3.invoke(() -> verifyRegionSize(false, NUM_ENTRIES)); dataStore1.invoke(() -> getRegion(false).clear()); dataStore1.invoke(() -> verifyRegionSize(false, 0)); dataStore2.invoke(() -> verifyRegionSize(false, 0)); dataStore3.invoke(() -> verifyRegionSize(false, 0)); }

Target:
public void normalClearFromDataStore() { accessor.invoke(() -> feed(false)); verifyServerRegionSize(NUM_ENTRIES); dataStore1.invoke(() -> getRegion(false).clear()); verifyServerRegionSize(0); verifyCacheListenerTriggerCount(dataStore1); }
Source:
public void initializeZipkinKafkaCollector() { if (zookeeper == null) { return; } if (spanPublisher == null) { throw new IllegalStateException("Span publisher is null!"); } log.infof("Initializing Zipkin kafka collector"); KafkaCollector kafkaCollector = KafkaCollector.builder() .zookeeper(this.zookeeper) .storage(new JMSZipkinStorage(spanPublisher)) .build(); kafkaCollector.start(); }

Target:
public void initializeZipkinKafkaCollector() { if (PropertyUtil.getKafkaZookeeper() == null) { return; } if (spanPublisher == null) { throw new IllegalStateException("Span publisher is null!"); } log.infof("Initializing Zipkin kafka collector"); KafkaCollector kafkaCollector = KafkaCollector.builder() .zookeeper(PropertyUtil.getKafkaZookeeper()) .storage(new APMZipkinSpanStorage(spanPublisher)) .build(); kafkaCollector.start(); }
Source:
public Document decodeFromStream(final DataInputStream dais) { try { final int size = dais.readInt(); final int[] words = new int[size]; for (int i = 0; i < size; i++) { final int word = dais.readInt(); words[i] = word; } return new Document(words, numTopics); } catch (final IOException e) { throw new RuntimeException(e); } }

Target:
public Document decodeFromStream(final DataInputStream dais) { try { final int numWords = dais.readInt(); final int[] words = new int[numWords]; final int[] assignments = new int[numWords]; final int[] topicCounts = new int[numTopics]; for (int wordIdx = 0; wordIdx < numWords; wordIdx++) { words[wordIdx] = dais.readInt(); } for (int wordIdx = 0; wordIdx < numWords; wordIdx++) { assignments[wordIdx] = dais.readInt(); } for (int topicIdx = 0; topicIdx < numTopics; topicIdx++) { topicCounts[topicIdx] = dais.readInt(); } return new Document(words, assignments, topicCounts, numTopics); } catch (final IOException e) { throw new RuntimeException(e); } }
Source:
public Iterable<String> getKeysToRemove() { return KEYS_TO_REMOVE; }

Target:
protected Iterable<String> getKeysToRemove() { return KEYS_TO_REMOVE; }
Source:
protected boolean repeatUntil(RepeatCompletion repeat) { repeatTime = 0; repeatTimer.start(); StopWatch loopTimer = new StopWatch(); loopTimer.start(); boolean result = false; try { try { result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking we can stop repeating before starting loop", e); } for (repeatCount = 0; !result && repeatCount < repeatMaxCount; repeatCount++) { int nextInterval = getNextInterval(loopTimer); waitMilliseconds(nextInterval); loopTimer.start(); try { repeat.repeat(); result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking whether we can stop repeating, loop count of {}", repeatCount, repeatMaxCount, e); } } } finally { repeatTime = repeatTimer.getTime(); repeatTimer.reset(); } return result; }

Target:
protected boolean repeatUntil(RepeatCompletion repeat) { repeatTime = 0; repeatTimer.start(); StopWatch loopTimer = new StopWatch(); loopTimer.start(); boolean result = false; try { try { result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking we can stop repeating before starting loop", e); } for (repeatCount = 0; !result && repeatCount < repeatMaxCount; repeatCount++) { int nextInterval = getNextInterval(loopTimer); waitMilliseconds(nextInterval); loopTimer.start(); repeat.repeat(); try { result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking whether we can stop repeating, loop count of {}", repeatCount, repeatMaxCount, e); } } } finally { repeatTime = repeatTimer.getTime(); repeatTimer.reset(); } return result; }
Source:
public void unregisterModuleMusic() { Json musicJson = Assets.getJson(currentlyRegisteredModule + ":musicConfig"); MusicConfig musicConfig = MusicConfig.load(currentlyRegisteredModule, musicJson.getJsonValue()); Map<String, List<String>> musicMap = musicConfig.getMusicMap(); int gameMusicSize = musicMap.get(GAME_MUSIC_SET).size(); int menuMusicSize = musicMap.get(MENU_MUSIC_SET).size(); for (int i = 1; i <= gameMusicSize; i++) { this.musicMap.get(GAME_MUSIC_SET).remove(this.musicMap.get(GAME_MUSIC_SET).size() - 1); } }

Target:
public void unregisterModuleMusic() { musicMap.get(GAME_MUSIC_SET).clear(); registerMusic(GAME_MUSIC_SET, "engine:cimmerianDawn"); registerMusic(GAME_MUSIC_SET, "engine:intoTheDark"); registerMusic(GAME_MUSIC_SET, "engine:spaceTheatre"); }
Source:
private Configuration createRemoteCacheManagerConfiguration(int... hotrodPortOverrides) { ConfigurationBuilder config = new ConfigurationBuilder(); if (hotrodPortOverrides.length != 0 && getServers().size() != hotrodPortOverrides.length) { throw new IllegalArgumentException("The number of defined ports is different from server count"); } int index = 0; for (RemoteInfinispanServer server : getServers()) { int port = hotrodPortOverrides.length != 0 ? hotrodPortOverrides[index] : server.getHotrodEndpoint().getPort(); config.addServer() .host(server.getHotrodEndpoint().getInetAddress().getHostName()) .port(port); ++index; } config.balancingStrategy("org.infinispan.server.test.client.hotrod.HotRodTestRequestBalancingStrategy") .balancingStrategy("org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy") .forceReturnValues(false) .tcpNoDelay(true) .pingOnStartup(true) .transportFactory("org.infinispan.client.hotrod.impl.transport.tcp.TcpTransportFactory") .marshaller("org.infinispan.commons.marshall.jboss.GenericJBossMarshaller") .asyncExecutorFactory().factoryClass("org.infinispan.client.hotrod.impl.async.DefaultAsyncExecutorFactory") .addExecutorProperty("infinispan.client.hotrod.default_executor_factory.pool_size", "10") .addExecutorProperty("infinispan.client.hotrod.default_executor_factory.queue_size", "100000") .keySizeEstimate(64) .valueSizeEstimate(512); if (isDistributedMode()) { config.consistentHashImpl(1, "org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV1"); } else { config.consistentHashImpl(2, "org.infinispan.client.hotrod.impl.consistenthash.ConsistentHashV2"); } return config.build(); }

Target:
private Configuration createRemoteCacheManagerConfiguration(int... hotrodPortOverrides) { if (hotrodPortOverrides.length != 0) { assert getServers().size() == hotrodPortOverrides.length : "The number of defined ports is different from server count"; } ConfigurationBuilder config = new ConfigurationBuilder(); int index = 0; for (RemoteInfinispanServer server : getServers()) { int port = hotrodPortOverrides.length != 0 ? hotrodPortOverrides[index] : server.getHotrodEndpoint().getPort(); config.addServer() .host(server.getHotrodEndpoint().getInetAddress().getHostName()) .port(port); ++index; } config.balancingStrategy("org.infinispan.server.test.client.hotrod.HotRodTestRequestBalancingStrategy") .balancingStrategy("org.infinispan.client.hotrod.impl.transport.tcp.RoundRobinBalancingStrategy") .forceReturnValues(false) .tcpNoDelay(true) .transportFactory("org.infinispan.client.hotrod.impl.transport.tcp.TcpTransportFactory") .marshaller(new GenericJBossMarshaller(Thread.currentThread().getContextClassLoader())) .asyncExecutorFactory().factoryClass("org.infinispan.client.hotrod.impl.async.DefaultAsyncExecutorFactory") .addExecutorProperty("infinispan.client.hotrod.default_executor_factory.pool_size", "10") .addExecutorProperty("infinispan.client.hotrod.default_executor_factory.queue_size", "100000") .keySizeEstimate(64) .valueSizeEstimate(512); return config.build(); }
Source:
private static String getPrefix() { StackTraceElement[] elems = Thread.currentThread().getStackTrace(); StackTraceElement elem = elems[BASE_DEPTH]; if (elem.getClassName().startsWith("kotlin.io.")) { elem = elems[BASE_DEPTH + 2]; } else if (elem.getClassName().startsWith("java.lang.Throwable")) { elem = elems[BASE_DEPTH + 4]; } return "[" + elem.getClassName() + ":" + elem.getMethodName() + ":" + elem.getLineNumber() + "]: "; }

Target:
private static String getPrefix() { StackTraceElement[] elems = Thread.currentThread().getStackTrace(); StackTraceElement elem = elems[Math.min(BASE_DEPTH, elems.length - 1)]; if (elem.getClassName().startsWith("kotlin.io.")) { elem = elems[Math.min(BASE_DEPTH + 2, elems.length - 1)]; } else if (elem.getClassName().startsWith("java.lang.Throwable")) { elem = elems[Math.min(BASE_DEPTH + 4, elems.length - 1)]; } return "[" + elem.getClassName() + ":" + elem.getMethodName() + ":" + elem.getLineNumber() + "]: "; }
Source:
public void testQueryType() throws IllegalArgumentException, IllegalAccessException { assertNotSame(VdcQueryType.Unknown, TestHelperQueriesCommandType.getQueryTypeFieldValue(query)); }

Target:
public void testQueryType() throws IllegalArgumentException, IllegalAccessException { assertNotSame("The query can't be found in the enum VdcQueryType", VdcQueryType.Unknown, TestHelperQueriesCommandType.getQueryTypeFieldValue(query)); }
Source:
public static ThirdPartyContext multitenant(String name) { checkNotNull(name); return newContext(name, true); }

Target:
public static ThirdPartyContext multitenant(String name) { return newContext(name, true); }
Source:
public void testMaxspeed() { ReaderWay osmWay = new ReaderWay(0); osmWay.setTag("highway", "primary"); osmWay.setTag("maxspeed", "10"); long flags = encoder.handleWayTags(osmWay, 1, 0); EdgeIteratorState edge = GHUtility.createMockedEdgeIteratorState(0, flags); assertEquals(10, encoder.getMaxspeed(edge, motorVehicleInt, false), .1); assertEquals(10, encoder.getMaxspeed(edge, motorVehicleInt, true), .1); osmWay = new ReaderWay(0); osmWay.setTag("highway", "primary"); osmWay.setTag("maxspeed:forward", "10"); flags = encoder.handleWayTags(osmWay, 1, 0); edge = GHUtility.createMockedEdgeIteratorState(0, flags); assertEquals(10, encoder.getMaxspeed(edge, motorVehicleInt, false), .1); assertEquals(-1, encoder.getMaxspeed(edge, motorVehicleInt, true), .1); }

Target:
public void testMaxspeed() { ReaderWay osmWay = new ReaderWay(0); osmWay.setTag("highway", "primary"); osmWay.setTag("maxspeed", "10"); long flags = encoder.handleWayTags(osmWay, 1, 0); EdgeIteratorState edge = GHUtility.createMockedEdgeIteratorState(0, flags); assertEquals(10, encoder.getMaxspeed(edge, motorVehicleInt, false), .1); assertEquals(10, encoder.getMaxspeed(edge, motorVehicleInt, true), .1); osmWay = new ReaderWay(0); osmWay.setTag("highway", "primary"); osmWay.setTag("maxspeed:forward", "10"); flags = encoder.handleWayTags(osmWay, 1, 0); edge = GHUtility.createMockedEdgeIteratorState(0, flags); assertEquals(10, encoder.getMaxspeed(edge, motorVehicleInt, false), .1); assertEquals(-1, encoder.getMaxspeed(edge, motorVehicleInt, true), .1); osmWay = new ReaderWay(0); osmWay.setTag("highway", "primary"); osmWay.setTag("maxspeed:forward", "50"); osmWay.setTag("maxspeed:backward", "50"); osmWay.setTag("maxspeed", "60"); flags = encoder.handleWayTags(osmWay, 1, 0); edge = GHUtility.createMockedEdgeIteratorState(0, flags); assertEquals(50, encoder.getMaxspeed(edge, motorVehicleInt, false), .1); assertEquals(50, encoder.getMaxspeed(edge, motorVehicleInt, true), .1); }
Source:
public static FailureItem of(FailureReason reason, String message, Map<String, String> attributes) { ArgChecker.notNull(reason, "reason"); ArgChecker.notEmpty(message, "message"); String stackTrace = localGetStackTraceAsString(message, 1); return new FailureItem(reason, message, attributes, stackTrace, null); }

Target:
private static FailureItem of(FailureReason reason, String message, Map<String, String> attributes) { ArgChecker.notNull(reason, "reason"); ArgChecker.notEmpty(message, "message"); String stackTrace = localGetStackTraceAsString(message, 1); return new FailureItem(reason, message, attributes, stackTrace, null); }
Source:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); try { assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); } catch (NullPointerException e) { e.printStackTrace(); throw e; } }

Target:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); }
Source:
@Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( !( o instanceof HazelcastConfiguration ) ) { return false; } HazelcastConfiguration that = (HazelcastConfiguration) o; return replicationFactor == that.replicationFactor && port == that.port && server == that.server && Objects.equals( hazelcastSeedNodes, that.hazelcastSeedNodes ) && Objects.equals( instanceName, that.instanceName ) && Objects.equals( group, that.group ) && Objects.equals( password, that.password ) && Objects.equals( scheduledExecutors, that.scheduledExecutors ); }

Target:
@Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( !( o instanceof HazelcastConfiguration ) ) { return false; } HazelcastConfiguration that = (HazelcastConfiguration) o; return replicationFactor == that.replicationFactor && port == that.port && server == that.server && Objects.equals( hazelcastSeedNodes, that.hazelcastSeedNodes ) && Objects.equals( instanceName, that.instanceName ) && Objects.equals( group, that.group ) && Objects.equals( password, that.password ) && Objects.equals( scheduledExecutors, that.scheduledExecutors ) && Objects.equals( cpMemberCount, that.cpMemberCount ) && Objects.equals( durableExecutors, that.durableExecutors ); }
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); jobProperties.put(GlusterConstants.VOLUME, getParameters().getVolume().getName()); } return jobProperties; }

Target:
public Map<String, String> getJobMessageProperties() { if (volume != null) { if (jobProperties == null) { jobProperties = super.getJobMessageProperties(); } jobProperties.put(GlusterConstants.VOLUME, volume.getName()); } return jobProperties; }
Source:
public void putEvent(JsonRpcEvent event) { try (LockWrapper wrapper = new LockWrapper(this.lock)) { event.setCreationTime(LocalTime.now().minusMinutes(1)); this.events.addFirst(event); purgeOldEventsIfNotConsumed(); } }

Target:
public void putEvent(JsonRpcEvent event) { try (LockWrapper wrapper = new LockWrapper(this.lock)) { event.setCreationTime(System.nanoTime()); this.events.addFirst(event); } }
Source:
private PendingIntent createPendingIntent(@PlaybackStateCompat.Actions long action) { int keyCode = PlaybackStateCompat.toKeyCode(action); Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(new ComponentName( mServiceInstance.getPackageName(), mServiceInstance.getClass().getCanonicalName())); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && keyCode == KEYCODE_MEDIA_PLAY) { return PendingIntent.getForegroundService( mServiceInstance, keyCode , intent, 0 ); } else { return PendingIntent.getService( mServiceInstance, keyCode , intent, 0 ); } }

Target:
private PendingIntent createPendingIntent(@PlaybackStateCompat.Actions long action) { int keyCode = PlaybackStateCompat.toKeyCode(action); Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(new ComponentName(mServiceInstance, mServiceInstance.getClass())); intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && action != ACTION_PAUSE) { return PendingIntent.getForegroundService( mServiceInstance, keyCode , intent, 0 ); } else { return PendingIntent.getService( mServiceInstance, keyCode , intent, 0 ); } }
Source:
private boolean parseUrl( JsonQueryProcessorState state, CharSequence keepAliveHeader ) throws PeerDisconnectedException, PeerIsSlowToReadException { final HttpRequestHeader header = state.getHttpConnectionContext().getRequestHeader(); final DirectByteCharSequence query = header.getUrlParam("query"); if (query == null || query.length() == 0) { state.info().$("Empty query header received. Sending empty reply.").$(); sendException(state.getHttpConnectionContext().getChunkedResponseSocket(), 0, "No query text", 400, query, keepAliveHeader); return false; } long skip = 0; long stop = Long.MAX_VALUE; CharSequence limit = header.getUrlParam("limit"); if (limit != null) { int sepPos = Chars.indexOf(limit, ','); try { if (sepPos > 0) { skip = Numbers.parseLong(limit, 0, sepPos) - 1; if (sepPos + 1 < limit.length()) { stop = Numbers.parseLong(limit, sepPos + 1, limit.length()); } } else { stop = Numbers.parseLong(limit); } } catch (NumericException ex) { } } if (stop < 0) { stop = 0; } if (skip < 0) { skip = 0; } if (configuration.getMaxQueryResponseRowLimit() != Long.MAX_VALUE && (stop - skip) > configuration.getMaxQueryResponseRowLimit()) { stop = skip + configuration.getMaxQueryResponseRowLimit(); } try { state.configure(header, query, skip, stop); } catch (Utf8Exception e) { state.info().$("Bad UTF8 encoding").$(); sendException(state.getHttpConnectionContext().getChunkedResponseSocket(), 0, "Bad UTF8 encoding in query text", 400, query, keepAliveHeader); return false; } return true; }

Target:
private boolean parseUrl( JsonQueryProcessorState state, CharSequence keepAliveHeader ) throws PeerDisconnectedException, PeerIsSlowToReadException { final HttpRequestHeader header = state.getHttpConnectionContext().getRequestHeader(); final DirectByteCharSequence query = header.getUrlParam("query"); if (query == null || query.length() == 0) { state.info().$("Empty query header received. Sending empty reply.").$(); sendException(state.getHttpConnectionContext().getChunkedResponseSocket(), 0, "No query text", 400, query, keepAliveHeader); return false; } long skip = 0; long stop = Long.MAX_VALUE; CharSequence limit = header.getUrlParam("limit"); if (limit != null) { int sepPos = Chars.indexOf(limit, ','); try { if (sepPos > 0) { skip = Numbers.parseLong(limit, 0, sepPos) - 1; if (sepPos + 1 < limit.length()) { stop = Numbers.parseLong(limit, sepPos + 1, limit.length()); } } else { stop = Numbers.parseLong(limit); } } catch (NumericException ex) { } } if (stop < 0) { stop = 0; } if (skip < 0) { skip = 0; } if ((stop - skip) > configuration.getMaxQueryResponseRowLimit()) { stop = skip + configuration.getMaxQueryResponseRowLimit(); } try { state.configure(header, query, skip, stop); } catch (Utf8Exception e) { state.info().$("Bad UTF8 encoding").$(); sendException(state.getHttpConnectionContext().getChunkedResponseSocket(), 0, "Bad UTF8 encoding in query text", 400, query, keepAliveHeader); return false; } return true; }
Source:
public void freeze() throws IOException { recordManager.close(); recordManager = null; }

Target:
public void freeze() throws IOException { logger.info("Closing Record Manager"); recordManager.close(); recordManager = null; isStarted = false; }
Source:
public void writePacket(byte[] buf, int pos, int len) throws IOException { formatLength(len + 4); out.write(lenbuffer, 0, 4); out.write(buf, pos, len); }

Target:
public void writePacket(byte[] buf, int pos, int len) throws IOException { formatLength(len + 4); out.write(lenbuffer, 0, 4); out.write(buf, pos, len); log.debug("git> " + RawParseUtils.decode(Constants.CHARSET, buf, pos, len)); }
Source:
int runCmd(CommandLine cmdLine) throws Exception { boolean getter = cmdLine.hasOption("g"); boolean setter = cmdLine.hasOption("s"); if ((!getter && !setter) || (getter && setter)) { LOG.error("One and only one of -get and -set must be specified"); printUsage(); return 1; } ZooKeeper zk = null; try { zk = ZooKeeperClient.newBuilder().connectString(bkConf.getZkServers()) .sessionTimeoutMs(bkConf.getZkTimeout()).build(); LedgerManagerFactory mFactory = LedgerManagerFactory.newLedgerManagerFactory(bkConf, zk); LedgerUnderreplicationManager underreplicationManager = mFactory.newLedgerUnderreplicationManager(); if (getter) { int lostBookieRecoveryDelay = underreplicationManager.getLostBookieRecoveryDelay(); LOG.info("LostBookieRecoveryDelay value in ZK: {}", String.valueOf(lostBookieRecoveryDelay)); } else { int lostBookieRecoveryDelay = Integer.parseInt(cmdLine.getOptionValue("set")); underreplicationManager.setLostBookieRecoveryDelay(lostBookieRecoveryDelay); LOG.info("Successfully set LostBookieRecoveryDelay value in ZK: {}", String.valueOf(lostBookieRecoveryDelay)); } } finally { if (zk != null) { zk.close(); } } return 0; }

Target:
int runCmd(CommandLine cmdLine) throws Exception { boolean getter = cmdLine.hasOption("g"); boolean setter = cmdLine.hasOption("s"); if ((!getter && !setter) || (getter && setter)) { LOG.error("One and only one of -get and -set must be specified"); printUsage(); return 1; } ClientConfiguration adminConf = new ClientConfiguration(bkConf); BookKeeperAdmin admin = new BookKeeperAdmin(adminConf); try { if (getter) { int lostBookieRecoveryDelay = admin.getLostBookieRecoveryDelay(); LOG.info("LostBookieRecoveryDelay value in ZK: {}", String.valueOf(lostBookieRecoveryDelay)); } else { int lostBookieRecoveryDelay = Integer.parseInt(cmdLine.getOptionValue("set")); admin.setLostBookieRecoveryDelay(lostBookieRecoveryDelay); LOG.info("Successfully set LostBookieRecoveryDelay value in ZK: {}", String.valueOf(lostBookieRecoveryDelay)); } } finally { if (admin != null) { admin.close(); } } return 0; }
Source:
private void refreshVdsRunTimeInfo() { boolean isVdsUpOrGoingToMaintenance = _vds.getStatus() == VDSStatus.Up || _vds.getStatus() == VDSStatus.PreparingForMaintenance || _vds.getStatus() == VDSStatus.Error || _vds.getStatus() == VDSStatus.NonOperational; try { if (isVdsUpOrGoingToMaintenance) { if (_vdsManager.getRefreshStatistics() || _vds.getStatus() == VDSStatus.PreparingForMaintenance) { refreshVdsStats(); } else { } } else { final AtomicBoolean processHardwareNeededAtomic = new AtomicBoolean(); VDSStatus refreshReturnStatus = _vdsManager.refreshCapabilities(processHardwareNeededAtomic, _vds, false); AttestationResultEnum trustLevel = AttestationCacheManager.getInstance() .getValueFromCache(_vds.getHostName()).getTrustLevel(); processHardwareCapsNeeded = processHardwareNeededAtomic.get(); refreshedCapabilities = true; if (refreshReturnStatus != VDSStatus.NonOperational) { _vdsManager.setStatus(VDSStatus.Up, _vds); } if (refreshReturnStatus != VDSStatus.NonOperational &&_vds.getTrustedService()){ if (trustLevel == AttestationResultEnum.TRUSTED){ _vdsManager.setStatus(VDSStatus.Up, _vds); } else{ _vdsManager.setStatus(VDSStatus.NonOperational, _vds); } } _saveVdsDynamic = true; } beforeFirstRefreshTreatment(isVdsUpOrGoingToMaintenance); refreshVmStats(); } catch (VDSRecoveringException e) { if (_vds.getStatus() != VDSStatus.PreparingForMaintenance) { throw e; } } moveVDSToMaintenanceIfNeeded(); }

Target:
private void refreshVdsRunTimeInfo() { boolean isVdsUpOrGoingToMaintenance = _vds.getStatus() == VDSStatus.Up || _vds.getStatus() == VDSStatus.PreparingForMaintenance || _vds.getStatus() == VDSStatus.Error || _vds.getStatus() == VDSStatus.NonOperational; try { if (isVdsUpOrGoingToMaintenance) { if (_vdsManager.getRefreshStatistics() || _vds.getStatus() == VDSStatus.PreparingForMaintenance) { refreshVdsStats(); } else { } } else { final AtomicBoolean processHardwareNeededAtomic = new AtomicBoolean(); VDSStatus refreshReturnStatus = _vdsManager.refreshCapabilities(processHardwareNeededAtomic, _vds, false); AttestationResultEnum trustLevel = AttestationResultEnum.UNKNOWN; AttestationValue value = AttestationCacheManager.getInstance().getValueFromCache(_vds.getHostName()); if (value !=null ){ trustLevel = value.getTrustLevel(); } processHardwareCapsNeeded = processHardwareNeededAtomic.get(); refreshedCapabilities = true; if (refreshReturnStatus != VDSStatus.NonOperational) { _vdsManager.setStatus(VDSStatus.Up, _vds); } if (refreshReturnStatus != VDSStatus.NonOperational &&_vds.getTrustedService()){ if (trustLevel == AttestationResultEnum.TRUSTED){ _vdsManager.setStatus(VDSStatus.Up, _vds); } else{ _vdsManager.setStatus(VDSStatus.NonOperational, _vds); } } _saveVdsDynamic = true; } beforeFirstRefreshTreatment(isVdsUpOrGoingToMaintenance); refreshVmStats(); } catch (VDSRecoveringException e) { if (_vds.getStatus() != VDSStatus.PreparingForMaintenance) { throw e; } } moveVDSToMaintenanceIfNeeded(); }
Source:
public Map<String, String> computeRecoveryAssignment(final CurrentStateOutput currentStateOutput, final String resourceName, final Partition partition, StateModelDefinition stateModelDef, List<String> preferenceList) { Map<String, String> currentStateMap = currentStateOutput.getCurrentStateMap(resourceName, partition); if (isCurrentStatesValid(currentStateOutput, resourceName, partition, stateModelDef)) { LOG.warn("The input current state map is valid, return the original current state.", currentStateMap); return currentStateMap; } Map<String, String> recoverMap = new HashMap<>(currentStateMap); String recoveryState = stateModelDef .getNextStateForTransition(stateModelDef.getTopState(), stateModelDef.getInitialState()); if (preferenceList != null && !preferenceList.isEmpty()) { String expectedTopStateHost = preferenceList.get(0); if (recoverMap.get(expectedTopStateHost).equals(stateModelDef.getTopState())) { recoverMap.put(expectedTopStateHost, recoveryState); } } boolean hasReservedTheTopState = false; for (String instance : recoverMap.keySet()) { if (recoverMap.get(instance).equals(stateModelDef.getTopState())) { if (hasReservedTheTopState) { recoverMap.put(instance, recoveryState); } else { hasReservedTheTopState = true; } } } return recoverMap; }

Target:
public Map<String, String> computeRecoveryAssignment(final CurrentStateOutput currentStateOutput, final String resourceName, final Partition partition, StateModelDefinition stateModelDef, List<String> preferenceList) { Map<String, String> currentStateMap = currentStateOutput.getCurrentStateMap(resourceName, partition); if (checkCurrentStates(currentStateOutput, resourceName, partition, stateModelDef)) { LOG.warn("The input current state map is valid, return the original current state.", currentStateMap); return currentStateMap; } Map<String, String> recoverMap = new HashMap<>(currentStateMap); String recoveryState = stateModelDef .getNextStateForTransition(stateModelDef.getTopState(), stateModelDef.getInitialState()); if (preferenceList != null && !preferenceList.isEmpty()) { String expectedTopStateHost = preferenceList.get(0); if (recoverMap.get(expectedTopStateHost).equals(stateModelDef.getTopState())) { recoverMap.put(expectedTopStateHost, recoveryState); } } boolean hasReservedTopState = false; for (String instance : recoverMap.keySet()) { if (recoverMap.get(instance).equals(stateModelDef.getTopState())) { if (hasReservedTopState) { recoverMap.put(instance, recoveryState); } else { hasReservedTopState = true; } } } return recoverMap; }