auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean refreshTt(final HttpHost httpHost) { log.debug("Obtaining TT"); final boolean result; final HttpGet getTT = new HttpGet(TOKEN_URL); try { final HttpResponse response = httpClient.execute(httpHost, getTT, context); final int status = response.getStatusLine().getStatusCode(); switch (status) { case HttpStatus.SC_OK: result = true; break; case HttpStatus.SC_UNAUTHORIZED: result = false; break; default: throw new GoodDataAuthException("Unable to obtain TT, HTTP status: " + status); } } catch (IOException e) { throw new GoodDataAuthException("Error during temporary token refresh: " + e.getMessage(), e); } finally { getTT.releaseConnection(); } return result; }

Target:
private boolean refreshTt(final HttpHost httpHost) { log.debug("Obtaining TT"); final boolean result; final HttpGet getTT = new HttpGet(TOKEN_URL); try { final HttpResponse response = httpClient.execute(httpHost, getTT, context); final int status = response.getStatusLine().getStatusCode(); switch (status) { case HttpStatus.SC_OK: return true; case HttpStatus.SC_UNAUTHORIZED: return false; default: throw new GoodDataAuthException("Unable to obtain TT, HTTP status: " + status); } } catch (IOException e) { throw new GoodDataAuthException("Error during temporary token refresh: " + e.getMessage(), e); } finally { getTT.releaseConnection(); } }
Source:
public void beginBlock(BlockType type, Attributes attributes) { pushBlockStrategy(type, attributes).beginBlock(delegate, type, attributes); }

Target:
public void beginBlock(BlockType type, Attributes attributes) { assertCloseImplicitBlock(); pushBlockStrategy(type, attributes).beginBlock(delegate, type, attributes); }
Source:
public TaskDTO getCurrentTaskDTO(ProcessDTO processDTO) { for (TaskDTO task : processDTO.getTasks()) { if (task.getProcessingStatus() == TaskStatus.OPEN || task.getProcessingStatus() == TaskStatus.INWORK) { return task; } } return null; }

Target:
public TaskDTO getCurrentTaskDTO(ProcessDTO processDTO) { for (TaskDTO task : processDTO.getTasks()) { if (task.getProcessingStatus().equals(TaskStatus.OPEN) || task.getProcessingStatus().equals(TaskStatus.INWORK)) { return task; } } return null; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { final List<RepositoryNode> selectedNodes; try { selectedNodes = getSelectedNodes(event); if (selectedNodes.isEmpty()) return null; } catch (ExecutionException e) { Activator.handleError(e.getMessage(), e, true); return null; } Job job = new Job("Collecting Garbage...") { @Override protected IStatus run(IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, selectedNodes.size()); for (RepositoryNode node : selectedNodes) { if (progress.isCanceled()) { break; } Repository repo = node.getRepository(); String name = MessageFormat.format( UIText.GarbageCollectCommand_jobTitle, getRepositoryName(repo)); this.setName(name); final GarbageCollectOperation op = new GarbageCollectOperation( repo); try { op.execute(progress.newChild(1)); } catch (CoreException e) { Activator.logError(MessageFormat.format( UIText.GarbageCollectCommand_failed, repo), e); } } return Status.OK_STATUS; } }; job.setUser(true); IServiceLocator serviceLocator = HandlerUtil.getActiveSite(event); if (serviceLocator != null) { IWorkbenchSiteProgressService service = CommonUtils.getService( serviceLocator, IWorkbenchSiteProgressService.class); service.schedule(job); } else { job.schedule(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { final List<RepositoryNode> selectedNodes; try { selectedNodes = getSelectedNodes(event); if (selectedNodes.isEmpty()) return null; } catch (ExecutionException e) { Activator.handleError(e.getMessage(), e, true); return null; } Job job = new Job("Collecting Garbage...") { @Override protected IStatus run(IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, selectedNodes.size()); for (RepositoryNode node : selectedNodes) { if (progress.isCanceled()) { break; } Repository repo = node.getRepository(); String name = MessageFormat.format( UIText.GarbageCollectCommand_jobTitle, getRepositoryName(repo)); this.setName(name); final GarbageCollectOperation op = new GarbageCollectOperation( repo); try { op.execute(progress.newChild(1)); } catch (CoreException e) { Activator.logError(MessageFormat.format( UIText.GarbageCollectCommand_failed, repo), e); } } monitor.done(); return Status.OK_STATUS; } }; job.setUser(true); IServiceLocator serviceLocator = HandlerUtil.getActiveSite(event); if (serviceLocator != null) { IWorkbenchSiteProgressService service = CommonUtils.getService( serviceLocator, IWorkbenchSiteProgressService.class); service.schedule(job); } else { job.schedule(); } return null; }
Source:
public void setupStateSystem() { try { IStateHistoryBackend backend = null; try { backend = StateHistoryBackendFactory.createHistoryTreeBackendNewFile("test", NonNullUtils.checkNotNull(File.createTempFile("2Dtest", "ht")), 0, START_TIME, 0); } catch (IOException e) { fail(e.getMessage()); } fStateSystem = StateSystemFactory.newStateSystem(NonNullUtils.checkNotNull(backend)); int stringQuark = fStateSystem.getQuarkAbsoluteAndAdd(STRING_ATTRIBUTE); int integerQuark = fStateSystem.getQuarkAbsoluteAndAdd(INTEGER_ATTRIBUTE); fStateSystem.modifyAttribute(60L, TmfStateValue.newValueString("String1"), stringQuark); fStateSystem.modifyAttribute(70L, TmfStateValue.newValueInt(0), integerQuark); fStateSystem.modifyAttribute(80L, TmfStateValue.newValueInt(1), integerQuark); fStateSystem.modifyAttribute(90L, TmfStateValue.newValueString("String2"), stringQuark); fStateSystem.modifyAttribute(100L, TmfStateValue.newValueInt(2), integerQuark); fStateSystem.modifyAttribute(110L, TmfStateValue.newValueInt(3), integerQuark); fStateSystem.modifyAttribute(130L, TmfStateValue.newValueString("String3"), stringQuark); fStateSystem.modifyAttribute(140L, TmfStateValue.newValueString("String4"), stringQuark); fStateSystem.modifyAttribute(160L, TmfStateValue.newValueInt(4), integerQuark); fStateSystem.closeHistory(200L); } catch (StateValueTypeException e) { fail(e.getMessage()); } }

Target:
public void setupStateSystem() throws IOException { IStateHistoryBackend backend = StateHistoryBackendFactory.createHistoryTreeBackendNewFile("test", NonNullUtils.checkNotNull(File.createTempFile("2Dtest", "ht")), 0, START_TIME, 0); fStateSystem = StateSystemFactory.newStateSystem(NonNullUtils.checkNotNull(backend)); int stringQuark = fStateSystem.getQuarkAbsoluteAndAdd(STRING_ATTRIBUTE); int integerQuark = fStateSystem.getQuarkAbsoluteAndAdd(INTEGER_ATTRIBUTE); fStateSystem.modifyAttribute(60L, "String1", stringQuark); fStateSystem.modifyAttribute(70L, 0, integerQuark); fStateSystem.modifyAttribute(80L, 1, integerQuark); fStateSystem.modifyAttribute(90L, "String2", stringQuark); fStateSystem.modifyAttribute(100L, 2, integerQuark); fStateSystem.modifyAttribute(110L, 3, integerQuark); fStateSystem.modifyAttribute(130L, "String3", stringQuark); fStateSystem.modifyAttribute(140L, "String4", stringQuark); fStateSystem.modifyAttribute(160L, 4, integerQuark); fStateSystem.closeHistory(200L); }
Source:
public ActionForward editDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AssociatedObjectsBean bean = getRenderedObject(); atomic(() -> { Department d = bean.getDepartment(); d.setCode(bean.getCode()); d.setName(bean.getName()); d.setRealName(bean.getRealName()); d.setRealNameEn(bean.getRealNameEn()); d.setCompetenceCourseMembersGroup(Group.parse(bean.getUsername())); }); return list(mapping, form, request, response); }

Target:
public ActionForward editDepartment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AssociatedObjectsBean bean = getRenderedObject(); atomic(() -> { Department d = bean.getDepartment(); d.setCode(bean.getCode()); d.setName(bean.getName()); d.setRealName(bean.getRealName()); d.setRealNameEn(bean.getRealNameEn()); d.setCompetenceCourseMembersGroup(Group.parse(bean.getMembersGroupExpression())); }); return list(mapping, form, request, response); }
Source:
Set<Long> getFileSizeSet() { rwLock.readLock().lock(); try { return internalMap.keySet(); } finally { rwLock.readLock().unlock(); } }

Target:
Set<Long> getFileSizeSet() { return internalMap.keySet(); }
Source:
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl sess, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { List<String> resolvingMessages = new ArrayList<>(); if (message == null) return resolvingMessages; Matcher addUserExtSourceMatcher = addUserExtSource.matcher(message); Matcher removeUserExtSourceMatcher = removeUserExtSource.matcher(message); Matcher extSourceRemsMatcher = extSourceRems.matcher(message); Matcher affiliationsAttributeMatcher = affiliationsAttribute.matcher(message); User user; Attribute attrVirtRemsLogins; if (affiliationsAttributeMatcher.find() || ( extSourceRemsMatcher.find() && (addUserExtSourceMatcher.find() || removeUserExtSourceMatcher.find()))) { user = (new ModulesUtilsBlImpl()).getUserFromMessage(sess, message); if (user != null) { attrVirtRemsLogins = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, AttributesManager.NS_USER_ATTR_VIRT + ":elixirBonaFideStatus"); String messageAttributeSet = attrVirtRemsLogins.serializeToString() + " set for " + user.serializeToString() + "."; resolvingMessages.add(messageAttributeSet); } } return resolvingMessages; }

Target:
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl sess, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { List<String> resolvingMessages = new ArrayList<>(); if (message == null) return resolvingMessages; Matcher userSetMatcher = userSetPattern.matcher(message); Matcher userRemoveMatcher = userRemovePattern.matcher(message); Matcher userAllAttrsRemovedMatcher = userAllAttrsRemovedPattern.matcher(message); Matcher uesAllAttrsRemovedMatcher = uesAllAttrsRemovedPattern.matcher(message); Matcher uesSetAffiliationAttributeMatcher = uesSetAffiliationAttributePattern.matcher(message); Matcher uesRemoveAffiliationAttributeMatcher = uesRemoveAffiliationAttributePattern.matcher(message); User user; Attribute attribute; if (uesSetAffiliationAttributeMatcher.find() || uesRemoveAffiliationAttributeMatcher.find() || uesAllAttrsRemovedMatcher.find() || userSetMatcher.find() || userRemoveMatcher.find() || userAllAttrsRemovedMatcher.find()) { user = sess.getPerunBl().getModulesUtilsBl().getUserFromMessage(sess, message); if (user != null) { String messageAttributeSet; attribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, AttributesManager.NS_USER_ATTR_VIRT + ":" + FRIENDLY_NAME); String value = (String) attribute.getValue(); if (value == null || value.isEmpty()) { AttributeDefinition attributeDefinition = new AttributeDefinition(attribute); messageAttributeSet = attributeDefinition.serializeToString() + " removed for " + user.serializeToString() + "."; } else { messageAttributeSet = attribute.serializeToString() + " set for " + user.serializeToString() + "."; } resolvingMessages.add(messageAttributeSet); } else { log.error("Failed to get user from message: {}", message); } } return resolvingMessages; }
Source:
private String getFileExtFromMimeType(String mimeType) throws MimeTypeException { MimeTypes allTypes = MimeTypes.getDefaultMimeTypes(); return allTypes.forName(mimeType).getExtension(); }

Target:
private String getFileExtFromMimeType(String mimeType) throws MimeTypeException { MimeTypes allTypes = MimeTypes.getDefaultMimeTypes(); String fileExt = allTypes.forName(mimeType).getExtension(); if (StringUtils.isEmpty(fileExt)) { LOGGER.debug("Null or empty file extension from mime-type {}", mimeType); } return fileExt; }
Source:
public static boolean isFloatingLabel(EObject notationElement) { if (!(notationElement instanceof DecorationNode)) { return false; } DecorationNode node = (DecorationNode) notationElement; if (node instanceof BasicCompartment) { return false; } if (node.eContainer() instanceof Connector) { return true; } if (node.eContainer() instanceof Shape) { if (node.getLayoutConstraint() != null) { return true; } } return false; }

Target:
public boolean isFloatingLabel(EObject notationElement) { if (!(notationElement instanceof DecorationNode)) { return false; } DecorationNode node = (DecorationNode) notationElement; if (node instanceof BasicCompartment) { return false; } if (node.eContainer() instanceof Connector) { return true; } if (node.eContainer() instanceof Shape) { if (node.getLayoutConstraint() != null) { return true; } } return false; }
Source:
private static String getTitleText(Map<String, Object> figureMetadata) { String title = TextUtil.sanitizeWhitespace((String) figureMetadata.get("title")); String description = TextUtil.sanitizeWhitespace((String) figureMetadata.get("description")); Matcher titleElement = TITLE_EXTRACTOR.matcher(description); if (!titleElement.find()) { return title + "."; } String descriptionTitleText = titleElement.group(1); descriptionTitleText = TextUtil.removeMarkup(descriptionTitleText); return String.format("%s. %s", title, descriptionTitleText); }

Target:
private static String getTitleText(Map<String, Object> figureMetadata) { String title = TextUtil.sanitizeWhitespace((String) figureMetadata.get("title")); String description = TextUtil.sanitizeWhitespace((String) figureMetadata.get("description")); Matcher titleElement = TITLE_EXTRACTOR.matcher(description); if (!titleElement.find()) { return title.isEmpty() ? "" : (title + "."); } String descriptionTitleText = titleElement.group(1); descriptionTitleText = TextUtil.removeMarkup(descriptionTitleText); return String.format("%s. %s", title, descriptionTitleText); }
Source:
public ImageAdapter(Context c) { mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); path = imagelist.split("#"); if (path.length > 0) { noPhotos.setVisibility(View.GONE); Log.e("Hi", "Removing"); } }

Target:
public ImageAdapter(Context c) { mInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); path = imagelist.split("#"); if (path.length > 0) { noPhotos.setVisibility(View.GONE); } }
Source:
public String toString() { return MoreObjects.toStringHelper("") .add("ChannelKey", mChannelKey) .add("ChannelHealthy", isHealthy()) .add("ChannelReleased", mChannelReleased) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("ChannelKey", mChannelKey) .add("ChannelHealthy", isHealthy()) .add("ChannelReleased", mChannelReleased) .toString(); }
Source:
static Duration getFsTimestampResolution(Path file) { try { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!Files.exists(dir) || !dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } FileStore s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c == null) { c = new FileStoreAttributeCache(dir); attributeCache.put(s, c); if (LOG.isDebugEnabled()) { LOG.debug(c.toString()); } } return c.getFsTimestampResolution(); } catch (IOException | InterruptedException e) { LOG.warn(e.getMessage(), e); return FALLBACK_TIMESTAMP_RESOLUTION; } }

Target:
static Duration getFsTimestampResolution(Path file) { try { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } FileStore s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c == null) { c = new FileStoreAttributeCache(dir); attributeCache.put(s, c); if (LOG.isDebugEnabled()) { LOG.debug(c.toString()); } } return c.getFsTimestampResolution(); } catch (IOException | InterruptedException e) { LOG.warn(e.getMessage(), e); return FALLBACK_TIMESTAMP_RESOLUTION; } }
Source:
public void linkingObjects_IllegalStateException_ifNotYetLoaded() { final Realm realm = looperThread.realm; realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { final BacklinksTarget target1 = realm.createObject(BacklinksTarget.class); target1.setId(1); final BacklinksSource source = realm.createObject(BacklinksSource.class); source.setChild(target1); } }); final DynamicRealm dynamicRealm = DynamicRealm.getInstance(looperThread.realmConfiguration); try { final DynamicRealmObject targetAsync = dynamicRealm.where(BacklinksTarget.CLASS_NAME) .equalTo(BacklinksTarget.FIELD_ID, 1L).findFirstAsync(); assertFalse(targetAsync.isLoaded()); thrown.expect(IllegalStateException.class); targetAsync.linkingObjects(BacklinksSource.CLASS_NAME, BacklinksSource.FIELD_CHILD); fail(); } finally { dynamicRealm.close(); } }

Target:
public void linkingObjects_IllegalStateException_ifNotYetLoaded() { final Realm realm = looperThread.getRealm(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { final BacklinksTarget target1 = realm.createObject(BacklinksTarget.class); target1.setId(1); final BacklinksSource source = realm.createObject(BacklinksSource.class); source.setChild(target1); } }); final DynamicRealm dynamicRealm = DynamicRealm.getInstance(looperThread.getConfiguration()); try { final DynamicRealmObject targetAsync = dynamicRealm.where(BacklinksTarget.CLASS_NAME) .equalTo(BacklinksTarget.FIELD_ID, 1L).findFirstAsync(); assertFalse(targetAsync.isLoaded()); thrown.expect(IllegalStateException.class); targetAsync.linkingObjects(BacklinksSource.CLASS_NAME, BacklinksSource.FIELD_CHILD); } finally { dynamicRealm.close(); } }
Source:
private void checkConnection() { if (getThing().getStatus() != ThingStatus.ONLINE) { openConnection(); } if (getThing().getStatus() == ThingStatus.ONLINE && this.session != null && this.session.isOpen()) { try { this.session.getRemote().sendPing(null); this.missedPongsCount.countDown(); } catch (IOException | NullPointerException | UnsupportedOperationException e) { logger.warn("Sending websocket PING failed."); onWebSocketError(e); closeConnection(); openConnection(); } } }

Target:
private void checkConnection() { if (getThing().getStatus() != ThingStatus.ONLINE) { openConnection(); } if (getThing().getStatus() == ThingStatus.ONLINE && this.session != null && this.session.isOpen()) { try { this.session.getRemote().sendPing(null); missedPongsCount++; } catch (IOException | NullPointerException e) { onWebSocketError(e); closeConnection(); openConnection(); } if (missedPongsCount == MAX_MISSED_PONGS_COUNT) { missedPongsCount = 0; closeConnection(); openConnection(); } } }
Source:
private static List<ReadRowsResponse> createResponses(int cellCount) { Builder readRowsResponse = ReadRowsResponse.newBuilder(); int size = 100_000 / cellCount; for (int i = 0; i < cellCount; i++) { CellChunk contentChunk = CellChunk.newBuilder() .setFamilyName(StringValue.newBuilder().setValue("Family" + i)) .setQualifier(BytesValue.newBuilder().setValue(ByteString.copyFromUtf8("Qaulifier"))) .setRowKey(ByteString.copyFrom(Bytes.toBytes("rowkey-0"))) .setValue(ByteString.copyFrom(RandomStringUtils.randomAlphanumeric(size).getBytes())) .setTimestampMicros(0L) .setCommitRow(i == cellCount - 1) .build(); readRowsResponse.addChunks(contentChunk); } return Arrays.asList(readRowsResponse.build()); }

Target:
private static List<ReadRowsResponse> createResponses(int cellCount) { Builder readRowsResponse = ReadRowsResponse.newBuilder(); Preconditions.checkArgument(cellCount > 0, "cellCount has to be > 0."); int size = 100_000 / cellCount; Preconditions.checkArgument(size > 0, "size has to be > 0."); for (int i = 0; i < cellCount; i++) { CellChunk contentChunk = CellChunk.newBuilder() .setFamilyName(StringValue.newBuilder().setValue("Family" + i)) .setQualifier(BytesValue.newBuilder().setValue(ByteString.copyFromUtf8("Qualifier"))) .setRowKey(ByteString.copyFrom(Bytes.toBytes("rowkey-0"))) .setValue(ByteString.copyFrom(RandomStringUtils.randomAlphanumeric(size).getBytes())) .setTimestampMicros(0L) .setCommitRow(i == cellCount - 1) .build(); readRowsResponse.addChunks(contentChunk); } return Arrays.asList(readRowsResponse.build()); }
Source:
private List<Entity> retrieveSurveyForms(DatastoreService ds, Long surveyId) { Filter surveyFilter = new Query.FilterPredicate("surveyGroupId", FilterOperator.EQUAL, surveyId); Query q = new Query(FORM_KIND).setFilter(surveyFilter); List<Entity> surveyForms = new ArrayList<Entity>(); for (Entity survey : ds.prepare(q).asIterable()) { surveyForms.add(survey); } return surveyForms; }

Target:
private List<Entity> retrieveSurveyForms(DatastoreService ds, Long surveyId) { Filter surveyFilter = new Query.FilterPredicate("surveyGroupId", FilterOperator.EQUAL, surveyId); Query q = new Query(FORM_KIND).setFilter(surveyFilter); return ds.prepare(q).asList(FetchOptions.Builder.withDefaults()); }
Source:
public static void putAsJson(String path, JsonNode data, EtcdClient etcdClient) throws IOException, EtcdAuthenticationException, TimeoutException, EtcdException { Map<String, Object> flattened = new JsonFlattener(EtcdUtil.jsonToString(data)) .withFlattenMode(FlattenMode.MONGODB) .withSeparator('/') .withKeyTransformer(s -> s.replaceAll("\\.", "__DOT__")) .flattenAsMap(); try { etcdClient.delete(path).recursive().send().get(); } catch (EtcdException e) { if (EtcdErrorCode.KeyNotFound != e.errorCode) { throw e; } } for (Map.Entry<String, Object> entry : flattened.entrySet()) { etcdClient.put(path + "/" + entry.getKey(), String.valueOf(entry.getValue())).send().get(); } }

Target:
public static void putAsJson(String path, JsonNode data, EtcdClient etcdClient) throws IOException, EtcdAuthenticationException, TimeoutException, EtcdException { Map<String, Object> flattened = new JsonFlattener(EtcdUtil.jsonToString(data)) .withFlattenMode(FlattenMode.MONGODB) .withSeparator('/') .withKeyTransformer(new KeyTransformer() { @Override public String transform(String s) { return s.replaceAll("\\.", "__DOT__"); } }) .flattenAsMap(); try { etcdClient.delete(path).recursive().send().get(); } catch (EtcdException e) { if (EtcdErrorCode.KeyNotFound != e.errorCode) { throw e; } } for (Map.Entry<String, Object> entry : flattened.entrySet()) { etcdClient.put(path + "/" + entry.getKey(), String.valueOf(entry.getValue())).send().get(); } }
Source:
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception { String jvmAlias; switch (pathChildrenCacheEvent.getType()) { case CHILD_ADDED: log.debug(ZookeeperClusterService.this.clConfig.getWorkerAlias() + " Node added: " + ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath())); jvmAlias = ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath()); if (!ZookeeperClusterService.this.jvmHandlers.containsKey(jvmAlias)) { ZookeeperJvmHandler handler = new ZookeeperJvmHandler( jvmAlias, ZookeeperClusterService.this.clClient, clConfig); handler.initialize(); ZookeeperClusterService.this.jvmHandlers.put(jvmAlias, handler); } break; case CHILD_UPDATED: log.debug(clConfig.getWorkerAlias() + " Node upadet: " + ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath())); break; case CHILD_REMOVED: jvmAlias = ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath()); if (ZookeeperClusterService.this.jvmHandlers.containsKey(jvmAlias)) { ZookeeperClusterService.this.jvmHandlers.get(jvmAlias).dispose(); ZookeeperClusterService.this.jvmHandlers.remove(jvmAlias); } log.debug(clConfig.getWorkerAlias() + " Node removed: " + ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath())); break; } }

Target:
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception { String jvmAlias; switch (pathChildrenCacheEvent.getType()) { case CHILD_ADDED: log.debug("{} Node added: {}", clConfig.getWorkerAlias(), ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath())); jvmAlias = ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath()); if (!this.jvmHandlers.containsKey(jvmAlias)) { ZookeeperJvmHandler handler = new ZookeeperJvmHandler( jvmAlias, clClient, clConfig, zookeeperClusterService); jvmHandlers.put(jvmAlias, handler); } break; case CHILD_UPDATED: log.debug(clConfig.getWorkerAlias() + " Node update: " + ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath())); break; case CHILD_REMOVED: jvmAlias = ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath()); ZookeeperJvmHandler jvmHandler = jvmHandlers.remove(jvmAlias); if (jvmHandler != null) jvmHandler.close(); log.debug("{} Node removed: {}", clConfig.getWorkerAlias(), ZKPaths.getNodeFromPath(pathChildrenCacheEvent.getData().getPath())); break; default: throw new IllegalArgumentException("Unknown event type: " + pathChildrenCacheEvent.getType()); } }
Source:
private Mono<Void> sendClientTelemetry() { return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec)) .flatMap(t -> { if (this.isClosed) { logger.warn("client already closed"); return Mono.empty(); } if(!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) { logger.trace("client telemetry not enabled"); return Mono.empty(); } readHistogram(); try { logger.info("ClientTelemetry {}", OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo)); } catch (JsonProcessingException e) { e.printStackTrace(); } clearDataForNextRun(); return this.sendClientTelemetry(); }).onErrorResume(ex -> { logger.error("sendClientTelemetry() - Unable to send client telemetry" + ". Exception: {}", ex.toString(), ex); clearDataForNextRun(); return this.sendClientTelemetry(); }).subscribeOn(scheduler); }

Target:
private Mono<Void> sendClientTelemetry() { return Mono.delay(Duration.ofSeconds(clientTelemetrySchedulingSec)) .flatMap(t -> { if (this.isClosed) { logger.warn("client already closed"); return Mono.empty(); } if(!Configs.isClientTelemetryEnabled(this.isClientTelemetryEnabled)) { logger.trace("client telemetry not enabled"); return Mono.empty(); } readHistogram(); try { logger.info("ClientTelemetry {}", OBJECT_MAPPER.writeValueAsString(this.clientTelemetryInfo)); } catch (JsonProcessingException e) { logger.error("Error which parsing client telemetry into json. ", e); } clearDataForNextRun(); return this.sendClientTelemetry(); }).onErrorResume(ex -> { logger.error("sendClientTelemetry() - Unable to send client telemetry" + ". Exception: ", ex); clearDataForNextRun(); return this.sendClientTelemetry(); }).subscribeOn(scheduler); }
Source:
public void scanFile(JavaFileScannerContext context) { occurrences.clear(); constants.clear(); scan(context.getTree()); for (String entry : occurrences.keySet()) { Collection<LiteralTree> literalTrees = occurrences.get(entry); boolean allInConstants = context.getSemanticModel() != null && literalTrees.stream().allMatch(t -> { if (t.parent().is(Tree.Kind.VARIABLE)) { Symbol symbol = ((VariableTree) t.parent()).symbol(); return symbol.isStatic() && symbol.isFinal(); } return false; }); if(allInConstants) { continue; } int literalOccurrence = literalTrees.size(); if (constants.containsKey(entry) && literalOccurrence > 1) { VariableTree constant = constants.get(entry); List<LiteralTree> duplications = literalTrees.stream().filter(literal -> literal.parent() != constant).collect(Collectors.toList()); context.reportIssue(this, duplications.iterator().next(), "Use already-defined constant '" + constant.simpleName() + "' instead of duplicating its value here.", secondaryLocations(duplications.subList(1, duplications.size())), literalOccurrence); } else if (literalOccurrence >= threshold) { context.reportIssue( this, literalTrees.iterator().next(), "Define a constant instead of duplicating this literal " + entry + " " + literalOccurrence + " times.", secondaryLocations(literalTrees), literalOccurrence); } } }

Target:
public void scanFile(JavaFileScannerContext context) { occurrences.clear(); constants.clear(); scan(context.getTree()); for (String entry : occurrences.keySet()) { Collection<LiteralTree> literalTrees = occurrences.get(entry); int literalOccurrence = literalTrees.size(); if (constants.containsKey(entry) && literalOccurrence > 0) { VariableTree constant = constants.get(entry); List<LiteralTree> duplications = literalTrees.stream().filter(literal -> literal.parent() != constant).collect(Collectors.toList()); context.reportIssue(this, duplications.iterator().next(), "Use already-defined constant '" + constant.simpleName() + "' instead of duplicating its value here.", secondaryLocations(duplications.subList(1, duplications.size())), literalOccurrence); } else if (literalOccurrence >= threshold) { context.reportIssue( this, literalTrees.iterator().next(), "Define a constant instead of duplicating this literal " + entry + " " + literalOccurrence + " times.", secondaryLocations(literalTrees), literalOccurrence); } } }
Source:
public PropertyRest findOne(Context context, String property) { if (!exposedProperties.contains(property) || configurationService.getArrayProperty(property).length == 0) { throw new ResourceNotFoundException("No such configuration property: " + property); } String[] propertyValues = configurationService.getArrayProperty(property); PropertyRest propertyRest = new PropertyRest(); propertyRest.setName(property); propertyRest.setValues(Arrays.asList(propertyValues)); return propertyRest; }

Target:
public PropertyRest findOne(Context context, String property) { if (!exposedProperties.contains(property) || !configurationService.hasProperty(property)) { throw new ResourceNotFoundException("No such configuration property: " + property); } String[] propertyValues = configurationService.getArrayProperty(property); PropertyRest propertyRest = new PropertyRest(); propertyRest.setName(property); propertyRest.setValues(Arrays.asList(propertyValues)); return propertyRest; }
Source:
public GitHubRepositoryList createRepositoriesList() throws IOException { GitHubRepositoryList dtoRepositoriesList = DtoFactory.getInstance().createDto(GitHubRepositoryList.class); return dtoRepositoriesList; }

Target:
public GitHubRepositoryList createRepositoriesList() throws IOException { return DtoFactory.getInstance().createDto(GitHubRepositoryList.class); }
Source:
private List<String> getNewWarnings(List<PrestoWarning> warnings) { int end; if (maxWarnings.isPresent()) { end = Math.min(processedWarnings + maxWarnings.getAsInt(), warnings.size()); } else { end = warnings.size(); } List<String> subList = warnings.subList(processedWarnings, end).stream() .map(this::getWarningMessage) .collect(toImmutableList()); processedWarnings = end; return subList; }

Target:
private List<String> getNewWarnings(List<PrestoWarning> warnings) { int end = warnings.size(); if (maxWarnings.isPresent()) { end = Math.min(processedWarnings + maxWarnings.getAsInt(), end); } List<String> subList = warnings.subList(processedWarnings, end).stream() .map(this::getWarningMessage) .collect(toImmutableList()); processedWarnings = end; return subList; }
Source:
protected void executeCommand() { StorageDomainDR storageDomainDR = storageDomainDRDao.get(getParameters().getStorageDomainId(), getParameters().getGeoRepSessionId()); if (storageDomainDR == null) { storageDomainDR = new StorageDomainDR(); storageDomainDR.setStorageDomainId(getParameters().getStorageDomainId()); storageDomainDR.setGeoRepSessionId(getParameters().getGeoRepSessionId()); } else { if (storageDomainDR.getJobId() != null) { schedulerUtil.deleteJob(storageDomainDR.getJobId()); } } if (getParameters().getSchedule().getFrequency() != StorageSyncSchedule.Frequency.NONE) { String jobId = schedulerUtil.scheduleACronJob(GlusterStorageDomainDRSyncJob.class, "syncData", new Class[] { String.class, String.class }, new Object[] { getParameters().getStorageDomainId().toString(), getParameters().getGeoRepSessionId().toString() }, getParameters().getSchedule().getCronExpression()); storageDomainDR.setScheduleCronExpression(getParameters().getSchedule().getCronExpression()); storageDomainDR.setJobId(jobId); storageDomainDRDao.saveOrUpdate(storageDomainDR); } else { storageDomainDRDao.remove(storageDomainDR.getStorageDomainId(), storageDomainDR.getGeoRepSessionId()); } setSucceeded(true); }

Target:
protected void executeCommand() { StorageDomainDR storageDomainDR = storageDomainDRDao.get(getParameters().getStorageDomainId(), getParameters().getGeoRepSessionId()); if (storageDomainDR == null) { storageDomainDR = new StorageDomainDR(); storageDomainDR.setStorageDomainId(getParameters().getStorageDomainId()); storageDomainDR.setGeoRepSessionId(getParameters().getGeoRepSessionId()); } else { if (storageDomainDR.getJobId() != null) { schedulerUtil.deleteJob(storageDomainDR.getJobId()); } } if (getParameters().getSchedule().getFrequency() != StorageSyncSchedule.Frequency.NONE) { String jobId = schedulerUtil.scheduleACronJob(new GlusterStorageDomainDRSyncJob(), "syncData", new Class[] { String.class, String.class }, new Object[] { getParameters().getStorageDomainId().toString(), getParameters().getGeoRepSessionId().toString() }, getParameters().getSchedule().toCronExpression()); storageDomainDR.setScheduleCronExpression(getParameters().getSchedule().toCronExpression()); storageDomainDR.setJobId(jobId); storageDomainDRDao.saveOrUpdate(storageDomainDR); } else { storageDomainDRDao.remove(storageDomainDR.getStorageDomainId(), storageDomainDR.getGeoRepSessionId()); } setSucceeded(true); }
Source:
private List<EnvironmentInfo> getStrongboxInfo() { List<EnvironmentInfo> strongboxInfo = new ArrayList(); Map<String, Storage> storageMap = getConfiguration().getStorages(); Long repositoriesCount = storageMap.values() .stream() .map(e -> e.getRepository(e.getId())) .count(); strongboxInfo.add(new EnvironmentInfo("repositories", String.valueOf(repositoriesCount))); Long storagesCount = storageMap.values() .stream() .count(); strongboxInfo.add(new EnvironmentInfo("storages", String.valueOf(storagesCount))); Long usersCount = userService.getUsers(null, null) .getUsers() .stream() .count(); strongboxInfo.add(new EnvironmentInfo("users", String.valueOf(usersCount))); return strongboxInfo; }

Target:
private List<EnvironmentInfo> getStrongboxInfo() { List<EnvironmentInfo> strongboxInfo = new ArrayList(); Map<String, Storage> storageMap = getConfiguration().getStorages(); Long repositoriesCount = storageMap.values() .stream() .map(e -> e.getRepository(e.getId())) .count(); strongboxInfo.add(new EnvironmentInfo("repositories", String.valueOf(repositoriesCount))); Long storagesCount = storageMap.values() .stream() .count(); strongboxInfo.add(new EnvironmentInfo("storages", String.valueOf(storagesCount))); Long usersCount = 0L; strongboxInfo.add(new EnvironmentInfo("users", String.valueOf(usersCount))); return strongboxInfo; }
Source:
private void assertAsSetContainsAll(MetricTarget... targets) { assertContainsAll(asSet(targets), asList(targets)); }

Target:
private void assertAsSetContainsAll(MetricTarget... targets) { assertContainsAll(MetricTarget.asSet(targets), asList(targets)); }
Source:
private Map<String, AttributeValueUpdate> generateAlarmUpdateItem(final List<Alarm> newAlarmList, final List<Alarm> oldAlarmList, final DateTimeZone userTimeZone){ final ObjectMapper mapper = new ObjectMapper(); final Map<String, AttributeValueUpdate> items = new HashMap<>(); final DateTime now = DateTime.now().withZone(userTimeZone); if(shouldUpdateRingTime(oldAlarmList, newAlarmList, userTimeZone, now)) { final Map<String, AttributeValueUpdate> ringTimeUpdateItems = appendRingTimeUpdateItem(newAlarmList, userTimeZone, now); items.putAll(ringTimeUpdateItems); } final String alarmListJSON; try { alarmListJSON = mapper.writeValueAsString(newAlarmList); } catch (JsonProcessingException e) { LOGGER.error("Deserialize alarmList error: {}", e.getMessage()); return Collections.EMPTY_MAP; } items.put(ALARM_TEMPLATES_ATTRIBUTE_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue().withS(alarmListJSON))); return items; }

Target:
private Map<String, AttributeValueUpdate> generateAlarmUpdateItem(final List<Alarm> newAlarmList, final List<Alarm> oldAlarmList, final DateTimeZone userTimeZone){ final Map<String, AttributeValueUpdate> items = new HashMap<>(); final DateTime now = DateTime.now().withZone(userTimeZone); if(shouldUpdateRingTime(oldAlarmList, newAlarmList, userTimeZone, now)) { final Map<String, AttributeValueUpdate> ringTimeUpdateItems = appendRingTimeUpdateItem(newAlarmList, userTimeZone, now); items.putAll(ringTimeUpdateItems); } final String alarmListJSON; try { alarmListJSON = this.objectMapper.writeValueAsString(newAlarmList); } catch (JsonProcessingException e) { LOGGER.error("Deserialize alarmList error: {}", e.getMessage()); return Collections.EMPTY_MAP; } items.put(ALARM_TEMPLATES_ATTRIBUTE_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue().withS(alarmListJSON))); return items; }
Source:
public void testGenericWordConstainsString() { StopList sut = new StopList(); boolean containsWord = sut.contains("and"); assertTrue(containsWord); }

Target:
public void testGenericWordConstainsString() { StopList sut = new StopList(); boolean containsWord = sut.contains("and"); assertTrue("Determine if stopword as string is contained", containsWord); }
Source:
public static String getDevMachineName(Environment envConfig) { for (Map.Entry<String, ? extends MachineConfig> entry : envConfig.getMachines().entrySet()) { List<String> installers = entry.getValue().getInstallers(); if (InstallerFqn.idInKeyList(WSAGENT_INSTALLER, installers)) { return entry.getKey(); } } return null; }

Target:
public static String getDevMachineName(Environment envConfig) { for (Map.Entry<String, ? extends MachineConfig> entry : envConfig.getMachines().entrySet()) { if (isDev(entry.getValue())) { return entry.getKey(); } } return null; }
Source:
public GerritHandler(int numberOfWorkerThreads, int threadKeepAliveTime) { this.numberOfWorkerThreads = numberOfWorkerThreads; if (threadKeepAliveTime < MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME) { threadKeepAliveTime = MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME; } this.threadKeepAliveTime = threadKeepAliveTime; startQueue(); }

Target:
public GerritHandler(int numberOfWorkerThreads, int threadKeepAliveTime) { this.numberOfWorkerThreads = numberOfWorkerThreads; this.threadKeepAliveTime = Math.max(MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME, threadKeepAliveTime); startQueue(); }
Source:
void testEncodingWithEmptyMetadata() { ByteBuf frame = RequestStreamFrameFlyweight.encode( ByteBufAllocator.DEFAULT, 1, false, 1, Unpooled.EMPTY_BUFFER, Unpooled.copiedBuffer("d", StandardCharsets.UTF_8)); frame = FrameLengthFlyweight.encode(ByteBufAllocator.DEFAULT, frame.readableBytes(), frame); assertEquals("00000b0000000118000000000164", ByteBufUtil.hexDump(frame)); frame.release(); }

Target:
void testEncodingWithEmptyMetadata() { ByteBuf frame = RequestStreamFrameFlyweight.encode( ByteBufAllocator.DEFAULT, 1, false, 1, Unpooled.EMPTY_BUFFER, Unpooled.copiedBuffer("d", StandardCharsets.UTF_8)); frame = FrameLengthFlyweight.encode(ByteBufAllocator.DEFAULT, frame.readableBytes(), frame); assertEquals("00000e0000000119000000000100000064", ByteBufUtil.hexDump(frame)); frame.release(); }
Source:
private void interpretCommandStatus(String status, ResultHandler handler) { long oid = 0; long count = 0; int marker1 = -1; int marker2 = -1; if (status.indexOf(" ") != -1) { for (int i = status.length() - 1; i >= 0; i--) { if (Character.isDigit(status.charAt(i))) { } else if (status.charAt(i) == ' ') { if (marker1 == -1) { marker1 = i; } else { marker2 = i; } } else { break; } } } if (marker1 != -1) { try { if (marker2 != -1) { oid = Long.parseLong(status.substring(marker2 + 1, marker1)); count = Long.parseLong(status.substring(marker1 + 1)); } else { count = Long.parseLong(status.substring(marker1 + 1)); } } catch (NumberFormatException e) { handler.handleError(new PSQLException( GT.tr("Unable to parse the count in command completion tag: {0}.", status), PSQLState.CONNECTION_FAILURE)); return; } } int countAsInt = 0; if (count > Integer.MAX_VALUE) { countAsInt = Statement.SUCCESS_NO_INFO; } else if (count > 0) { countAsInt = (int) count; } handler.handleCommandStatus(status, countAsInt, oid); }

Target:
private void interpretCommandStatus(String status, ResultHandler handler) { long oid = 0; long count = 0; int marker1 = -1; int marker2 = -1; for (int i = status.length() - 1; i >= 0; i--) { if (Character.isDigit(status.charAt(i))) { } else if (status.charAt(i) == ' ') { if (marker1 == -1) { marker1 = i; } else { marker2 = i; } } else { break; } } if (marker1 != -1) { try { if (marker2 != -1) { oid = Long.parseLong(status.substring(marker2 + 1, marker1)); count = Long.parseLong(status.substring(marker1 + 1)); } else { count = Long.parseLong(status.substring(marker1 + 1)); } } catch (NumberFormatException e) { handler.handleError(new PSQLException( GT.tr("Unable to parse the count in command completion tag: {0}.", status), PSQLState.CONNECTION_FAILURE)); return; } } int countAsInt = 0; if (count > Integer.MAX_VALUE) { countAsInt = Statement.SUCCESS_NO_INFO; } else if (count > 0) { countAsInt = (int) count; } handler.handleCommandStatus(status, countAsInt, oid); }
Source:
private static void scanFile(String filename, JavaFileScanner check, JavaCheckVerifier javaCheckVerifier) { Collection<File> classpath = Lists.newLinkedList(); File testJars = new File("target/test-jars"); if(testJars.exists()) { classpath = FileUtils.listFiles(testJars, new String[]{"jar", "zip"}, true); } classpath.add(new File("target/test-classes")); JavaAstScanner.scanSingleFile(new File(filename), new VisitorsBridge(Lists.newArrayList(check, javaCheckVerifier), Lists.newArrayList(classpath), null)); }

Target:
private static void scanFile(String filename, JavaFileScanner check, JavaCheckVerifier javaCheckVerifier) { Collection<File> classpath = Lists.newLinkedList(); File testJars = new File(javaCheckVerifier.testJarsDirectory); if (testJars.exists()) { classpath = FileUtils.listFiles(testJars, new String[]{"jar", "zip"}, true); } else if (!DEFAULT_TEST_JARS_DIRECTORY.equals(javaCheckVerifier.testJarsDirectory)) { throw Fail.fail("The directory to be used to extend class path does not exists (" + testJars.getAbsolutePath() + ")."); } classpath.add(new File("target/test-classes")); JavaAstScanner.scanSingleFile(new File(filename), new VisitorsBridge(Lists.newArrayList(check, javaCheckVerifier), Lists.newArrayList(classpath), null)); }
Source:
public static Dialog find(@NotNull Robot robot, @NotNull String title) { return WindowFinder.findDialog(new DialogTitleMatcher(title)).withTimeout(10000).using(robot).target; }

Target:
public static Dialog find(@NotNull Robot robot, @NotNull String title) { return WindowFinder.findDialog(new DialogTitleMatcher(title)).withTimeout(GuiTests.LONG_TIMEOUT.duration()).using(robot).target; }
Source:
public void testHostStatuses() throws Exception { final String aHost = testHost() + "a"; final String bHost = testHost() + "b"; startDefaultMaster(); startDefaultAgent(aHost); startDefaultAgent(bHost); awaitHostStatus(aHost, UP, LONG_WAIT_MINUTES, MINUTES); awaitHostStatus(bHost, UP, LONG_WAIT_MINUTES, MINUTES); final Map<String, HostStatus> cliStatuses = new ObjectMapper().readValue(cli("hosts", "--json"), new TypeReference<Map<String, HostStatus>>(){}); assertTrue("status must contain key for " + aHost, cliStatuses.containsKey(aHost)); assertTrue("status must contain key for " + bHost, cliStatuses.containsKey(bHost)); final HeliosClient client = defaultClient(); final Map<String, HostStatus> clientStatuses = client.hostStatuses( ImmutableList.of(aHost, bHost)).get(); assertTrue("status must contain key for " + aHost, clientStatuses.containsKey(aHost)); assertTrue("status must contain key for " + bHost, clientStatuses.containsKey(bHost)); }

Target:
public void testHostStatuses() throws Exception { final String aHost = testHost() + "a"; final String bHost = testHost() + "b"; startDefaultMaster(); startDefaultAgent(aHost); startDefaultAgent(bHost); awaitHostStatus(aHost, UP, LONG_WAIT_SECONDS, SECONDS); awaitHostStatus(bHost, UP, LONG_WAIT_SECONDS, SECONDS); final Map<String, HostStatus> cliStatuses = new ObjectMapper().readValue(cli("hosts", "--json"), new TypeReference<Map<String, HostStatus>>(){}); assertTrue("status must contain key for " + aHost, cliStatuses.containsKey(aHost)); assertTrue("status must contain key for " + bHost, cliStatuses.containsKey(bHost)); final HeliosClient client = defaultClient(); final Map<String, HostStatus> clientStatuses = client.hostStatuses( ImmutableList.of(aHost, bHost)).get(); assertTrue("status must contain key for " + aHost, clientStatuses.containsKey(aHost)); assertTrue("status must contain key for " + bHost, clientStatuses.containsKey(bHost)); }
Source:
public void maybeShowIndicatorDots() { editOptionIndicatorDot.setVisibility((Prefs.showEditMenuOptionIndicator() && Prefs.getTotalUserDescriptionsEdited() >= ACTION_DESCRIPTION_EDIT_UNLOCK_THRESHOLD) ? VISIBLE : GONE); }

Target:
public void maybeShowIndicatorDots() { editOptionIndicatorDot.setVisibility(Prefs.showEditMenuOptionIndicator() ? VISIBLE : GONE); }
Source:
public BlockBreakHandler getItemHandler() { return new BlockBreakHandler() { @Override public boolean isPrivate() { return false; } @Override public boolean onBlockBreak(BlockBreakEvent e, ItemStack item, int fortune, List<ItemStack> drops) { if (isItem(item)) { if (Slimefun.hasUnlocked(e.getPlayer(), ExplosiveTool.this, true)) { e.getBlock().getWorld().createExplosion(e.getBlock().getLocation(), 0.0F); e.getBlock().getWorld().playSound(e.getBlock().getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.2F, 1F); List<Block> blocks = findBlocks(e.getBlock()); if (callExplosionEvent.getValue()) { BlockExplodeEvent blockExplodeEvent = new BlockExplodeEvent(e.getBlock(), blocks, 0); Bukkit.getServer().getPluginManager().callEvent(blockExplodeEvent); if (!blockExplodeEvent.isCancelled()) { blockExplodeEvent.blockList().forEach(b -> breakBlock(e.getPlayer(), item, b, fortune, drops)); } } else { for (Block b : blocks) { breakBlock(e.getPlayer(), item, b, fortune, drops); } } } return true; } else { return false; } } }; }

Target:
public ToolUseHandler getItemHandler() { return (e, tool, fortune, drops) -> { Player p = e.getPlayer(); Block b = e.getBlock(); b.getWorld().createExplosion(b.getLocation(), 0.0F); b.getWorld().playSound(b.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 0.2F, 1F); List<Block> blocks = findBlocks(b); breakBlocks(p, tool, b, blocks, fortune, drops); }; }