auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPutAll_with_cache_writer() throws Exception { CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(); CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder .addServiceConfig(new CacheWriterConfiguration()) .buildCacheConfig(String.class, String.class); CacheWriterFactoryHashMap cacheWriterFactoryHashMap = new CacheWriterFactoryHashMap(false); CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheWriterFactoryHashMap); CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(); Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class); HashMap<String, String> stringStringHashMap = new HashMap<String, String>(); for (int i = 0; i < 100; i++) { stringStringHashMap.put("key" + i, "value" + i); } myCache.putAll(stringStringHashMap.entrySet()); Map<String, String> cacheWriterToHashMapMap = cacheWriterFactoryHashMap.getCacheWriterToHashMap().getMap(); for (int i = 0; i < 100; i++) { assertThat(myCache.get("key" + i), is("value" + i)); assertThat(cacheWriterToHashMapMap.get("key" + i), is("value" + i)); } }

Target:
public void testPutAll_with_cache_writer() throws Exception { CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(); CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder .addServiceConfig(new CacheWriterConfiguration()) .buildCacheConfig(String.class, String.class); CacheWriterFactory cacheWriterFactory = mock(CacheWriterFactory.class); CacheWriter cacheWriter = mock(CacheWriter.class); when(cacheWriter.write(Matchers.anyObject(), Matchers.anyObject(), Matchers.anyObject())).thenThrow(new RuntimeException("We should not have called .write() but .writeAll()")); when(cacheWriterFactory.createCacheWriter(anyString(), Matchers.any(CacheConfiguration.class))).thenReturn(cacheWriter); CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheWriterFactory); CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(); Cache<String, String> myCache = cacheManager.getCache("myCache", String.class, String.class); HashMap<String, String> stringStringHashMap = new HashMap<String, String>(); for (int i = 0; i < 3; i++) { stringStringHashMap.put("key" + i, "value" + i); } myCache.putAll(stringStringHashMap.entrySet()); verify(cacheWriter, times(3)).writeAll(Matchers.any(Iterable.class)); Map iterable = new HashMap(){{put("key2", "value2");}}; verify(cacheWriter).writeAll(iterable.entrySet()); for (int i = 0; i < 3; i++) { assertThat(myCache.get("key" + i), is("value" + i)); } }
Source:
private void setNameQualifierIfPersistent(NameIDType nameIDType) { if (nameIDType.getFormat() != null && nameIDType.getFormat().toUpperCase().contains(PERSISTENT.toUpperCase())) nameIDType.setNameQualifier(NAME_QUALIFIER); }

Target:
private void setNameQualifierIfPersistent(NameIDType nameIDType) { if (nameIDType.getFormat() != null && nameIDType.getFormat().equalsIgnoreCase(PERSISTENT)) { nameIDType.setNameQualifier(NAME_QUALIFIER); } }
Source:
void executeTask(String taskName, InterruptibleRangeTask task) throws InterruptedException { BlockingWorkerPool pool = new BlockingWorkerPool(exec, threadCount); for (final MutableRange range : getRanges(threadCount, batchSize)) { if (Thread.currentThread().isInterrupted()) { log.info("Thread interrupted. Cancelling of range {}", taskName, range); break; } pool.submitTask(() -> { do { if (Thread.currentThread().isInterrupted()) { log.info("Thread interrupted. Cancelling of range {}", taskName, range); break; } try { task.execute(range); } catch (InterruptedException e) { throw Throwables.rewrapAndThrowUncheckedException(e); } } while (!range.isComplete()); }); } pool.waitForSubmittedTasks(); }

Target:
void executeTask(String taskName, InterruptibleRangeTask task) throws InterruptedException { BlockingWorkerPool pool = new BlockingWorkerPool(exec, threadCount); for (final MutableRange range : getRanges(threadCount, batchSize)) { if (Thread.currentThread().isInterrupted()) { log.info("Thread interrupted. Cancelling of range {}", SafeArg.of("taskName", taskName), UnsafeArg.of("range", range)); return; } pool.submitTask(() -> { do { if (Thread.currentThread().isInterrupted()) { log.info("Thread interrupted. Cancelling of range {}", SafeArg.of("taskName", taskName), UnsafeArg.of("range", range)); break; } try { task.execute(range); } catch (InterruptedException e) { throw Throwables.rewrapAndThrowUncheckedException(e); } } while (!range.isComplete()); }); } pool.waitForSubmittedTasks(); }
Source:
public void toLower() { assertThat( value.apply( "HELLO" ).toLower(), equalTo( value.apply( "hello" ) ) ); assertThat( value.apply( "Hello" ).toLower(), equalTo( value.apply( "hello" ) ) ); assertThat( value.apply( "hello" ).toLower(), equalTo( value.apply( "hello" ) ) ); }

Target:
public void toLower() { assertThat( value.apply( "HELLO" ).toLower(), equalTo( value.apply( "hello" ) ) ); assertThat( value.apply( "Hello" ).toLower(), equalTo( value.apply( "hello" ) ) ); assertThat( value.apply( "hello" ).toLower(), equalTo( value.apply( "hello" ) ) ); assertThat( value.apply( "" ).toLower(), equalTo( value.apply( "" ) ) ); }
Source:
public void onDataSetChanged() { SharedPreferences sharedprefs = PreferenceManager.getDefaultSharedPreferences(mContext); long noteID = sharedprefs.getLong(SingleNoteWidget.WIDGET_KEY + mAppWidgetId, -1); if (noteID >= 0) { if (db.getNote(noteID) == null) { Log.e(TAG, "Error: note not found"); note = null; } else { note = db.getNote(noteID); } } }

Target:
public void onDataSetChanged() { SharedPreferences sharedprefs = PreferenceManager.getDefaultSharedPreferences(mContext); long noteID = sharedprefs.getLong(SingleNoteWidget.WIDGET_KEY + mAppWidgetId, -1); if (noteID >= 0) { note = db.getNote(noteID); if (note == null) { Log.e(TAG, "Error: note not found"); } } }
Source:
public String render(Boolean vmMigrateEncrypted) { if (vmMigrateEncrypted == null) { if (getModel() == null || getModel().getSelectedCluster() == null) { return constants.clusterDefaultOption(); } Cluster cluster = getModel().getSelectedCluster(); boolean clusterMigrateEncrypted; if (cluster.getMigrateEncrypted() == null) { clusterMigrateEncrypted = AsyncDataProvider.getInstance().getMigrateEncrypted(); } else { clusterMigrateEncrypted = cluster.getMigrateEncrypted(); } String clusterMigrateEncryptedLabel = clusterMigrateEncrypted ? constants.encrypt() : constants.dontEncrypt(); return constants.clusterDefaultOption() + " (" + clusterMigrateEncryptedLabel + ")"; } else if (vmMigrateEncrypted) { return constants.encrypt(); } else { return constants.dontEncrypt(); } }

Target:
public String render(Boolean vmMigrateEncrypted) { if (vmMigrateEncrypted == null) { if (getModel() == null || getModel().getSelectedCluster() == null) { return constants.clusterDefaultOption(); } Cluster cluster = getModel().getSelectedCluster(); boolean clusterMigrateEncrypted; if (cluster.getMigrateEncrypted() == null) { clusterMigrateEncrypted = AsyncDataProvider.getInstance().getMigrateEncrypted(); } else { clusterMigrateEncrypted = cluster.getMigrateEncrypted(); } String clusterMigrateEncryptedLabel = clusterMigrateEncrypted ? constants.encrypt() : constants.dontEncrypt(); return messages.clusterDefaultOption(clusterMigrateEncryptedLabel); } else if (vmMigrateEncrypted) { return constants.encrypt(); } else { return constants.dontEncrypt(); } }
Source:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { try { Optional<CompressionCodec> compressionCodec = getCompressionCodec((TextInputFormat) inputFormat, path); if (!compressionCodec.isPresent() || stream(S3SelectSupportedCompressionCodecs.values()) .anyMatch(codec -> codec.getCodecClass().isInstance(compressionCodec.get()))) { return true; } } catch (IllegalAccessException e) { LOG.error(e, "Failed to find compressionCodec for inputFormat: %s", inputFormat.getClass().getName()); return false; } } return false; }

Target:
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path) { if (inputFormat instanceof TextInputFormat) { return getCompressionCodec((TextInputFormat) inputFormat, path) .map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec)) .orElse(true); } return false; }
Source:
public Metadata loadMetadata(String name, String metadataName) throws EntityNotFoundException { Product product = null; try { product = productManager.load(name); if (product.getMetadata(metadataName) == null ) { log.warning("Metadata not found : " + metadataName); throw new APIException(new EntityNotFoundException(Metadata.class, "Metadata not found : " + metadataName, metadataName)); } else { return product.getMetadata(metadataName); } } catch (EntityNotFoundException e) { log.warning("EntityNotFoundException: " + e.getMessage()); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } }

Target:
public Metadata loadMetadata(String name, String metadataName) throws APIException { Product product = null; try { product = productManager.load(name); } catch (EntityNotFoundException e) { log.warning("EntityNotFoundException: " + e.getMessage()); throw new APIException(new EntityNotFoundException(Product.class,name, e)); } try { return product.getMetadata(metadataName); } catch (Exception e) { log.warning("Metadata not found : " + metadataName); throw new APIException(new EntityNotFoundException(Metadata.class, "Metadata not found : " + metadataName, metadataName)); } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiLifecycleHelper = IUiLifecycleHelper.Factory.getInstance(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); Context context = getActivity().getBaseContext(); socialPref = new PrefManager(context, PrefManager.Pref.FEATURES); pref = new PrefManager(context, PrefManager.Pref.LOGIN); profile = pref.getCurrentUserProfile(); if (config.isUserProfilesEnabled() && profile != null && profile.username != null) { getAccountTask = new GetAccountTask(getActivity(), profile.username) { @Override protected void onSuccess(Account account) throws Exception { final ProfileImage profileImage = account.getProfileImage(); Glide.with(NavigationFragment.this) .load(profileImage.getImageUrlLarge()) .skipMemoryCache(true) .into(imageView); } }; getAccountTask.execute(); } }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiLifecycleHelper = IUiLifecycleHelper.Factory.getInstance(getActivity(), callback); uiLifecycleHelper.onCreate(savedInstanceState); Context context = getActivity().getBaseContext(); socialPref = new PrefManager(context, PrefManager.Pref.FEATURES); pref = new PrefManager(context, PrefManager.Pref.LOGIN); profile = pref.getCurrentUserProfile(); if (config.isUserProfilesEnabled() && profile != null && profile.username != null) { getAccountTask = new GetAccountTask(getActivity(), profile.username) { @Override protected void onSuccess(@NonNull Account account) throws Exception { NavigationFragment.this.profileImage = account.getProfileImage(); if (null != imageView) { loadProfileImage(account.getProfileImage(), imageView); } } }; getAccountTask.setTaskProcessCallback(null); getAccountTask.execute(); } }
Source:
public void setLastSpTruncationHandle(long spHandle) { if (spHandle > m_lastSpTruncationHandle) { m_lastSpTruncationHandle = spHandle; } }

Target:
public void setLastSpTruncationHandle(long spHandle) { if (spHandle > m_lastSpTruncationHandle) { m_lastSpTruncationHandle = spHandle; releaseShortCircuitRead(m_lastSpTruncationHandle, IS_SP); } }
Source:
public UnionOperatorStream<T> union(final ContinuousStream<T> inputStream) throws IOException{ final Type inputStreamDataType = ((ParameterizedType)inputStream.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; final Type thisStreamDataType = ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; if (inputStreamDataType.equals(thisStreamDataType)) { Set<ContinuousStream<T>> unifiedStream = new HashSet<>(); unifiedStream.add(this); unifiedStream.add(inputStream); return new UnionOperatorStream<>(unifiedStream); } else { throw new IOException("Cannot perform union between streams having different data type!"); } }

Target:
public UnionOperatorStream<T> union(final ContinuousStream<T> inputStream) throws StreamTypeMismatchException { if (TypeChecker.checkTypesEqual(this, inputStream)) { final Set<ContinuousStream<T>> unifiedStream = new HashSet<>(); unifiedStream.add(this); unifiedStream.add(inputStream); return new UnionOperatorStream<>(unifiedStream); } else { throw new StreamTypeMismatchException("Cannot perform union between streams having different data types!"); } }
Source:
private void executeDoneStage(ModelNode primaryResponse) { Throwable toThrow = null; try { ConfigurationPersister.PersistenceResource persistenceResource = null; if (isModelAffected() && resultAction != ResultAction.ROLLBACK) { try { persistenceResource = createPersistenceResource(); } catch (ConfigurationPersistenceException e) { MGMT_OP_LOGGER.failedToPersistConfigurationChange(e); primaryResponse.get(OUTCOME).set(FAILED); primaryResponse.get(FAILURE_DESCRIPTION).set(ControllerLogger.ROOT_LOGGER.failedToPersistConfigurationChange(e.getLocalizedMessage())); resultAction = ResultAction.ROLLBACK; executeResultHandlerPhase(null); return; } } final AtomicReference<ResultAction> ref = new AtomicReference<ResultAction>( transactionControl == null ? ResultAction.KEEP : ResultAction.ROLLBACK); if (transactionControl != null) { if (MGMT_OP_LOGGER.isTraceEnabled()) { MGMT_OP_LOGGER.trace("Prepared response is " + activeStep.response); } transactionControl.operationPrepared(new ModelController.OperationTransaction() { public void commit() { ref.set(ResultAction.KEEP); } public void rollback() { ref.set(ResultAction.ROLLBACK); } }, primaryResponse); } resultAction = ref.get(); if (persistenceResource != null) { if (resultAction == ResultAction.ROLLBACK) { persistenceResource.rollback(); } else { persistenceResource.commit(); } } publishCapabilityRegistry(); } catch (Throwable t) { toThrow = t; resultAction = ResultAction.ROLLBACK; } finally { executeResultHandlerPhase(toThrow); } }

Target:
private void executeDoneStage(ModelNode primaryResponse) { Throwable toThrow = null; try { ConfigurationPersister.PersistenceResource persistenceResource = null; if (isModelAffected() && resultAction != ResultAction.ROLLBACK) { try { persistenceResource = createPersistenceResource(); } catch (ConfigurationPersistenceException e) { MGMT_OP_LOGGER.failedToPersistConfigurationChange(e); primaryResponse.get(OUTCOME).set(FAILED); primaryResponse.get(FAILURE_DESCRIPTION).set(ControllerLogger.ROOT_LOGGER.failedToPersistConfigurationChange(e.getLocalizedMessage())); resultAction = ResultAction.ROLLBACK; executeResultHandlerPhase(null); return; } } final AtomicReference<ResultAction> ref = new AtomicReference<ResultAction>( transactionControl == null ? ResultAction.KEEP : ResultAction.ROLLBACK); if (transactionControl != null) { if (MGMT_OP_LOGGER.isTraceEnabled()) { MGMT_OP_LOGGER.trace("Prepared response is " + activeStep.response); } transactionControl.operationPrepared(new ModelController.OperationTransaction() { public void commit() { ref.set(ResultAction.KEEP); } public void rollback() { ref.set(ResultAction.ROLLBACK); } }, primaryResponse); } resultAction = ref.get(); if (persistenceResource != null) { if (resultAction == ResultAction.ROLLBACK) { persistenceResource.rollback(); } else { persistenceResource.commit(); } } if (resultAction != ResultAction.ROLLBACK) { publishCapabilityRegistry(); } } catch (Throwable t) { toThrow = t; resultAction = ResultAction.ROLLBACK; } finally { executeResultHandlerPhase(toThrow); } }
Source:
public static Properties defaultProperties() { Properties properties = OneAndOneApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "de,us,es,gb"); properties.setProperty(PROPERTY_REGION + ".de." + ISO3166_CODES, "DE-DEU"); properties.setProperty(PROPERTY_REGION + ".us." + ISO3166_CODES, "US-USA"); properties.setProperty(PROPERTY_REGION + ".es." + ISO3166_CODES, "ES-ESP"); properties.setProperty(PROPERTY_REGION + ".gb." + ISO3166_CODES, "GB-GBR"); properties.put("jclouds.ssh.max-retries", "7"); properties.put("jclouds.ssh.retry-auth", "true"); long defaultTimeout = 60L * 60L; properties.put(POLL_TIMEOUT, defaultTimeout); properties.put(POLL_PERIOD, 2L); properties.put(POLL_MAX_PERIOD, 2L * 10L); properties.put(PROPERTY_SO_TIMEOUT, 60000 * 5); properties.put(PROPERTY_CONNECTION_TIMEOUT, 60000 * 5); properties.put(PROPERTY_MAX_RATE_LIMIT_WAIT, 20); return properties; }

Target:
public static Properties defaultProperties() { Properties properties = OneAndOneApiMetadata.defaultProperties(); properties.put("jclouds.ssh.max-retries", "7"); properties.put("jclouds.ssh.retry-auth", "true"); long defaultTimeout = 60L * 60L; properties.put(POLL_TIMEOUT, defaultTimeout); properties.put(POLL_INITIAL_PERIOD, 5L * 10); properties.put(POLL_MAX_PERIOD, 7L * 10L); properties.put(PROPERTY_SO_TIMEOUT, 6000 * 5); properties.put(PROPERTY_CONNECTION_TIMEOUT, 60000 * 5); properties.put(PROPERTY_MAX_RATE_LIMIT_WAIT, 330000); return properties; }
Source:
public static List<Path> unrollPaths(final Collection<Path> inputs, final String... extensions) { if (extensions.length < 1) throw new IllegalArgumentException("Must provide at least one extension."); final Stack<Path> stack = new Stack<>(); final List<Path> output = new ArrayList<>(); stack.addAll(inputs); while (!stack.empty()) { final Path p = stack.pop(); final String name = p.toUri().toString(); boolean matched = false; for (final String ext : extensions) { if (!matched && name.endsWith(ext)) { output.add(p); matched = true; } } if (!matched) { IOUtil.assertFileIsReadable(p); try { Files.lines(p).forEach(s -> { if (!s.trim().isEmpty()) { final Path innerPath; try { innerPath = getPath(s.trim()); stack.push(innerPath); } catch (IOException e) { throw new IllegalArgumentException("cannot convert " + s.trim() + " to a Path."); } } }); } catch (IOException e) { throw new IllegalArgumentException("had trouble reading from " + p.toUri().toString()); } } } Collections.reverse(output); return output; }

Target:
public static List<Path> unrollPaths(final Collection<Path> inputs, final String... extensions) { if (extensions.length < 1) throw new IllegalArgumentException("Must provide at least one extension."); final Stack<Path> stack = new Stack<>(); final List<Path> output = new ArrayList<>(); stack.addAll(inputs); while (!stack.empty()) { final Path p = stack.pop(); final String name = p.toString(); boolean matched = false; for (final String ext : extensions) { if (!matched && name.endsWith(ext)) { output.add(p); matched = true; } } if (!matched) { IOUtil.assertFileIsReadable(p); try { Files.lines(p) .map(String::trim) .filter(s -> !s.isEmpty()) .forEach(s -> { final Path innerPath; try { innerPath = getPath(s); stack.push(innerPath); } catch (IOException e) { throw new IllegalArgumentException("cannot convert " + s + " to a Path."); } } ); } catch (IOException e) { throw new IllegalArgumentException("had trouble reading from " + p.toUri().toString()); } } } Collections.reverse(output); return output; }
Source:
private void loadDictionary() { final String language = userPrefs_.spellingDictionaryLanguage().getValue(); if (!userPrefs_.realTimeSpellchecking().getValue() || typoLoaded_ && loadedDict_.equals(language)) return; if (!canRealtimeSpellcheckDict(language)) { userPrefs_.realTimeSpellchecking().setGlobalValue(false); return; } if (activeRequest_ != null && activeRequest_.isAlive()) { if (StringUtil.equals(activeRequest_.getLanguage(), language)) return; activeRequest_.cancel(); activeRequest_ = null; } activeRequest_ = new TypoDictionaryRequest(language); activeRequest_.send(); }

Target:
private void loadDictionary() { final String language = userPrefs_.spellingDictionaryLanguage().getValue(); if (!userPrefs_.realTimeSpellchecking().getValue() || typoLoaded_ && loadedDict_.equals(language)) return; if (!canRealtimeSpellcheckDict(language)) return; if (activeRequest_ != null && activeRequest_.isAlive()) { if (StringUtil.equals(activeRequest_.getLanguage(), language)) return; activeRequest_.cancel(); activeRequest_ = null; } activeRequest_ = new TypoDictionaryRequest(language); activeRequest_.send(); }
Source:
public void doesNotComplainAboutConstantsInInnerClasses() throws Exception { final Environment env = new Environment.Mock().withFile( "src/main/java/foo/Foo.java", Joiner.on('\n').join( "package foo;", "interface Foo {", " final class Bar implements Foo {", " private static final Pattern TEST =", " Pattern.compile(\"hey\");", " public String doSomething() {", " return Foo.Bar.TEST.toString();", " }", " }", "}" ) ); final StringWriter writer = new StringWriter(); Logger.getRootLogger().addAppender( new WriterAppender(new SimpleLayout(), writer) ); final Validator validator = new PMDValidator(); validator.validate(env); MatcherAssert.assertThat( writer.toString(), Matchers.allOf( Matchers.not(Matchers.containsString("UnusedPrivateMethod")), Matchers.containsString("No PMD violations found in 1 files") ) ); }

Target:
public void doesNotComplainAboutConstantsInInnerClasses() throws Exception { final Environment env = new Environment.Mock().withFile( "src/main/java/foo/Foo.java", Joiner.on('\n').join( "package foo;", "interface Foo {", " final class Bar implements Foo {", " private static final Pattern TEST =", " Pattern.compile(\"hey\");", " public String doSomething() {", " return Foo.Bar.TEST.toString();", " }", " }", "}" ) ); final StringWriter writer = new StringWriter(); final Appender appender = new WriterAppender( new SimpleLayout(), writer ); try { Logger.getRootLogger().addAppender(appender); new PMDValidator().validate(env); writer.flush(); MatcherAssert.assertThat( writer.toString(), Matchers.allOf( Matchers.not(Matchers.containsString("UnusedPrivateField")), Matchers.containsString("No PMD violations found") ) ); } finally { Logger.getRootLogger().removeAppender(appender); } }
Source:
private String getCurrentUsername() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username; if (Objects.nonNull(authentication) && authentication.isAuthenticated()) { username = authentication.getName(); } else { username = "Unauthenticated User"; } return username; }

Target:
private String getCurrentUsername() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return (Objects.nonNull(authentication) && authentication.isAuthenticated()) ? authentication.getName() : "Unauthenticated User"; }
Source:
public File getFile10(String taskId, String repositoryUrl) { try { String pathName = URLEncoder.encode(repositoryUrl, ENCODING_UTF_8); String fileName = taskId; File path = new File(dataPath + File.separator + FOLDER_TASKS_1_0, pathName); File file = new File(path, fileName + EXTENSION); if (file.exists()) { return file; } fileName = getFileName(taskId, path); return new File(path, fileName + EXTENSION); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }

Target:
public File getFile10(String taskId, String repositoryUrl) { try { String pathName = URLEncoder.encode(repositoryUrl, ENCODING_UTF_8); String fileName = taskId; File path = new File(dataPath + File.separator + FOLDER_TASKS_1_0, pathName); if (!fileExists(fileName, path)) { fileName = getFileName(taskId, path); } return new File(path, fileName + EXTENSION); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
static CharSequence toLowerCase(CharSequence s) { return AsciiString.of(s).toLowerCase(); }

Target:
static CharSequence toLowerCase(CharSequence s) { if (s instanceof AsciiString) { return ((AsciiString) s).toLowerCase(); } else { byte[] bytes = new byte[s.length()]; int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (AsciiString.isUpperCase(c)) { bytes[index] = AsciiString.c2b((char)(c + ('a' - 'A'))); } else { bytes[index] = AsciiString.c2b(c); } } return new AsciiString(bytes); } }
Source:
public List<Trigger> handle(ResultSet rs) throws SQLException { if (!rs.next()) { return Collections.<Trigger>emptyList(); } ArrayList<Trigger> triggers = new ArrayList<Trigger>(); do { int triggerId = rs.getInt(1); int encodingType = rs.getInt(4); byte[] data = rs.getBytes(5); Object jsonObj = null; if (data != null) { EncodingType encType = EncodingType.fromInteger(encodingType); try { if (encType == EncodingType.GZIP) { String jsonString = GZIPUtils.unGzipString(data, "UTF-8"); jsonObj = JSONUtils.parseJSONFromString(jsonString); } else { String jsonString = new String(data, "UTF-8"); jsonObj = JSONUtils.parseJSONFromString(jsonString); } } catch (IOException e) { throw new SQLException("Error reconstructing trigger data "); } } Trigger t = null; try { t = Trigger.fromJson(jsonObj); triggers.add(t); } catch (Exception e) { e.printStackTrace(); logger.error("Failed to load trigger " + triggerId); } } while (rs.next()); return triggers; }

Target:
public List<Trigger> handle(ResultSet rs) throws SQLException { if (!rs.next()) { return Collections.<Trigger>emptyList(); } ArrayList<Trigger> triggers = new ArrayList<Trigger>(); do { int triggerId = rs.getInt(1); int encodingType = rs.getInt(4); byte[] data = rs.getBytes(5); Object jsonObj = null; if (data != null) { EncodingType encType = EncodingType.fromInteger(encodingType); try { jsonObj = JSONUtils.parseJSONFromString(encType == EncodingType.GZIP ? GZIPUtils.unGzipString(data, "UTF-8") : new String(data, "UTF-8")); } catch (IOException e) { throw new SQLException("Error reconstructing trigger data "); } } Trigger t = null; try { t = Trigger.fromJson(jsonObj); triggers.add(t); } catch (Exception e) { logger.error("Failed to load trigger " + triggerId, e); } } while (rs.next()); return triggers; }
Source:
public void close() { if (updateScoresScheduler != null) updateScoresScheduler.cancel(false); if (updateSamplesScheduler != null) updateSamplesScheduler.cancel(false); for (AnnotatedMeasurement measurement : samples.values()) { if (measurement.probeFuture != null) measurement.probeFuture.cancel(false); measurement.millisSinceLastMeasure.set(0); measurement.millisSinceLastRequest.set(MAX_PROBE_INTERVAL_MS); measurement.probeTimerMillis = 0; } MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { if (mbeanRegistered) mbs.unregisterMBean(new ObjectName(mbeanName)); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public synchronized void close() { ensureCancelled(updateScoresScheduler); ensureCancelled(updateSamplesScheduler); updateScoresScheduler = null; updateSamplesScheduler = null; List<ScheduledFuture> probesToCancel = new ArrayList<>(); for (AnnotatedMeasurement measurement : samples.values()) { probesToCancel.add(measurement.probeFuture); measurement.millisSinceLastMeasure.set(0); measurement.millisSinceLastRequest.set(0); measurement.nextProbeDelayMillis = 0; measurement.probeFuture = null; } ensureCancelled(probesToCancel); if (mbeanRegistered) MBeanWrapper.instance.unregisterMBean(mbeanName); MessagingService.instance().unregisterLatencySubscriber(this); mbeanRegistered = false; }
Source:
private void loadAttributeWasValues(BranchId sourceBranch, TransactionToken transactionId, Set<ArtifactId> artIds, IProgressMonitor monitor, Map<Integer, ChangeBuilder> attributesWasValueCache, boolean hasBranch) { if (!artIds.isEmpty()) { Id sqlParamter; BranchId wasValueBranch; String sql; if (hasBranch) { wasValueBranch = sourceBranch; sql = ServiceUtil.getSql(OseeSql.CHANGE_BRANCH_ATTRIBUTE_WAS); sqlParamter = wasValueBranch; } else { wasValueBranch = transactionId.getBranch(); sql = ServiceUtil.getSql(OseeSql.CHANGE_TX_ATTRIBUTE_WAS); sqlParamter = transactionId; } try (Id4JoinQuery joinQuery = JoinUtility.createId4JoinQuery()) { for (ArtifactId artId : artIds) { joinQuery.add(wasValueBranch, ArtifactId.valueOf(artId), TransactionId.SENTINEL, wasValueBranch.getViewId()); } joinQuery.store(); previousAttrId = -1; ConnectionHandler.getJdbcClient().runQuery(this::buildAttributeChange, sql, sqlParamter, joinQuery.getQueryId()); } if (getMonitor() != null) { monitor.worked(12); } } }

Target:
private void loadAttributeWasValues(BranchId sourceBranch, TransactionToken transactionId, Set<ArtifactId> artIds, IProgressMonitor monitor, Map<Integer, ChangeBuilder> attributesWasValueCache, boolean hasBranch) { if (!artIds.isEmpty()) { Id sqlParamter; BranchId wasValueBranch; String sql; if (hasBranch) { wasValueBranch = sourceBranch; sql = ServiceUtil.getSql(OseeSql.CHANGE_BRANCH_ATTRIBUTE_WAS); sqlParamter = wasValueBranch; } else { wasValueBranch = transactionId.getBranch(); sql = ServiceUtil.getSql(OseeSql.CHANGE_TX_ATTRIBUTE_WAS); sqlParamter = transactionId; } try (Id4JoinQuery joinQuery = JoinUtility.createId4JoinQuery()) { for (ArtifactId artId : artIds) { joinQuery.add(wasValueBranch, artId, TransactionId.SENTINEL, wasValueBranch.getViewId()); } joinQuery.store(); previousAttrId = -1; ConnectionHandler.getJdbcClient().runQuery(this::buildAttributeChange, sql, sqlParamter, joinQuery.getQueryId()); } if (getMonitor() != null) { monitor.worked(12); } } }
Source:
private SubPillarConfigPolicy(int minimumSubPillarSize, int maximumSubPillarSize, Comparator<?> entityComparator) { this.subPillarEnabled = true; this.minimumSubPillarSize = minimumSubPillarSize; this.maximumSubPillarSize = maximumSubPillarSize; validateSizes(); if (entityComparator == null) { throw new IllegalStateException("entityComparator must not be null."); } this.entityComparator = entityComparator; }

Target:
private SubPillarConfigPolicy(int minimumSubPillarSize, int maximumSubPillarSize, Comparator<?> entityComparator) { this.subPillarEnabled = true; this.minimumSubPillarSize = minimumSubPillarSize; this.maximumSubPillarSize = maximumSubPillarSize; validateSizes(); if (entityComparator == null) { throw new IllegalStateException("The entityComparator must not be null."); } this.entityComparator = entityComparator; }
Source:
getResponsesSortedByGiverQuestionRecipient(boolean sortByTeam) { Map<String, Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>> sortedMap = new LinkedHashMap<>(); if (sortByTeam) { responses.sort(compareByTeamGiverQuestionTeamRecipient); } else { responses.sort(compareByGiverQuestionTeamRecipient); } for (FeedbackResponseAttributes response : responses) { String giverEmail = response.giver; Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> responsesFromOneGiver = sortedMap.computeIfAbsent(giverEmail, (String key) -> new LinkedHashMap<>()); FeedbackQuestionAttributes question = questions.get(response.feedbackQuestionId); responsesFromOneGiver.computeIfAbsent(question, (FeedbackQuestionAttributes key) -> new ArrayList<>()) .add(response); } return sortedMap; }

Target:
getResponsesSortedByGiverQuestionRecipient(boolean sortByTeam) { Map<String, Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>> sortedMap = new LinkedHashMap<>(); if (sortByTeam) { responses.sort(compareByTeamGiverQuestionTeamRecipient); } else { responses.sort(compareByGiverQuestionTeamRecipient); } for (FeedbackResponseAttributes response : responses) { String giverEmail = response.giver; Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> responsesFromOneGiver = sortedMap.computeIfAbsent(giverEmail, key -> new LinkedHashMap<>()); FeedbackQuestionAttributes question = questions.get(response.feedbackQuestionId); responsesFromOneGiver.computeIfAbsent(question, key -> new ArrayList<>()) .add(response); } return sortedMap; }
Source:
public Set<SOURCE> getActiveSources() { Set<SOURCE> inactiveSources = Sets.newHashSet(); inactiveSources.addAll(soundSources.keySet().stream().filter(source -> isActive(source)).collect(Collectors.toList())); return inactiveSources; }

Target:
public Set<SOURCE> getActiveSources() { return soundSources.keySet().stream().filter(this::isActive).collect(Collectors.toCollection(HashSet::new)); }
Source:
protected void init() { super.init(); if (Guid.Empty.equals(getParameters().getVmId())) { boolean vmPrestarted = true; Guid vmToAttach = vmPoolHandler.selectPrestartedVm( getVmPoolId(), getVmPool().isStateful(), (vmId, errors) -> getReturnValue().getValidationMessages().addAll(errors)); if (Guid.Empty.equals(vmToAttach)) { vmPrestarted = false; vmToAttach = vmPoolHandler.selectNonPrestartedVm( getVmPoolId(), (vmId, errors) -> getReturnValue().getValidationMessages().addAll(errors)); } getParameters().setVmId(vmToAttach); getParameters().setVmPrestarted(vmPrestarted); } setVmId(getParameters().getVmId()); }

Target:
protected void init() { super.init(); if (Guid.Empty.equals(getParameters().getVmId()) && getVmPool() != null) { boolean vmPrestarted = true; Guid vmToAttach = vmPoolHandler.selectPrestartedVm( getVmPoolId(), getVmPool().isStateful(), (vmId, errors) -> getReturnValue().getValidationMessages().addAll(errors)); if (Guid.Empty.equals(vmToAttach)) { vmPrestarted = false; vmToAttach = vmPoolHandler.selectNonPrestartedVm( getVmPoolId(), (vmId, errors) -> getReturnValue().getValidationMessages().addAll(errors)); } getParameters().setVmId(vmToAttach); getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VM, vmToAttach)); getParameters().setVmPrestarted(vmPrestarted); } setVmId(getParameters().getVmId()); }
Source:
public void showPreview(final PageTitle title, final String wikiText) { hideSoftKeyboard(requireActivity()); parentActivity.showProgressBar(true); String url = model.getTitle().getWikiSite().uri() + PAGE_HTML_PREVIEW_ENDPOINT + title.getPrefixedText(); String postData; try { postData = "wikitext=" + URLEncoder.encode(wikiText, "UTF-8"); webview.postUrl(url, postData.getBytes()); } catch (UnsupportedEncodingException e) { parentActivity.showError(e.getCause()); L.e(e.getCause()); } setUpWebView(); }

Target:
public void showPreview(final PageTitle title, final String wikiText) { hideSoftKeyboard(requireActivity()); parentActivity.showProgressBar(true); String url = model.getTitle().getWikiSite().uri() + PAGE_HTML_PREVIEW_ENDPOINT + title.getConvertedText(); String postData; postData = "wikitext=" + UriUtil.encodeURL(wikiText); webview.postUrl(url, postData.getBytes()); setUpWebView(); }
Source:
public void init(final T model) { super.init(model); model.getPropertyChangedEvent().addListener((ev, sender, args) -> { NetworkModel senderModel = (NetworkModel) sender; String propertyName = args.propertyName; if ("Message".equals(propertyName)) { getView().setMessageLabel(senderModel.getMessage()); } }); getView().toggleSubnetVisibility(model.getExternal().getEntity()); model.getExternal().getEntityChangedEvent().addListener((ev, sender, args) -> getView().toggleSubnetVisibility( model.getExternal().getEntity() && !model.getExternalProviders().getSelectedItem().getIsUnmanaged())); model.getExternalProviders().getSelectedItemChangedEvent().addListener((ev, sender, args) -> getView().toggleSubnetVisibility(model.getExternal().getEntity() && !model.getExternalProviders().getSelectedItem().getIsUnmanaged())); getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); model.getProfiles().getPropertyChangedEvent().addListener((ev, sender, args) -> { if ("IsAvailable".equals(args.propertyName)) { getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); } }); getView().getQosButton().setCommand(model.getAddQosCommand()); getView().getQosButton().addClickHandler(event -> getView().getQosButton().getCommand().execute()); getView().addMtuEditor(); }

Target:
public void init(final T model) { super.init(model); model.getPropertyChangedEvent().addListener((ev, sender, args) -> { NetworkModel senderModel = (NetworkModel) sender; String propertyName = args.propertyName; if ("Message".equals(propertyName)) { getView().setMessageLabel(senderModel.getMessage()); } }); getView().toggleSubnetVisibility(model.getExternal().getEntity()); model.getExternal().getEntityChangedEvent().addListener((ev, sender, args) -> toggleSubnetVisibility(model)); model.getExternalProviders().getSelectedItemChangedEvent().addListener((ev, sender, args) -> toggleSubnetVisibility(model)); model.getProfiles().getPropertyChangedEvent().addListener((ev, sender, args) -> { if ("IsAvailable".equals(args.propertyName)) { getView().toggleProfilesVisibility(model.getProfiles().getIsAvailable()); } }); getView().getQosButton().setCommand(model.getAddQosCommand()); getView().getQosButton().addClickHandler(event -> getView().getQosButton().getCommand().execute()); getView().addMtuEditor(); }
Source:
public void doTestHook(final SPOTS spot, final DefaultQuery _ignored, final ExecutionContext executionContext) { switch (spot) { case BEFORE_QUERY_EXECUTION: try { if (!latch.await(8, SECONDS)) { logger.warn("doTestHook latch took to long to release"); if (!latch.await(1, MINUTES)) { logger.error("doTestHook latch took way way long to release"); fail("testhook: query was not unlatched in time"); } } } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } break; case BEFORE_ADD_OR_UPDATE_MAPPING_OR_DESERIALIZING_NTH_STREAMINGOPERATION: if (hitCriticalThreshold && hitOnce.compareAndSet(false, true)) { InternalResourceManager resourceManager = (InternalResourceManager) getCache().getResourceManager(); resourceManager.getHeapMonitor().updateStateAndSendEvent(CRITICAL_HEAP_USED, "test"); await().until(() -> vmCheckCritcalHeap() == EVICTION_DISABLED_CRITICAL); callbackVM .invoke(() -> ResourceManagerWithQueryMonitorDUnitTest.criticalMemoryCountDownLatch .countDown()); } break; case LOW_MEMORY_WHEN_DESERIALIZING_STREAMINGOPERATION: rejectedObjects = true; break; default: break; } }

Target:
public void doTestHook(final SPOTS spot, final DefaultQuery _ignored, final ExecutionContext executionContext) { switch (spot) { case BEFORE_QUERY_EXECUTION: try { if (!latch.await(GeodeAwaitility.getTimeout().getValueInMS(), MILLISECONDS)) { fail("doTestHook: query was not unlatched in time"); } } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } break; case BEFORE_ADD_OR_UPDATE_MAPPING_OR_DESERIALIZING_NTH_STREAMINGOPERATION: if (hitCriticalThreshold && hitOnce.compareAndSet(false, true)) { InternalResourceManager resourceManager = (InternalResourceManager) getCache().getResourceManager(); resourceManager.getHeapMonitor().updateStateAndSendEvent(CRITICAL_HEAP_USED, "test"); await().until(() -> vmCheckCritcalHeap() == EVICTION_DISABLED_CRITICAL); callbackVM .invoke(() -> ResourceManagerWithQueryMonitorDUnitTest.criticalMemoryCountDownLatch .countDown()); } break; case LOW_MEMORY_WHEN_DESERIALIZING_STREAMINGOPERATION: rejectedObjects = true; break; default: break; } }
Source:
public void testAltNames() throws Exception { final File altFile = File.createTempFile("CreateSequenceDictionaryTest.", ".alt"); final PrintWriter pw = new PrintWriter(altFile); pw.println("chr1\t1"); pw.println("chr1\t01"); pw.println("chr1\tk1"); pw.println("chrMT\tM"); pw.flush(); pw.close(); altFile.deleteOnExit(); final File outputDict = File.createTempFile("CreateSequenceDictionaryTest.", ".dict"); outputDict.delete(); outputDict.deleteOnExit(); final String[] argv = { "REFERENCE=" + BASIC_FASTA, "AN=" + altFile, "OUTPUT=" + outputDict, "TRUNCATE_NAMES_AT_WHITESPACE=true" }; Assert.assertEquals(runPicardCommandLine(argv), 0); final SAMSequenceDictionary dict = SAMSequenceDictionaryExtractor.extractDictionary(outputDict); Assert.assertNotNull(dict, "dictionary is null"); SAMSequenceRecord ssr = dict.getSequence("chr1"); Assert.assertNotNull(ssr, "chr1 missing in dictionary"); String an = ssr.getAttribute("AN"); Assert.assertNotNull(ssr, "AN Missing"); Set<String> anSet = new HashSet<>(Arrays.asList(an.split("[,]"))); Assert.assertTrue(anSet.contains("1")); Assert.assertTrue(anSet.contains("01")); Assert.assertTrue(anSet.contains("k1")); Assert.assertFalse(anSet.contains("M")); ssr = dict.getSequence("chr2"); Assert.assertNotNull(ssr, "chr2 missing in dictionary"); an = ssr.getAttribute("AN"); Assert.assertNull(an, "AN Present"); ssr = dict.getSequence("chrM"); Assert.assertNull(ssr, "chrM presnt in dictionary"); }

Target:
public void testAltNames() throws Exception { final File altFile = File.createTempFile("CreateSequenceDictionaryTest", ".alt"); final PrintWriter pw = new PrintWriter(altFile); pw.println("chr1\t1"); pw.println("chr1\t01"); pw.println("chr1\tk1"); pw.println("chrMT\tM"); pw.flush(); pw.close(); altFile.deleteOnExit(); final File outputDict = File.createTempFile("CreateSequenceDictionaryTest.", ".dict"); outputDict.delete(); outputDict.deleteOnExit(); final String[] argv = { "REFERENCE=" + BASIC_FASTA, "AN=" + altFile, "OUTPUT=" + outputDict, "TRUNCATE_NAMES_AT_WHITESPACE=true" }; Assert.assertEquals(runPicardCommandLine(argv), 0); final SAMSequenceDictionary dict = SAMSequenceDictionaryExtractor.extractDictionary(outputDict); Assert.assertNotNull(dict, "dictionary is null"); SAMSequenceRecord ssr = dict.getSequence("chr1"); Assert.assertNotNull(ssr, "chr1 missing in dictionary"); String an = ssr.getAttribute("AN"); Assert.assertNotNull(ssr, "AN Missing"); Set<String> anSet = new HashSet<>(Arrays.asList(an.split("[,]"))); Assert.assertTrue(anSet.contains("1")); Assert.assertTrue(anSet.contains("01")); Assert.assertTrue(anSet.contains("k1")); Assert.assertFalse(anSet.contains("M")); ssr = dict.getSequence("chr2"); Assert.assertNotNull(ssr, "chr2 missing in dictionary"); an = ssr.getAttribute("AN"); Assert.assertNull(an, "AN Present"); ssr = dict.getSequence("chrM"); Assert.assertNull(ssr, "chrM present in dictionary"); }
Source:
private List<ProcessInstance> startProcess(KieSession kieSession, String processId, int count) throws InterruptedException { List<ProcessInstance> piList = new ArrayList<ProcessInstance>(); for (int i = 0; i < count; i++) { TimeUnit.MILLISECONDS.sleep(1000); ProcessInstance pi = kieSession.startProcess(processId); if (pi != null) { piList.add(pi); } } return piList; }

Target:
private List<ProcessInstance> startProcess(KieSession kieSession, String processId, int count) throws InterruptedException { return this.startProcess(kieSession, processId, count, 0); }
Source:
public Boolean call() throws InterruptedException{ CallContext callContext = bulkExecCallerImpl.getCallContextQueue().poll(); continueCalling = (callContext == null)? false:bulkExecCallerImpl.processOutput((CallContextImpl) callContext); if(continueCalling) { bulkExecCallerImpl.getCallContextQueue().put(callContext); submitTask(this); } else { aliveCallContextCount.decrementAndGet(); if (aliveCallContextCount.get() == 0) { getCallerThreadPoolExecutor().shutdown(); } } return true; }

Target:
public Boolean call() throws InterruptedException{ CallContext callContext = bulkExecCallerImpl.getCallContextQueue().poll(); continueCalling = (callContext == null)? false:bulkExecCallerImpl.processOutput((CallContextImpl) callContext); if(continueCalling) { bulkExecCallerImpl.getCallContextQueue().put(callContext); submitTask(this); } else { if (aliveCallContextCount.decrementAndGet() == 0) { getCallerThreadPoolExecutor().shutdown(); } } return true; }
Source:
public String getDropboxDisplayName(String siteId) { if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId)) { return null; } String id = COLLECTION_DROPBOX + siteId + "/"; if (isDropboxMaintainer(siteId)) { return siteId + DROPBOX_ID; } String displayId = userDirectoryService.getCurrentUser().getDisplayId(); if(displayId != null && displayId.length()>0) { return userDirectoryService.getCurrentUser().getSortName()+" ("+ displayId+")"; } else { return userDirectoryService.getCurrentUser().getSortName(); } }

Target:
public String getDropboxDisplayName(String siteId) { if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId)) { return null; } String id = COLLECTION_DROPBOX + siteId + "/"; if (isDropboxMaintainer(siteId)) { return siteId + DROPBOX_ID; } return getDisplayName(null); }
Source:
private void possiblyResetOffsetsOrWait( Map<TopicPartition, Long> outOfRangePartitions, KafkaConsumer<byte[], byte[]> consumer, Set<Integer> assignment ) throws InterruptedException { boolean shouldRetry = false; for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { final TopicPartition topicPartition = outOfRangePartition.getKey(); final long nextOffset = outOfRangePartition.getValue(); consumer.seekToBeginning(topicPartition); final long leastAvailableOffset = consumer.position(topicPartition); consumer.seek(topicPartition, nextOffset); if (tuningConfig.isResetOffsetAutomatically() && leastAvailableOffset > nextOffset) { resetOffset(consumer, assignment, topicPartition); } else { shouldRetry = true; } } if (shouldRetry) { log.warn("Retrying in %dms", POLL_RETRY_MS); pollRetryLock.lockInterruptibly(); try { long nanos = TimeUnit.MILLISECONDS.toNanos(POLL_RETRY_MS); while (nanos > 0L && !pauseRequested && !stopRequested) { nanos = isAwaitingRetry.awaitNanos(nanos); } } finally { pollRetryLock.unlock(); } } }

Target:
private void possiblyResetOffsetsOrWait( Map<TopicPartition, Long> outOfRangePartitions, KafkaConsumer<byte[], byte[]> consumer, Set<Integer> assignment ) throws InterruptedException { boolean shouldRetry = false; if(tuningConfig.isResetOffsetAutomatically()) { for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) { final TopicPartition topicPartition = outOfRangePartition.getKey(); final long nextOffset = outOfRangePartition.getValue(); consumer.seekToBeginning(topicPartition); final long leastAvailableOffset = consumer.position(topicPartition); consumer.seek(topicPartition, nextOffset); if (leastAvailableOffset > nextOffset) { resetOffset(consumer, assignment, topicPartition); } else { shouldRetry = true; } } } else { shouldRetry = true; } if (shouldRetry) { log.warn("Retrying in %dms", POLL_RETRY_MS); pollRetryLock.lockInterruptibly(); try { long nanos = TimeUnit.MILLISECONDS.toNanos(POLL_RETRY_MS); while (nanos > 0L && !pauseRequested && !stopRequested) { nanos = isAwaitingRetry.awaitNanos(nanos); } } finally { pollRetryLock.unlock(); } } }
Source:
public boolean initializeStream(StreamSpec streamSpec) { systemStreamToPartitions.put(streamSpec.toSystemStream(), streamSpec.getPartitionCount()); for (int partition = 0; partition < streamSpec.getPartitionCount(); partition++) { bufferedMessages.put( new SystemStreamPartition(streamSpec.toSystemStream(), new Partition(partition)), newSynchronizedLinkedList()); } return true; }

Target:
boolean initializeStream(StreamSpec streamSpec) { LOG.info("Initializing the stream for {}", streamSpec.getId()); systemStreamToPartitions.put(streamSpec.toSystemStream(), streamSpec.getPartitionCount()); for (int partition = 0; partition < streamSpec.getPartitionCount(); partition++) { bufferedMessages.put( new SystemStreamPartition(streamSpec.toSystemStream(), new Partition(partition)), newSynchronizedLinkedList()); } return true; }