auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Doi getAssetDoi(Node assetNode) { String nodeName = assetNode.getNodeName(); String doi; if (nodeName.equals(DISP_FORMULA)) { doi = readString("object-id[@pub-id-type=\"doi\"]", assetNode); if (doi == null) { doi = readHrefAttribute(assetNode); } } else if (GRAPHIC_NODE_PARENTS.contains(nodeName)) { doi = readString("object-id[@pub-id-type=\"doi\"]", assetNode); } else if (ASSET_NODE_NAMES.contains(nodeName)) { doi = readHrefAttribute(assetNode); } else { String message = String.format("Received a node of type \"%s\"; expected one of: %s", nodeName, Iterables.concat(ASSET_NODE_NAMES, GRAPHIC_NODE_PARENTS)); throw new IllegalArgumentException(message); } if (doi == null) { log.warn("An asset node ({}) does not have DOI as expected", assetNode.getNodeName()); return null; } return Doi.create(doi); }

Target:
protected Doi getAssetDoi(Node assetNode) { String nodeName = assetNode.getNodeName(); String doi; if (GRAPHIC_NODE_PARENTS.contains(nodeName)) { doi = readString("object-id[@pub-id-type=\"doi\"]", assetNode); if (doi == null && nodeName.equals(DISP_FORMULA)) { doi = readHrefAttribute(assetNode); } } else if (ASSET_NODE_NAMES.contains(nodeName)) { doi = readHrefAttribute(assetNode); } else { String message = String.format("Received a node of type \"%s\"; expected one of: %s", nodeName, Iterables.concat(ASSET_NODE_NAMES, GRAPHIC_NODE_PARENTS)); throw new IllegalArgumentException(message); } if (doi == null) { log.warn("An asset node ({}) does not have DOI as expected", assetNode.getNodeName()); return null; } return Doi.create(doi); }
Source:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int viewType = parent.getAdapter().getItemViewType(position); if (viewType == NavListAdapter.VIEW_TYPE_SECTION_DIVIDER) { FeedFilterDialog.showDialog(requireContext()); } else { if (position < navAdapter.getSubscriptionOffset()) { String tag = navAdapter.getTags().get(position); if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).loadFragment(tag, null); } else { showMainActivity(tag); } } else { int pos = position - navAdapter.getSubscriptionOffset(); long feedId = navDrawerData.feeds.get(pos).getId(); if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).loadFeedFragmentById(feedId, null); } else { Intent intent = new Intent(getActivity(), MainActivity.class); intent.putExtra(MainActivity.EXTRA_FEED_ID, feedId); startActivity(intent); } } } }

Target:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int viewType = parent.getAdapter().getItemViewType(position); if (viewType != NavListAdapter.VIEW_TYPE_SECTION_DIVIDER) { if (position < navAdapter.getSubscriptionOffset()) { String tag = navAdapter.getTags().get(position); if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).loadFragment(tag, null); } else { showMainActivity(tag); } } else { int pos = position - navAdapter.getSubscriptionOffset(); long feedId = navDrawerData.feeds.get(pos).getId(); if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).loadFeedFragmentById(feedId, null); } else { Intent intent = new Intent(getActivity(), MainActivity.class); intent.putExtra(MainActivity.EXTRA_FEED_ID, feedId); startActivity(intent); } } } else if (UserPreferences.getFeedFilter() != UserPreferences.FEED_FILTER_NONE && navAdapter.showSubscriptionList) { FeedFilterDialog.showDialog(requireContext()); } }
Source:
public void process(ImageProxyBundle bundle) { List<Integer> ids = bundle.getCaptureIds(); if (ids.size() > 1) { throw new IllegalArgumentException("Processing bundle of size greater than 1."); } ListenableFuture<ImageProxy> imageProxyListenableFuture = bundle.getImageProxy(ids.get(0)); try { ImageProxy imageProxy = imageProxyListenableFuture.get(5, TimeUnit.SECONDS); Image image = imageProxy.getImage(); if (image == null) { return; } ImageInfo imageInfo = imageProxy.getImageInfo(); CameraCaptureResult result = CameraCaptureResults.retrieveCameraCaptureResult(imageInfo); if (result == null) { mImpl.process(imageProxy.getImage(), null); return; } CaptureResult captureResult = Camera2CameraCaptureResultConverter.getCaptureResult(result); if (captureResult == null) { mImpl.process(imageProxy.getImage(), null); return; } TotalCaptureResult totalCaptureResult = (TotalCaptureResult) captureResult; if (totalCaptureResult == null) { mImpl.process(imageProxy.getImage(), null); return; } mImpl.process(imageProxy.getImage(), totalCaptureResult); } catch (TimeoutException | ExecutionException | InterruptedException e) { return; } }

Target:
public void process(ImageProxyBundle bundle) { List<Integer> ids = bundle.getCaptureIds(); if (ids.size() != 1) { throw new IllegalArgumentException( "Processing preview bundle must be 1, but found " + ids.size()); } ListenableFuture<ImageProxy> imageProxyListenableFuture = bundle.getImageProxy(ids.get(0)); try { ImageProxy imageProxy = imageProxyListenableFuture.get(5, TimeUnit.SECONDS); Image image = imageProxy.getImage(); if (image == null) { return; } ImageInfo imageInfo = imageProxy.getImageInfo(); CameraCaptureResult result = CameraCaptureResults.retrieveCameraCaptureResult(imageInfo); if (result == null) { mImpl.process(image, null); return; } CaptureResult captureResult = Camera2CameraCaptureResultConverter.getCaptureResult(result); if (captureResult == null) { mImpl.process(image, null); return; } if (captureResult instanceof TotalCaptureResult) { mImpl.process(imageProxy.getImage(), (TotalCaptureResult) captureResult); } else { mImpl.process(image, null); } } catch (TimeoutException | ExecutionException | InterruptedException e) { Log.e(TAG, "Unable to retrieve ImageProxy from bundle"); } }
Source:
public void testUpdateEstimation() { String topic = "tp"; class EstimationsObservedRatios { float currentEstimation; float observedRatio; float expected; EstimationsObservedRatios(float currentEstimation, float observedRatio, float expected) { this.currentEstimation = currentEstimation; this.observedRatio = observedRatio; this.expected = expected; } } EstimationsObservedRatios[] currentEstimationsObservedRatios = new EstimationsObservedRatios[] { new EstimationsObservedRatios(0.8f, 0.84f, 0.84f), new EstimationsObservedRatios(0.6f, 0.7f, 0.7f), new EstimationsObservedRatios(0.6f, 0.4f, 0.4f), new EstimationsObservedRatios(0.004f, 0.001f, 0.001f) }; float updatedCompressionRatio; for (int i = 0; i < currentEstimationsObservedRatios.length; i++) { CompressionRatioEstimator.setEstimation(topic, CompressionType.ZSTD, currentEstimationsObservedRatios[i].currentEstimation); updatedCompressionRatio = CompressionRatioEstimator.updateEstimation(topic, CompressionType.ZSTD, currentEstimationsObservedRatios[i].observedRatio); assertTrue(updatedCompressionRatio >= currentEstimationsObservedRatios[i].expected); } }

Target:
public void testUpdateEstimation() { class EstimationsObservedRatios { float currentEstimation; float observedRatio; EstimationsObservedRatios(float currentEstimation, float observedRatio) { this.currentEstimation = currentEstimation; this.observedRatio = observedRatio; } } List<EstimationsObservedRatios> estimationsObservedRatios = Arrays.asList( new EstimationsObservedRatios(0.8f, 0.84f), new EstimationsObservedRatios(0.6f, 0.7f), new EstimationsObservedRatios(0.6f, 0.4f), new EstimationsObservedRatios(0.004f, 0.001f)); for (EstimationsObservedRatios estimationsObservedRatio : estimationsObservedRatios) { String topic = "tp"; CompressionRatioEstimator.setEstimation(topic, CompressionType.ZSTD, estimationsObservedRatio.currentEstimation); float updatedCompressionRatio = CompressionRatioEstimator.updateEstimation(topic, CompressionType.ZSTD, estimationsObservedRatio.observedRatio); assertTrue(updatedCompressionRatio >= estimationsObservedRatio.observedRatio); } }
Source:
public boolean isSupported(Schema<?> schema) { return schema instanceof IntegerSchema || schema instanceof NumberSchema || schema instanceof StringSchema || schema instanceof BooleanSchema || schema instanceof ArraySchema || schema instanceof FileSchema || schema instanceof MapSchema; }

Target:
public boolean isSupported(Schema<?> schema) { return schema instanceof ArraySchema || schema instanceof BooleanSchema || schema instanceof FileSchema || schema instanceof IntegerSchema || schema instanceof MapSchema || schema instanceof NumberSchema || schema instanceof StringSchema; }
Source:
public CuratedContentPageObject openCuratedContentPage(String wikiURL, String path) { getUrl(wikiURL + path + "?cb=" + DateTime.now().getMillis()); PageObjectLogging .log("openCuratedContentPage", "Curated content page" + path + " was opened", true); return new CuratedContentPageObject(driver); }

Target:
public CuratedContentPageObject openCuratedContentPage(String wikiURL, String path) { String url; Long currentTime = DateTime.now().getMillis(); UrlBuilder builder = new UrlBuilder(); url = wikiURL + path; url = builder.appendQueryStringToURL(url, "cb=" + currentTime); getUrl(url); PageObjectLogging .log("openCuratedContentPage", "Curated content page" + path + " was opened", true); return new CuratedContentPageObject(driver); }
Source:
protected void initTableColumns(ApplicationConstants constants) { deviceTable.addColumn(new TextColumnWithTooltip<StorageDevice>() { @Override public String getValue(StorageDevice entity) { return entity.getName(); } }, constants.deviceName()); deviceTable.addColumnAndSetWidth(new TextColumnWithTooltip<StorageDevice>() { @Override public String getValue(StorageDevice entity) { return entity.getDevType(); } }, constants.deviceType(), "100px"); deviceTable.addColumnAndSetWidth(new TextColumnWithTooltip<StorageDevice>() { @Override public String getValue(StorageDevice entity) { Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(entity.getSize(), SizeUnit.MB); return formatSize(convertedSize.getSecond()) + " " + convertedSize.getFirst().toString(); } }, constants.size(), "100px"); deviceSelectionInfo.setVisible(false); }

Target:
protected void initTableColumns(ApplicationConstants constants) { deviceTable.addColumn(new AbstractTextColumnWithTooltip<StorageDevice>() { @Override public String getValue(StorageDevice entity) { return entity.getName(); } }, constants.deviceName()); deviceTable.addColumnAndSetWidth(new AbstractTextColumnWithTooltip<StorageDevice>() { @Override public String getValue(StorageDevice entity) { return entity.getDevType(); } }, constants.deviceType(), "100px"); deviceTable.addColumnAndSetWidth(new AbstractTextColumnWithTooltip<StorageDevice>() { @Override public String getValue(StorageDevice entity) { Pair<SizeUnit, Double> convertedSize = SizeConverter.autoConvert(entity.getSize(), SizeUnit.MB); return formatSize(convertedSize.getSecond()) + " " + convertedSize.getFirst().toString(); } }, constants.size(), "100px"); }
Source:
void init(int width, int height) { if (width <= 0 || height <= 0) { SWT.error (SWT.ERROR_INVALID_ARGUMENT); } this.type = SWT.BITMAP; surface = GDK.gdk_window_create_similar_surface(GDK.gdk_get_default_root_window(), Cairo.CAIRO_CONTENT_COLOR, width, height); if (surface == 0) SWT.error(SWT.ERROR_NO_HANDLES); if (!GTK.GTK3) { currentDeviceZoom = DPIUtil.getDeviceZoom(); } else { currentDeviceZoom = 100; Cairo.cairo_surface_set_device_scale(surface, currentDeviceZoom/100f, currentDeviceZoom/100f); } long cairo = Cairo.cairo_create(surface); if (cairo == 0) SWT.error(SWT.ERROR_NO_HANDLES); Cairo.cairo_set_source_rgb(cairo, 1, 1, 1); Cairo.cairo_rectangle(cairo, 0, 0, width, height); Cairo.cairo_fill(cairo); Cairo.cairo_destroy(cairo); this.width = width; this.height = height; }

Target:
void init(int width, int height) { if (width <= 0 || height <= 0) { SWT.error (SWT.ERROR_INVALID_ARGUMENT); } this.type = SWT.BITMAP; surface = GDK.gdk_window_create_similar_surface(GDK.gdk_get_default_root_window(), Cairo.CAIRO_CONTENT_COLOR, width, height); if (surface == 0) SWT.error(SWT.ERROR_NO_HANDLES); if (!GTK.GTK3) { currentDeviceZoom = DPIUtil.getDeviceZoom(); } else { currentDeviceZoom = 100; Cairo.cairo_surface_set_device_scale(surface, 1f, 1f); } long cairo = Cairo.cairo_create(surface); if (cairo == 0) SWT.error(SWT.ERROR_NO_HANDLES); Cairo.cairo_set_source_rgb(cairo, 1, 1, 1); Cairo.cairo_rectangle(cairo, 0, 0, width, height); Cairo.cairo_fill(cairo); Cairo.cairo_destroy(cairo); this.width = width; this.height = height; }
Source:
protected abstract void doChangeCurrentSchemaTo(String schema) throws SQLException; public String getCurrentUserName() { try { return doGetCurrentUserName(); } catch (SQLException e) { throw new FlywaySqlException("Unable to retrieve the current user for the connection", e); } }

Target:
protected abstract void doChangeCurrentSchemaTo(String schema) throws SQLException; public abstract String getCurrentUserFunction(); public abstract boolean supportsDdlTransactions(); public abstract String getBooleanTrue(); public abstract String getBooleanFalse(); public String quote(String... identifiers) { String result = ""; boolean first = true; for (String identifier : identifiers) { if (!first) { result += "."; } first = false; result += doQuote(identifier); } return result; }
Source:
private int getMaxSimul(@Nullable String maxSimulQueryParam, int totalTasks) { if (maxSimulQueryParam == null) { return totalTasks; } try { int n = Integer.parseInt(maxSimulQueryParam); return (0 < n && n <= totalTasks) ? n : totalTasks; } catch (Exception e) { return totalTasks; } }

Target:
private int getMaxSimul(@Nullable String maxSimulQueryParam, int totalTasks) { Integer n = Ints.tryParse(Strings.nullToEmpty(maxSimulQueryParam)); return (n != null && 0 < n && n <= totalTasks) ? n : totalTasks; }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Disk)) { return false; } Disk other = (Disk) obj; if (activeImage == null) { if (other.activeImage != null) { return false; } } else if (!activeImage.equals(other.activeImage)) { return false; } if (diskInterface != other.diskInterface) { return false; } if (diskType != other.diskType) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (propagateErrors != other.propagateErrors) { return false; } if (status != other.status) { return false; } if (wipeAfterDelete != other.wipeAfterDelete) { return false; } return true; }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Disk)) { return false; } Disk other = (Disk) obj; if (activeImage == null) { if (other.activeImage != null) { return false; } } else if (!activeImage.equals(other.activeImage)) { return false; } if (diskInterface != other.diskInterface) { return false; } if (diskType != other.diskType) { return false; } if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (internalDriveMapping != other.internalDriveMapping) { return false; } if (propagateErrors != other.propagateErrors) { return false; } if (status != other.status) { return false; } if (wipeAfterDelete != other.wipeAfterDelete) { return false; } return true; }
Source:
public Spliterator<T> spliterator() { if (!locked) throw new IllegalStateException("Cannot use EnumSelector that is not locked."); else return Spliterators.spliterator(iterator(), defaultBlock ? exceptions.size() : EnumSet.complementOf(exceptions).size(), Spliterator.DISTINCT | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE); }

Target:
public Spliterator<T> spliterator() { checkReadable(); return Spliterators.spliterator(iterator(), defaultBlock ? exceptions.size() : EnumSet.complementOf(exceptions).size(), Spliterator.DISTINCT | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE); }
Source:
private boolean isReplicaCountIncreased() { if ((getGlusterVolume().getVolumeType().isReplicatedType()) && getParameters().getReplicaCount() > getGlusterVolume().getReplicaCount()) { return true; } else { return false; } }

Target:
private boolean isReplicaCountIncreased() { return ((getGlusterVolume().getVolumeType() == GlusterVolumeType.REPLICATE || getGlusterVolume().getVolumeType() == GlusterVolumeType.DISTRIBUTED_REPLICATE) && getParameters().getReplicaCount() > getGlusterVolume().getReplicaCount()); }
Source:
public static Optional<RingTime> getRingTimeFromAttributes(final String deviceId, final long accountId, final Map<String, AttributeValue> item){ final HashSet<String> ringTimeAttributes = new HashSet<String>(); Collections.addAll(ringTimeAttributes, ACTUAL_RING_TIME_ATTRIBUTE_NAME, EXPECTED_RING_TIME_ATTRIBUTE_NAME, SOUND_IDS_ATTRIBUTE_NAME); if(!item.keySet().containsAll(ringTimeAttributes)){ return Optional.absent(); } final long expected = Long.valueOf(item.get(EXPECTED_RING_TIME_ATTRIBUTE_NAME).getN()); final long actual = Long.valueOf(item.get(ACTUAL_RING_TIME_ATTRIBUTE_NAME).getN()); final String soundArrayJSON = item.get(SOUND_IDS_ATTRIBUTE_NAME).getS(); final ObjectMapper mapper = new ObjectMapper(); try { final long[] soundIds = mapper.readValue(soundArrayJSON, long[].class); boolean isSmart = true; if(item.containsKey(IS_SMART_ALARM_ATTRIBUTE_NAME)){ isSmart = Boolean.parseBoolean(item.get(IS_SMART_ALARM_ATTRIBUTE_NAME).getS()); } return Optional.of(new RingTime(actual, expected, soundIds, isSmart)); } catch (IOException e) { LOGGER.error("Deserialize JSON for ring time failed {}, device {}, account id {}.", e.getMessage(), deviceId, accountId); } return Optional.absent(); }

Target:
public static Optional<RingTime> getRingTimeFromAttributes(final String deviceId, final long accountId, final Map<String, AttributeValue> item){ final HashSet<String> ringTimeAttributes = new HashSet<String>(); Collections.addAll(ringTimeAttributes, ACTUAL_RING_TIME_ATTRIBUTE_NAME, EXPECTED_RING_TIME_ATTRIBUTE_NAME, SOUND_IDS_ATTRIBUTE_NAME); if(!item.keySet().containsAll(ringTimeAttributes)){ return Optional.absent(); } final long expected = Long.valueOf(item.get(EXPECTED_RING_TIME_ATTRIBUTE_NAME).getN()); final long actual = Long.valueOf(item.get(ACTUAL_RING_TIME_ATTRIBUTE_NAME).getN()); final String soundArrayJSON = item.get(SOUND_IDS_ATTRIBUTE_NAME).getS(); final ObjectMapper mapper = new ObjectMapper(); try { final long[] soundIds = mapper.readValue(soundArrayJSON, long[].class); boolean isSmart = true; if(item.containsKey(IS_SMART_ALARM_ATTRIBUTE_NAME)){ isSmart = item.get(IS_SMART_ALARM_ATTRIBUTE_NAME).getBOOL(); } return Optional.of(new RingTime(actual, expected, soundIds, isSmart)); } catch (IOException e) { LOGGER.error("Deserialize JSON for ring time failed {}, device {}, account id {}.", e.getMessage(), deviceId, accountId); } return Optional.absent(); }
Source:
public TreeSet<T> addAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (Collections.isEmpty(elements) || this.equals(elements)){ return this; } RedBlackTree<T> that = tree; for (T element : elements) { if (!that.contains(element)) { that = that.insert(element); } } return new TreeSet<>(that); }

Target:
public TreeSet<T> addAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); RedBlackTree<T> that = tree; for (T element : elements) { if (!that.contains(element)) { that = that.insert(element); } } if (tree == that) { return this; } else { return new TreeSet<>(that); } }
Source:
public static DeleteRecord deserializeDeleteRecord(CrcInputStream crcStream) throws IOException, MessageFormatException { DataInputStream dataStream = new DataInputStream(crcStream); boolean isDeleted = dataStream.readByte() == 1 ? true : false; long actualCRC = crcStream.getValue(); long expectedCRC = dataStream.readLong(); if (actualCRC != expectedCRC) { logger.error( "corrupt data while parsing delete record Expected CRC " + expectedCRC + " Actual CRC " + actualCRC); throw new MessageFormatException("delete record data is corrupt", MessageFormatErrorCodes.Data_Corrupt); } return new DeleteRecord(); }

Target:
public static DeleteRecord deserializeDeleteRecord(CrcInputStream crcStream) throws IOException, MessageFormatException { DataInputStream dataStream = new DataInputStream(crcStream); boolean isDeleted = dataStream.readByte() == 1; long actualCRC = crcStream.getValue(); long expectedCRC = dataStream.readLong(); if (actualCRC != expectedCRC) { logger.error( "corrupt data while parsing delete record Expected CRC " + expectedCRC + " Actual CRC " + actualCRC); throw new MessageFormatException("delete record data is corrupt", MessageFormatErrorCodes.Data_Corrupt); } return new DeleteRecord(UNKNOWN_ACCOUNT_ID, UNKNOWN_CONTAINER_ID, Utils.Infinite_Time); }
Source:
public void uploadEnrichmentTags(InputStream inputStream) throws IOException, JsonParseException, JsonItemParseException, ValidationException, ServiceException { try (LimitedInputStream limitedInputStream = limitInputStream(inputStream, enrichmentTagMaxUploadSize)) { JsonParser jsonParser = jsonFactory.createParser(limitedInputStream); EnrichmentTagItem enrichmentTagItem = null; do { enrichmentTagItem = enrichmentTagItemReader.nextEnrichmentTagItem(jsonParser); if (enrichmentTagItem == null) { return; } enrichmentTagItemUploadProcessor.processEnrichmentTagItem(enrichmentTagItem); } while (enrichmentTagItem != null); } }

Target:
public void uploadEnrichmentTags(InputStream inputStream) { try { try (LimitedInputStream limitedInputStream = limitInputStream(inputStream, enrichmentTagMaxUploadSize)) { JsonParser jsonParser = jsonFactory.createParser(limitedInputStream); EnrichmentTagItem enrichmentTagItem = null; do { enrichmentTagItem = enrichmentTagItemReader.nextEnrichmentTagItem(jsonParser); if (enrichmentTagItem == null) { return; } enrichmentTagItemUploadProcessor.processEnrichmentTagItem(enrichmentTagItem); } while (true); } } catch (JsonParseException e) { throw new ServiceException(ERROR_INVALID_JSON_FORMAT, e.getMessage(), e); } catch (ValidationException e) { throw new ServiceException(ERROR_INVALID_DATA, e.getMessage(), e); } catch (IOException e) { throw new ServiceException(ERROR_IO, e.getMessage(), e); } catch (DataIntegrityViolationException e) { throw new ServiceException(ERROR_SAME_TAG_ALREADY_UPLOADED, e.getMessage(), e); } }
Source:
public void addChangeListener_throwOnAddingNullListenerFromNonLooperThread() throws Throwable { TestHelper.executeOnNonLooperThread(new TestHelper.Task() { @Override public void run() throws Exception { final Realm realm = Realm.getInstance(realmConfig); final Dog dog = createManagedDogObjectFromRealmInstance(realm); try { dog.addChangeListener((RealmChangeListener)null); fail("adding null change listener must throw an exception."); } catch (IllegalArgumentException ignore) { } finally { realm.close(); } } }); }

Target:
public void addChangeListener_throwOnAddingNullListenerFromNonLooperThread() throws Throwable { final Dog dog = createManagedDogObjectFromRealmInstance(realm); try { dog.addChangeListener((RealmChangeListener) null); fail("adding null change listener must throw an exception."); } catch (IllegalArgumentException ignore) { } try { dog.addChangeListener((RealmObjectChangeListener) null); fail("adding null change listener must throw an exception."); } catch (IllegalArgumentException ignore) { } }
Source:
private void prePopulateDatabase( GraphDatabaseService database, Label testLabel, String propertyName ) { for ( int j = 0; j < 100; j++ ) { for ( int i = 0; i < 100; i++ ) { try ( Transaction transaction = database.beginTx() ) { Node node = database.createNode( testLabel ); node.setProperty( propertyName, RandomStringUtils.randomAlphabetic( 10 ) ); transaction.success(); } } } }

Target:
private void prePopulateDatabase( GraphDatabaseService database, Label testLabel, String propertyName ) { for ( int j = 0; j < 10_000; j++ ) { try ( Transaction transaction = database.beginTx() ) { Node node = database.createNode( testLabel ); node.setProperty( propertyName, RandomStringUtils.randomAlphabetic( 10 ) ); transaction.success(); } } }
Source:
@Test public void binaryCaching() throws Exception { assumeTrue(!platform.equals(TestPlatform.UBUNTU_NO_BINARY)); String os; switch (platform) { case NATIVE: if (Platform.isDarwin()) { os = "darwin"; } else { os = "unix"; } break; default: os = "unix"; } String version = j.getPluginManager().getPlugin("durable-task").getVersion(); version = StringUtils.substringBefore(version, "-"); String binaryName = "durable_task_monitor_" + version + "_" + os + "_64"; FilePath binaryPath = ws.getParent().getParent().child("caches/durable-task/" + binaryName); assertFalse(binaryPath.exists()); BourneShellScript script = new BourneShellScript("echo hello"); EnvVars envVars = new EnvVars(); Controller c = script.launch(envVars, ws, launcher, listener); awaitCompletion(c); assertEquals(0, c.exitStatus(ws, launcher, listener).intValue()); assertTrue(binaryPath.exists()); Long timeCheck1 = binaryPath.lastModified(); c = script.launch(envVars, ws, launcher, listener); awaitCompletion(c); assertEquals(0, c.exitStatus(ws, launcher, listener).intValue()); Long timeCheck2 = binaryPath.lastModified(); assertEquals(timeCheck1, timeCheck2); binaryPath.delete(); binaryPath.touch(Instant.now().toEpochMilli()); try { c = script.launch(envVars, ws, launcher, listener); } catch (Exception e) { assertThat(e, instanceOf(IOException.class)); assertThat(e.getMessage(), containsString("Cannot run program")); } }

Target:
@Test public void binaryCaching() throws Exception { assumeTrue(!platform.equals(TestPlatform.UBUNTU_NO_BINARY)); String os; switch (platform) { case NATIVE: if (Platform.isDarwin()) { os = "darwin"; } else { os = "unix"; } break; default: os = "unix"; } String version = j.getPluginManager().getPlugin("durable-task").getVersion(); version = StringUtils.substringBefore(version, "-"); String binaryName = "durable_task_monitor_" + version + "_" + os + "_64"; FilePath binaryPath = ws.getParent().getParent().child("caches/durable-task/" + binaryName); assertFalse(binaryPath.exists()); BourneShellScript script = new BourneShellScript("echo hello"); EnvVars envVars = new EnvVars(); Controller c = script.launch(envVars, ws, launcher, listener); awaitCompletion(c); assertEquals(0, c.exitStatus(ws, launcher, listener).intValue()); assertTrue(binaryPath.exists()); Long timeCheck1 = binaryPath.lastModified(); c = script.launch(envVars, ws, launcher, listener); awaitCompletion(c); assertEquals(0, c.exitStatus(ws, launcher, listener).intValue()); Long timeCheck2 = binaryPath.lastModified(); assertEquals(timeCheck1, timeCheck2); binaryPath.delete(); binaryPath.touch(Instant.now().toEpochMilli()); try { c = script.launch(envVars, ws, launcher, listener); fail("binary was copied over"); } catch (Exception e) { assertThat(e, instanceOf(IOException.class)); assertThat(e.getMessage(), containsString("Cannot run program")); } }
Source:
private static String getTaskMessage(VDSGroup cluster, StepEnum stepType, GlusterAsyncTask task) { if (task==null) { return null; } Map<String, String> values = getMessageMap(cluster, task); String message = ExecutionMessageDirector.resolveStepMessage(stepType, values); if(message.contains("Total size moved")) { int start = message.lastIndexOf(' ') + 1; int end = message.length() - 1; String sSize = message.substring(start, end); Long size = Long.parseLong(sSize); sSize = SizeConverter.toString(size); StringBuilder tmp = new StringBuilder(message); tmp = tmp.replace(start, end, sSize); message = new String(tmp.toString()); } return message; }

Target:
private static String getTaskMessage(VDSGroup cluster, StepEnum stepType, GlusterAsyncTask task) { if (task==null) { return null; } Map<String, String> values = getMessageMap(cluster, task); return ExecutionMessageDirector.resolveStepMessage(stepType, values); }
Source:
public void onPostReceive(final ReceivePack arg0, final Collection<ReceiveCommand> commands) { for (final ReceiveCommand c : commands) { if (c.getResult() == Result.OK) { if (isHead(c)) { try { sendBypassEmail(c); } catch (EmailException e) { String error_head = ""; switch (c.getType()) { case CREATE: error_head = "Create branch email error: "; break; case DELETE: error_head = "Delete branch email error: "; break; case UPDATE: error_head = "Update branch email error: "; break; } log.error(error_head, e); } } switch (c.getType()) { case CREATE: if (isHead(c)) { autoCloseChanges(c); } break; case UPDATE: tagCache.updateFastForward(project.getNameKey(), c.getRefName(), c.getOldId(), c.getNewId()); if (isHead(c)) { autoCloseChanges(c); } break; case UPDATE_NONFASTFORWARD: if (isHead(c)) { autoCloseChanges(c); } break; } if (isConfig(c)) { projectCache.evict(project); ProjectState ps = projectCache.get(project.getNameKey()); repoManager.setProjectDescription(project.getNameKey(), ps.getProject().getDescription()); } if (!c.getRefName().startsWith(NEW_CHANGE)) { replication.scheduleUpdate(project.getNameKey(), c.getRefName()); Branch.NameKey destBranch = new Branch.NameKey(project.getNameKey(), c.getRefName()); hooks.doRefUpdatedHook(destBranch, c.getOldId(), c.getNewId(), currentUser.getAccount()); } } } if (!allNewChanges.isEmpty() && canonicalWebUrl != null) { final String url = canonicalWebUrl; rp.sendMessage(""); rp.sendMessage("New Changes:"); for (final Change.Id c1 : allNewChanges) { rp.sendMessage(" " + url + c1.get()); } rp.sendMessage(""); } }

Target:
public void onPostReceive(final ReceivePack arg0, final Collection<ReceiveCommand> commands) { for (final ReceiveCommand c : commands) { if (c.getResult() == Result.OK) { if (isHead(c)) { sendBypassEmail(c); } switch (c.getType()) { case CREATE: if (isHead(c)) { autoCloseChanges(c); } break; case UPDATE: tagCache.updateFastForward(project.getNameKey(), c.getRefName(), c.getOldId(), c.getNewId()); if (isHead(c)) { autoCloseChanges(c); } break; case UPDATE_NONFASTFORWARD: if (isHead(c)) { autoCloseChanges(c); } break; } if (isConfig(c)) { projectCache.evict(project); ProjectState ps = projectCache.get(project.getNameKey()); repoManager.setProjectDescription(project.getNameKey(), ps.getProject().getDescription()); } if (!c.getRefName().startsWith(NEW_CHANGE)) { replication.scheduleUpdate(project.getNameKey(), c.getRefName()); Branch.NameKey destBranch = new Branch.NameKey(project.getNameKey(), c.getRefName()); hooks.doRefUpdatedHook(destBranch, c.getOldId(), c.getNewId(), currentUser.getAccount()); } } } if (!allNewChanges.isEmpty() && canonicalWebUrl != null) { final String url = canonicalWebUrl; rp.sendMessage(""); rp.sendMessage("New Changes:"); for (final Change.Id c : allNewChanges) { rp.sendMessage(" " + url + c.get()); } rp.sendMessage(""); } }
Source:
public int getSmsCapacityOnIcc() { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, "getSmsCapacityOnIcc"); int numberOnIcc = -1; if (mPhone.getIccRecordsLoaded()) { final UiccProfile uiccProfile = UiccController.getInstance() .getUiccProfileForPhone(mPhone.getPhoneId()); IccRecords iccRecords = null; if(uiccProfile != null) { iccRecords = uiccProfile.getIccRecords(); } if(uiccProfile != null && iccRecords != null) { numberOnIcc = iccRecords.getSmsCapacityOnIcc(); } else { log("UiccProfile = " + uiccProfile + "IccRecords = " + iccRecords); } } else { log("getSmsCapacityOnIcc - aborting, no icc card present."); } log("getSmsCapacityOnIcc().numberOnIcc = " + numberOnIcc); return numberOnIcc; }

Target:
public int getSmsCapacityOnIcc() { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, "getSmsCapacityOnIcc"); int numberOnIcc = 0; if (mPhone.getIccRecordsLoaded()) { final UiccProfile uiccProfile = UiccController.getInstance() .getUiccProfileForPhone(mPhone.getPhoneId()); IccRecords iccRecords = null; if(uiccProfile != null) { iccRecords = uiccProfile.getIccRecords(); } if(uiccProfile != null && iccRecords != null) { numberOnIcc = iccRecords.getSmsCapacityOnIcc(); } else { log("UiccProfile = " + uiccProfile + "IccRecords = " + iccRecords); } } else { log("getSmsCapacityOnIcc - aborting, no icc card present."); } log("getSmsCapacityOnIcc().numberOnIcc = " + numberOnIcc); return numberOnIcc; }
Source:
private InstructorPermission getInstructorPermissionEntityForEmail(String courseId, String instrEmail) { Query q = getPM().newQuery(InstructorPermission.class); q.declareParameters("String courseIdParam, String emailParam"); q.setFilter("courseId == courseIdParam && instructorEmail == emailParam"); @SuppressWarnings("unchecked") List<InstructorPermission> instructorPermissionList = (List<InstructorPermission>) q.execute(courseId, instrEmail); if (instructorPermissionList.isEmpty() || JDOHelper.isDeleted(instructorPermissionList.get(0))) { return null; } return instructorPermissionList.get(0); }

Target:
private InstructorPermission getInstructorPermissionEntityForEmail(String courseId, String instrEmail) { Query q = getPM().newQuery(InstructorPermission.class); q.declareParameters("String courseIdParam, String emailParam"); q.setFilter("courseId == courseIdParam && instructorEmail == emailParam"); @SuppressWarnings("unchecked") List<InstructorPermission> instructorPermissionList = (List<InstructorPermission>) q.execute(courseId, instrEmail); if (instructorPermissionList.isEmpty() || JDOHelper.isDeleted(instructorPermissionList.get(0))) { return null; } if (instructorPermissionList.size() > 1) { log.severe("Duplicate InstructorPermission Entity: " + courseId + "/" + instrEmail); } return instructorPermissionList.get(0); }
Source:
public void testUpgradeResponseHasReason() { UpgradeV4Request request = new UpgradeV4Request(); when(upgradeAvailabilityService.checkForUpgrade(CLUSTER, WS_ID, request, USER_CRN)).thenReturn(new UpgradeV4Response("reasion", null)); Assertions.assertThrows(BadRequestException.class, () -> underTest.triggerUpgrade(CLUSTER, WS_ID, USER_CRN, request)); }

Target:
public void testUpgradeResponseHasReason() { UpgradeV4Request request = new UpgradeV4Request(); when(upgradeAvailabilityService.checkForUpgrade(CLUSTER, WS_ID, request, USER_CRN)).thenReturn(new UpgradeV4Response("reason", null)); Assertions.assertThrows(BadRequestException.class, () -> underTest.triggerUpgrade(CLUSTER, WS_ID, USER_CRN, request)); }
Source:
public void endElement(TagNode node) { if (isObject(node) && object != null) { if (!object.hasAlternativeContent) { createViolation(object.node.getStartLinePosition(), "Add an accessible content to this \"<object>\" tag."); } object = null; } }

Target:
public void endElement(TagNode node) { if (isObject(node) && object != null) { createViolation(object.getStartLinePosition(), "Add an accessible content to this \"<object>\" tag."); object = null; } }
Source:
private void uploadFileUsingFTPSClient(Operation operation, String host, String ftpUserName, String ftpPassword, String uploadDirectory, String fileLocation, int serverPort) throws AndroidAgentException { FTPSClient ftpsClient = new FTPSClient(); String fileName = null; InputStream inputStream = null; Boolean loginResult = false; String response; try { File file = new File(fileLocation); fileName = file.getName(); ftpsClient.connect(host, serverPort); ftpsClient.enterLocalPassiveMode(); loginResult = ftpsClient.login(ftpUserName, ftpPassword); ftpsClient.execPROT("P"); inputStream = new FileInputStream(file); ftpsClient.changeWorkingDirectory(uploadDirectory); if (ftpsClient.storeFile(fileName, inputStream)) { response = "File uploaded from the device completed."; operation.setStatus(resources.getString(R.string.operation_value_completed)); } else { response = "File uploaded from the device not completed."; operation.setStatus(resources.getString(R.string.operation_value_error)); } operation.setOperationResponse(response); } catch (IOException e) { if (!loginResult) { response = "FTP login failed."; } else { response = fileTransferExceptionHandler(e, fileName); } handleOperationError(operation, response, e); } finally { try { if (ftpsClient.isConnected()) { ftpsClient.logout(); ftpsClient.disconnect(); } } catch (IOException ignored) { } cleanupStreams(inputStream); } }

Target:
private void uploadFileUsingFTPSClient(Operation operation, String host, String ftpUserName, String ftpPassword, String uploadDirectory, String fileLocation, int serverPort) throws AndroidAgentException { FTPSClient ftpsClient = new FTPSClient(); String fileName = null; InputStream inputStream = null; Boolean loginResult = false; String response; try { File file = new File(fileLocation); fileName = file.getName(); ftpsClient.connect(host, serverPort); ftpsClient.enterLocalPassiveMode(); loginResult = ftpsClient.login(ftpUserName, ftpPassword); ftpsClient.execPROT("P"); inputStream = new FileInputStream(file); ftpsClient.changeWorkingDirectory(uploadDirectory); if (ftpsClient.storeFile(fileName, inputStream)) { response = "File uploaded from the device completed ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_completed)); } else { response = "File uploaded from the device not completed ( " + fileName + " )."; operation.setStatus(resources.getString(R.string.operation_value_error)); } operation.setOperationResponse(response); } catch (IOException e) { if (!loginResult) { response = ftpUserName + " - FTP login failed."; } else { response = fileTransferExceptionCause(e, fileName); } handleOperationError(operation, response, e); } finally { try { if (ftpsClient.isConnected()) { ftpsClient.logout(); ftpsClient.disconnect(); } } catch (IOException ignored) { } cleanupStreams(inputStream, null, null, null, null, null, null, null); } }
Source:
public int read (byte[] bytes, int off, int len) throws IOException { if (bytes == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > bytes.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } if (!buf.hasRemaining()) { return -1; } int end = Math.min(len, buf.remaining()); buf.get(bytes, off, end); return end; }

Target:
public int read (byte[] bytes, int off, int len) throws IOException { Preconditions.checkNotNull(bytes, "Given byte array can not be null"); Preconditions.checkPositionIndexes(off, off + len, bytes.length); if (!buf.hasRemaining()) { return -1; } if (len == 0) { return 0; } int end = Math.min(len, buf.remaining()); buf.get(bytes, off, end); return end; }
Source:
private void showRepository(final Repository repository) { if (form.isDisposed()) return; if (repository == null) { form.setText(UIText.RebaseInteractiveView_NoSelection); currentPlan = null; refresh(); return; } if (currentPlan != null) currentPlan.removeRebaseInteractivePlanChangeListener(this); if (planIndexer != null) planIndexer.dispose(); currentPlan = RebaseInteractivePlan.getPlan(repository); planIndexer = new RebasePlanIndexer(currentPlan); currentPlan.addRebaseInteractivePlanChangeListener(this); form.setText(getRepositoryName(repository)); refresh(); }

Target:
private void showRepository(final Repository repository) { if (form.isDisposed()) return; if (currentPlan != null) currentPlan.removeRebaseInteractivePlanChangeListener(this); if (planIndexer != null) planIndexer.dispose(); if (repository != null) { currentPlan = RebaseInteractivePlan.getPlan(repository); planIndexer = new RebasePlanIndexer(currentPlan); currentPlan.addRebaseInteractivePlanChangeListener(this); form.setText(getRepositoryName(repository)); } else { currentPlan = null; planIndexer = null; form.setText(UIText.RebaseInteractiveView_NoSelection); } refresh(); }
Source:
public synchronized void start() throws IllegalStateException, StreamsException { if (setState(State.REBALANCING)) { log.debug("Starting Streams client"); if (globalStreamThread != null) { globalStreamThread.start(); } for (final StreamThread thread : threads) { thread.start(); } final Long cleanupDelay = config.getLong(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG); stateDirCleaner.scheduleAtFixedRate(() -> { if (state == State.RUNNING) { stateDirectory.cleanRemovedTasks(cleanupDelay); } }, cleanupDelay, cleanupDelay, TimeUnit.MILLISECONDS); if (RecordingLevel.forName(config.getString(METRICS_RECORDING_LEVEL_CONFIG)) == RecordingLevel.DEBUG) { rocksDBMetricsRecordingTriggerThread.scheduleAtFixedRate( rocksDBMetricsRecordingTrigger, Duration.ZERO.toMinutes(), Duration.ofMinutes(1).toMinutes(), TimeUnit.MINUTES ); } } else { throw new IllegalStateException("The client is either already started or already stopped, cannot re-start"); } }

Target:
public synchronized void start() throws IllegalStateException, StreamsException { if (setState(State.REBALANCING)) { log.debug("Starting Streams client"); if (globalStreamThread != null) { globalStreamThread.start(); } for (final StreamThread thread : threads) { thread.start(); } final Long cleanupDelay = config.getLong(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG); stateDirCleaner.scheduleAtFixedRate(() -> { if (state == State.RUNNING) { stateDirectory.cleanRemovedTasks(cleanupDelay); } }, cleanupDelay, cleanupDelay, TimeUnit.MILLISECONDS); final long recordingDelay = 0; final long recordingInterval = 1; if (RecordingLevel.forName(config.getString(METRICS_RECORDING_LEVEL_CONFIG)) == RecordingLevel.DEBUG) { rocksDBMetricsRecordingTriggerThread.scheduleAtFixedRate( rocksDBMetricsRecordingTrigger, recordingDelay, recordingInterval, TimeUnit.MINUTES ); } } else { throw new IllegalStateException("The client is either already started or already stopped, cannot re-start"); } }
Source:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder, String subscriptionId) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), subscriptionId, assertion != null ? assertion.getTransactionTimeout() : null); configCNCheck(); }

Target:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder, String subscriptionId) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), subscriptionId, assertion != null ? assertion.getTransactionTimeout() : null); }
Source:
private void checkProblemSubDirectory(File dir) throws AppException { AppExceptionUtil.assertNotNull(dir); File[] files = dir.listFiles(); boolean hasProblemInfo = false; for (File current : files) { String fileName = current.getName(); if ("problemInfo.xml".equals(fileName)) { hasProblemInfo = true; } } if (!hasProblemInfo) { throw new AppException("No description file in problem information directory."); } new ZipDataChecker().check(dir); }

Target:
private void checkProblemSubDirectory(File dir) throws AppException { AppExceptionUtil.assertNotNull(dir); File[] files = dir.listFiles(); boolean hasProblemInfo = false; for (File current : files) { String fileName = current.getName(); if ("problemInfo.xml".equals(fileName)) { hasProblemInfo = true; } } if (!hasProblemInfo) { throw new AppException("No description file in problem information directory."); } zipDataChecker.check(dir); }
Source:
void decodeAttributeBody(byte[] attributeValue, char offset, char length) { while (length >= offset && attributeValue[length] == 0) { length--; } username = new byte[length]; System.arraycopy(attributeValue, offset, username, 0, length); }

Target:
void decodeAttributeBody(byte[] attributeValue, char offset, char length) { while (length > 0 && attributeValue[offset + length] == 0) { length--; } username = new byte[length]; System.arraycopy(attributeValue, offset, username, 0, length); }
Source:
public String getActualName() { return StringUtils.hasText(this.name) ? this.name : this.declaredName; }

Target:
public String getActualName() { return this.actualName; }
Source:
private MenuManager createWindowMenu() { MenuManager menu = new MenuManager( IDEWorkbenchMessages.Workbench_window, IWorkbenchActionConstants.M_WINDOW); addMacWindowMenuItems(menu); menu.add(newWindowAction); menu.add(new Separator()); menu.add(addShowView()); menu.add(addPerspectiveActions()); menu.add(new Separator()); addKeyboardShortcuts(menu); Separator sep = new Separator(IWorkbenchActionConstants.MB_ADDITIONS); sep.setVisible(!Util.isMac()); menu.add(sep); if(Util.isCocoa()) menu.add(arrangeWindowsItem); ActionContributionItem openPreferencesItem = new ActionContributionItem(openPreferencesAction); openPreferencesItem.setVisible(!Util.isMac()); menu.add(openPreferencesItem); String menuProxy = System.getenv("UBUNTU_MENUPROXY"); String desktopSession = System.getenv("DESKTOP_SESSION"); String os = Platform.getOS(); boolean radioButtonsMightCauseCrash = ((menuProxy == null) || !menuProxy.equals("0")) && SWT.getPlatform().equals("gtk") && os.equals(Platform.OS_LINUX) && (desktopSession == null || desktopSession.equals("ubuntu")); if (!radioButtonsMightCauseCrash) { menu.add(ContributionItemFactory.OPEN_WINDOWS.create(getWindow())); } return menu; }

Target:
private MenuManager createWindowMenu() { MenuManager menu = new MenuManager( IDEWorkbenchMessages.Workbench_window, IWorkbenchActionConstants.M_WINDOW); addMacWindowMenuItems(menu); menu.add(newWindowAction); menu.add(new Separator()); menu.add(addShowView()); menu.add(addPerspectiveActions()); menu.add(new Separator()); addKeyboardShortcuts(menu); Separator sep = new Separator(IWorkbenchActionConstants.MB_ADDITIONS); sep.setVisible(!Util.isMac()); menu.add(sep); if(Util.isCocoa()) menu.add(arrangeWindowsItem); ActionContributionItem openPreferencesItem = new ActionContributionItem(openPreferencesAction); openPreferencesItem.setVisible(!Util.isMac()); menu.add(openPreferencesItem); String menuProxy = System.getenv("UBUNTU_MENUPROXY"); String desktopSession = System.getenv("DESKTOP_SESSION"); String os = Platform.getOS(); String ws = Platform.getWS(); boolean workaroundEnabled = !"false".equals(System.getProperty("eclipse.workaround.bug461311")); boolean radioButtonsMightCauseCrash = ((menuProxy == null) || !menuProxy.equals("0")) && Platform.WS_GTK.equals(ws) && Platform.OS_LINUX.equals(os) && (desktopSession == null || desktopSession.equals("ubuntu")) && workaroundEnabled; if (!radioButtonsMightCauseCrash) { menu.add(ContributionItemFactory.OPEN_WINDOWS.create(getWindow())); } return menu; }
Source:
public final boolean canProceed(final K key, final int tokens) { TokenBucket tokenBucket = null; try { tokenBucket = tokenBucketCache.get(key); } catch (ExecutionException e) { LOGGER.error("error=ExecutionException method=canProceed key={} tokens={} exception={}", key, tokens, e); } if (tokenBucket == null) { return false; } return tokenBucket.tryConsume(tokens); }

Target:
public final boolean canProceed(final K key, final int tokens) { TokenBucket tokenBucket = null; try { tokenBucket = tokenBucketCache.get(key); } catch (ExecutionException e) { LOGGER.error("error=ExecutionException method=canProceed key={} tokens={} exception={}", key, tokens, e); } if (tokenBucket == null) { return true; } return tokenBucket.tryConsume(tokens); }