auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private VoidResult doAddReviewers(final Set<Id> reviewerIds, final Change.Id id, final ReviewDb db, final Transaction txn) throws OrmException { final List<ApprovalType> allTypes = Common.getGerritConfig().getApprovalTypes(); final ApprovalCategory.Id ac = allTypes.get(allTypes.size() - 1).getCategory().getId(); for (Account.Id reviewer : reviewerIds) { if (db.changeApprovals().byChangeUser(id, reviewer).iterator().hasNext() == false) { ChangeApproval myca = new ChangeApproval(new ChangeApproval.Key(id, reviewer, ac), (short) 0); db.changeApprovals().insert(Collections.singleton(myca), txn); } } return VoidResult.INSTANCE; }

Target:
private VoidResult doAddReviewers(final Set<Id> reviewerIds, final Change.Id id, final ReviewDb db, final Transaction txn) throws OrmException { final List<ApprovalType> allTypes = Common.getGerritConfig().getApprovalTypes(); final ApprovalCategory.Id ac = allTypes.get(allTypes.size() - 1).getCategory().getId(); for (Account.Id reviewer : reviewerIds) { if (!db.changeApprovals().byChangeUser(id, reviewer).iterator().hasNext()) { ChangeApproval myca = new ChangeApproval(new ChangeApproval.Key(id, reviewer, ac), (short) 0); db.changeApprovals().insert(Collections.singleton(myca), txn); } } return VoidResult.INSTANCE; }
Source:
public void testGetRequiredTokens() { final AnnotationLocationCheck checkObj = new AnnotationLocationCheck(); assertArrayEquals( "AnnotationLocationCheck#getRequiredtokens should return empty array by default", CommonUtils.EMPTY_INT_ARRAY, checkObj.getRequiredTokens()); }

Target:
public void testGetRequiredTokens() { final AnnotationLocationCheck checkObj = new AnnotationLocationCheck(); assertArrayEquals( "AnnotationLocationCheck#getRequiredTokens should return empty array by default", CommonUtils.EMPTY_INT_ARRAY, checkObj.getRequiredTokens()); }
Source:
public String encodeUnicodeString(String str) { str = str == null ? "" : str; String tmp; StringBuilder sb = new StringBuilder(); char c; int i, j; sb.setLength(0); for (i = 0; i < str.length(); i++) { c = str.charAt(i); sb.append("%u"); j = (c >>>8); tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append('0'); sb.append(tmp); j = (c & 0xFF); tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append('0'); sb.append(tmp); } return (sb.toString()); }

Target:
private static String encodeUnicodeString(String str) { str = str == null ? "" : str; String tmp; StringBuilder sb = new StringBuilder(); char c; int i, j; sb.setLength(0); for (i = 0; i < str.length(); i++) { c = str.charAt(i); sb.append("%u"); j = (c >>>8); tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append('0'); sb.append(tmp); j = (c & 0xFF); tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append('0'); sb.append(tmp); } return (sb.toString()); }
Source:
private static String[] getFieldArray(String field) { StringBuilder sb = new StringBuilder(); List<String> list = new ArrayList<>(); for (int i = 1; i < field.length(); i++) { char charAt = field.charAt(i); if (charAt == SLASH) { list.add(sb.toString()); sb = new StringBuilder(); } else if (charAt == BACKSLASH && i < field.length() - 1 && field.charAt(i + 1) == SLASH) { sb.append(SLASH); i++; } else { sb.append(charAt); } } list.add(sb.toString()); String[] array = new String[list.size()]; list.toArray(array); return array; }

Target:
private static String[] getFieldArray(String field) { StringBuilder sb = new StringBuilder(); List<String> list = new ArrayList<>(); for (int i = 1; i < field.length(); i++) { char charAt = field.charAt(i); if (charAt == SLASH) { list.add(sb.toString()); sb = new StringBuilder(); } else if ((charAt == BACKSLASH) && (i < field.length() - 1) && (field.charAt(i + 1) == SLASH)) { sb.append(SLASH); i++; } else { sb.append(charAt); } } list.add(sb.toString()); String[] array = new String[list.size()]; list.toArray(array); return array; }
Source:
protected void checkReferenceType(Set<SwaggerError> errors, AbstractNode node) { if (JsonReference.isReference(node)) { Model model = node.getModel(); TypeDefinition type = node.getType(); if (type instanceof ReferenceTypeDefinition) { type = ((ReferenceTypeDefinition) type).resolve(); } AbstractNode nodeValue = node.get(JsonReference.PROPERTY); AbstractNode valueNode = model.find((String) nodeValue.asValue().getValue()); if (valueNode != null && type.getPointer() != null && valueNode.getType() != null && !type.getPointer().equals(valueNode.getType().getPointer())) { errors.add(error(nodeValue, IMarker.SEVERITY_ERROR, Messages.error_invalid_reference_type)); } } }

Target:
protected void checkReferenceType(Set<SwaggerError> errors, AbstractNode node) { if (JsonReference.isReference(node)) { Model model = node.getModel(); TypeDefinition type = node.getType(); AbstractNode nodeValue = node.get(JsonReference.PROPERTY); AbstractNode valueNode = model.find((String) nodeValue.asValue().getValue()); if (valueNode == null) { return; } if (!type.validate(valueNode)) { errors.add(error(nodeValue, IMarker.SEVERITY_WARNING, Messages.error_invalid_reference_type)); } } }
Source:
public void onPlayerCastsSpell(ManaChangeEvent event) { player = dPlayer.mirrorBukkitPlayer(event.getPlayer()); new_mana = event.getNewAmount(); old_mana = event.getOldAmount(); max_mana = event.getMaxMana(); reason = new Element(event.getReason().name()); this.event = event; fire(); event.setNewAmount(new_mana); }

Target:
public void onPlayerCastsSpell(ManaChangeEvent event) { player = dPlayer.mirrorBukkitPlayer(event.getPlayer()); new_mana = event.getNewAmount(); old_mana = event.getOldAmount(); max_mana = event.getMaxMana(); reason = new Element(event.getReason().name()); this.event = event; fire(event); event.setNewAmount(new_mana); }
Source:
public void onEvent(Event event, Object source, Object data) { XWikiContext context = (XWikiContext) data; XWikiDocument doc = (XWikiDocument) source; BaseObject patientRecordObj = doc.getXObject(new DocumentReference(doc.getDocumentReference().getWikiReference().getName(), Constants.CODE_SPACE, "PatientClass")); if (patientRecordObj == null) { return; } List<BaseObject> existingVersionObjects = doc.getXObjects(VERSION_RECORDER_REFERENCE); try { for (Map.Entry<String, String> versionType : this.versionTypes().entrySet()) { boolean skip = false; if (existingVersionObjects != null) { for (BaseObject existingVersionObject : existingVersionObjects) { String name = existingVersionObject.getField(NAME_FIELD).toFormString(); if (name.equalsIgnoreCase(versionType.getKey())) { skip = true; break; } } if (skip) { continue; } } BaseObject versionObject = doc.newXObject(VERSION_RECORDER_REFERENCE, context); versionObject.set(NAME_FIELD, versionType.getKey(), context); versionObject.set("version", versionType.getValue(), context); } } catch (XWikiException ex) { } }

Target:
public void onEvent(Event event, Object source, Object data) { XWikiContext context = (XWikiContext) data; XWikiDocument doc = (XWikiDocument) source; BaseObject patientRecordObj = doc.getXObject(new DocumentReference(doc.getDocumentReference().getWikiReference().getName(), Constants.CODE_SPACE, "PatientClass")); if (patientRecordObj == null) { return; } List<BaseObject> existingVersionObjects = doc.getXObjects(VERSION_RECORDER_REFERENCE); try { for (Map.Entry<String, String> versionType : this.getOntologiesVersions().entrySet()) { boolean skip = false; if (existingVersionObjects != null) { for (BaseObject existingVersionObject : existingVersionObjects) { String name = existingVersionObject.getStringValue(NAME_FIELD); if (StringUtils.equalsIgnoreCase(name, versionType.getKey())) { existingVersionObject.set(VERSION_FIELD, versionType.getValue(), context); skip = true; break; } } if (skip) { continue; } } BaseObject versionObject = doc.newXObject(VERSION_RECORDER_REFERENCE, context); versionObject.set(NAME_FIELD, versionType.getKey(), context); versionObject.set(VERSION_FIELD, versionType.getValue(), context); } } catch (XWikiException ex) { } }
Source:
public void flush() { Map<String, Object>[] vmInfos = getVmInfo(vdsId, getVmsToProcess()); if (vmInfos != null) { for (Map<String, Object> vmInfo : vmInfos) { processFullList(vmInfo); } } for (VmDevice deviceToUpdate : getDevicesToProcess()) { processDeviceUpdate(this, deviceToUpdate); } saveDevicesToDb(this); unlockTouchedVms(); }

Target:
public void flush() { Map<String, Object>[] vmInfos = getVmInfo(vdsId, getVmsToProcess()); if (vmInfos != null) { for (Map<String, Object> vmInfo : vmInfos) { processFullList(vmInfo); } } for (VmDevice deviceToProcess : getDevicesToProcess()) { processDevice(this, deviceToProcess); } saveDevicesToDb(this); unlockTouchedVms(); }
Source:
private RiakConnection getConnection(int attempts) throws IOException { try { if (permits.tryAcquire(connectionWaitTimeoutMillis, TimeUnit.MILLISECONDS)) { RiakConnection c = available.poll(); if (c == null) { try { c = new RiakConnection(host, port, bufferSizeKb, this); } catch (IOException e) { permits.release(); throw e; } } inUse.offer(c); return c; } else { throw new AcquireConnectionTimeoutException("timeout aquiring connection permit from pool"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (attempts > 0) { return getConnection(attempts - 1); } else { throw new IOException("interrupted whilst waiting to acquire connection"); } } }

Target:
private RiakConnection getConnection(int attempts) throws IOException { try { if (permits.tryAcquire(connectionWaitTimeoutMillis, TimeUnit.MILLISECONDS)) { RiakConnection c = available.poll(); if (c == null) { try { c = new RiakConnection(host, port, bufferSizeKb, this); } catch (IOException e) { permits.release(); throw e; } } inUse.offer(c); return c; } else { throw new AcquireConnectionTimeoutException("timeout acquiring connection permit from pool"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (attempts > 0) { return getConnection(attempts - 1); } else { throw new IOException("interrupted whilst waiting to acquire connection"); } } }
Source:
public Channel attach(String handle, final Map<String, String> parameters) { if (log.isDebugEnabled()) { log.debug("attach: [ " + handle + " ] with parameters: " + parameters); } Channel channel = new TransportChannel(transportConnection); HashMap<String, String> request = new HashMap<String, String>(parameters); request.putAll(buildParams("type", "attach", "handle", handle)); transportConnection.sendMessage(channel, request); return channel; }

Target:
public Channel attach(String handle, final Map<String, String> parameters) { log.debug("attach: [ ] with parameters: {}", handle, parameters); Channel channel = new TransportChannel(transportConnection); Map<String, String> request = new HashMap<String, String>(parameters); request.put("type", "attach"); request.put("handle", handle); transportConnection.sendMessage(channel, request); return channel; }
Source:
public static Slice stLineString(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input) { int addedPoints = 0; MultiPath multipath = new Polyline(); OGCPoint previousPoint = null; for (int i = 0; i < input.getPositionCount(); i++) { Slice slice = GEOMETRY.getSlice(input, i); if (slice.getInput().available() == 0) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_LineString: null at index %s", i + 1)); } OGCGeometry geometry = deserialize(slice); if (!(geometry instanceof OGCPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("ST_LineString takes only an array of valid points, %s was passed", geometry.geometryType())); } OGCPoint point = (OGCPoint) geometry; if (point.isEmpty()) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_LineString: empty point found at index %s", i + 1)); } if (addedPoints == 0) { previousPoint = point; multipath.startPath(point.X(), point.Y()); } else { if(point.Equals(previousPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("ST_LineString doesn't take array with consecutive duplicate points, duplicates found at index %s", i + 1)); } previousPoint = point; multipath.lineTo(point.X(), point.Y()); } addedPoints++; } OGCLineString linestring = new OGCLineString(multipath, 0, null); return serialize(linestring); }

Target:
public static Slice stLineString(@SqlType("array(" + GEOMETRY_TYPE_NAME + ")") Block input) { MultiPath multipath = new Polyline(); OGCPoint previousPoint = null; for (int i = 0; i < input.getPositionCount(); i++) { Slice slice = GEOMETRY.getSlice(input, i); if (slice.getInput().available() == 0) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_LineString: null point at index %s", i + 1)); } OGCGeometry geometry = deserialize(slice); if (!(geometry instanceof OGCPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("ST_LineString takes only an array of valid points, %s was passed", geometry.geometryType())); } OGCPoint point = (OGCPoint) geometry; if (point.isEmpty()) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_LineString: empty point at index %s", i + 1)); } if (previousPoint == null) { multipath.startPath(point.X(), point.Y()); } else { if (point.Equals(previousPoint)) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, format("Invalid input to ST_LineString: consecutive duplicate points at index %s", i + 1)); } multipath.lineTo(point.X(), point.Y()); } previousPoint = point; } OGCLineString linestring = new OGCLineString(multipath, 0, null); return serialize(linestring); }
Source:
public void testEnglishLanguage() { WebElement webElement = browser.findElement(By.linkText("Take a Tour!")); webElement.click(); WindowFragment windowFragment = Console.withBrowser(browser).openedWindow(); if (windowFragment != null) { WebElement iFrame = browser.findElement(ByJQuery.selector("iframe.gwt-Frame")); WebElement content = browser.switchTo().frame(iFrame).findElement(By.tagName("body")); String text = content.findElement(By.className("text-1")).getText(); Assert.assertTrue("Take a tour window doesn't contain English text (Enable, disable, and view the ...)", text.contains("Enable, disable, and view the")); } }

Target:
public void testEnglishLanguage() { WebElement webElement = browser.findElement(By.linkText("Take a Tour!")); webElement.click(); WindowFragment windowFragment = Console.withBrowser(browser).openedWindow(); if (windowFragment != null) { WebElement iFrame = browser.findElement(ByJQuery.selector("iframe.gwt-Frame")); WebElement content = browser.switchTo().frame(iFrame).findElement(By.tagName("body")); String text = content.findElement(By.className("text-1")).getText(); Assert.assertTrue("Take a tour window doesn't contain English text (Enable, disable, and view the ...). Probably due to <LINK_0>", text.contains("Enable, disable, and view the")); } }
Source:
public Map<String, NoteInfo> list(AuthenticationInfo subject) throws IOException { Map<String, NoteInfo> infos = new HashMap<>(); Document match = new Document("$match", new Document(Fields.IS_DIR, false)); Document graphLookup = new Document("$graphLookup" , new Document("from", folderName) .append("startWith", "$" + Fields.PID) .append("connectFromField", Fields.PID) .append("connectToField", Fields.ID) .append("as", "fullPath")); ArrayList<Document> list = Lists.newArrayList(match, graphLookup); AggregateIterable<Document> aggregate = folders.aggregate(list); for (Document document : aggregate) { String id = document.getString(Fields.ID); String name = document.getString(Fields.NAME); List<Document> fullPath = document.get("fullPath", List.class); StringBuilder sb = new StringBuilder(); for (Document pathNode : fullPath) { sb.append("/").append(pathNode.getString(Fields.NAME)); } String fullPathStr = sb.append("/").append(name).toString(); NoteInfo noteInfo = new NoteInfo(id, fullPathStr); infos.put(id, noteInfo); } return infos; }

Target:
public Map<String, NoteInfo> list(AuthenticationInfo subject) throws IOException { LOG.debug("list repo."); Map<String, NoteInfo> infos = new HashMap<>(); Document match = new Document("$match", new Document(Fields.IS_DIR, false)); Document graphLookup = new Document("$graphLookup", new Document("from", folderName) .append("startWith", "$" + Fields.PID) .append("connectFromField", Fields.PID) .append("connectToField", Fields.ID) .append("as", Fields.FULL_PATH)); try (AutoLock autoLock = lock.lockForRead()) { ArrayList<Document> list = Lists.newArrayList(match, graphLookup); AggregateIterable<Document> aggregate = folders.aggregate(list); for (Document document : aggregate) { String id = document.getString(Fields.ID); String name = document.getString(Fields.NAME); List<Document> fullPath = document.get(Fields.FULL_PATH, List.class); StringBuilder sb = new StringBuilder(); for (Document pathNode : fullPath) { sb.append("/").append(pathNode.getString(Fields.NAME)); } String fullPathStr = sb.append("/").append(name).toString(); NoteInfo noteInfo = new NoteInfo(id, fullPathStr); infos.put(id, noteInfo); } } return infos; }
Source:
public void updateNonValidSupportLevel() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateAdminAccess") .build(); context.restoreAuthSystemState(); BitstreamFormatRest bitstreamFormatRest = converter.fromModel(bitstreamFormat); String token = getAuthToken(admin.getEmail(), password); bitstreamFormatRest.setShortDescription("Test short UPDATED"); bitstreamFormatRest.setSupportLevel("NONVALID SUPPORT LEVEL"); getClient(token).perform(put("/api/core/bitstreamformats/" + bitstreamFormat.getID()) .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isBadRequest()); }

Target:
public void updateNonValidSupportLevel() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateAdminAccess") .withSupportLevel(BitstreamFormat.SUPPORTED) .build(); context.restoreAuthSystemState(); BitstreamFormatRest bitstreamFormatRest = converter.fromModel(bitstreamFormat); String token = getAuthToken(admin.getEmail(), password); bitstreamFormatRest.setShortDescription("Test short UPDATED"); bitstreamFormatRest.setSupportLevel("NONVALID SUPPORT LEVEL"); getClient(token).perform(put("/api/core/bitstreamformats/" + bitstreamFormat.getID()) .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isBadRequest()); getClient(token).perform(get("/api/core/bitstreamformats/" + bitstreamFormat.getID())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", Matchers.is( BitstreamFormatMatcher .matchBitstreamFormat(bitstreamFormat.getID(), bitstreamFormat.getMIMEType(), bitstreamFormat.getDescription(), bitstreamFormat.getShortDescription(), bitstreamFormatService .getSupportLevelText(bitstreamFormat)) ))); }
Source:
public void testGetDeclaredFieldPrivate() throws NoSuchFieldException { exceptionGrabber.expect(NoSuchFieldException.class); Class<?> privateString = ReflectionUtil.getDeclaredField("private", TestClass.class); assertThat((privateString == String.class), is(true)); }

Target:
public void testGetDeclaredFieldPrivate() throws NoSuchFieldException { exceptionGrabber.expect(NoSuchFieldException.class); ReflectionUtil.getDeclaredField("private", TestClass.class); }
Source:
private String validateNewBulkBranchName(String newBranchName, Repository[] repositories) { for (Repository repo : repositories) { IStatus status = Utils.validateNewRefName(newBranchName, repo, Constants.R_HEADS, true); if (status.getException() != null) { Activator.handleStatus(status, false); } if (!status.isOK()) { return status.getMessage(); } } return null; }

Target:
private String validateNewBulkBranchName(String newBranchName, Repository[] repositories) { for (Repository repo : repositories) { IStatus status = Utils.validateNewRefName(newBranchName, repo, Constants.R_HEADS, true); if (status.getException() != null) { Activator.handleStatus(status, false); } if (!status.isOK()) { return Activator.getDefault().getRepositoryUtil() .getRepositoryName(repo) + ": " + status.getMessage(); } } return null; }
Source:
public void taskDataUpdated(TaskDataManagerEvent event) { if (event.getToken() != null && event.getTaskDataChanged()) { recordNotificationText(event); if (isEnabled()) { return; } if (PresentationFilter.getInstance().isInVisibleQuery(event.getTask())) { AbstractRepositoryConnectorUi connectorUi = TasksUi .getRepositoryConnectorUi(event.getTaskData().getConnectorKind()); if (!connectorUi.hasCustomNotifications()) { TaskListNotification notification = getNotification(event.getTask(), event.getToken()); if (notification != null) { synchronized (notificationQueue) { if (enabled) { notificationQueue.add(notification); } } } } } } }

Target:
public void taskDataUpdated(TaskDataManagerEvent event) { if (event.getToken() != null && event.getTaskDataChanged()) { recordNotificationText(event); if (isEnabled()) { if (PresentationFilter.getInstance().isInVisibleQuery(event.getTask())) { AbstractRepositoryConnectorUi connectorUi = TasksUi .getRepositoryConnectorUi(event.getTaskData().getConnectorKind()); if (!connectorUi.hasCustomNotifications()) { TaskListNotification notification = getNotification(event.getTask(), event.getToken()); if (notification != null) { synchronized (notificationQueue) { if (enabled) { notificationQueue.add(notification); } } } } } } } }
Source:
protected void handleModelOpenUri(BinaryResource res, IOpenUriAction openUriAction) { String filename = ObjectUtility.nvl(res.getFilename(), "binaryData"); String filenameWithCounter = filename; long counter = RESOURCE_COUNTER.getAndIncrement(); filenameWithCounter = counter + "/" + filenameWithCounter; BinaryResourceHolder holder = new BinaryResourceHolder(res); if (openUriAction == OpenUriAction.DOWNLOAD) { holder.addHttpResponseInterceptor(new DownloadHttpResponseInterceptor(res.getFilename())); } m_downloads.put(filenameWithCounter, holder, openUriAction); String downloadUrl = BinaryResourceUrlUtility.createDynamicAdapterResourceUrl(this, filenameWithCounter); handleModelOpenUri(downloadUrl, openUriAction); }

Target:
protected void handleModelOpenUri(BinaryResource res, IOpenUriAction openUriAction) { long counter = RESOURCE_COUNTER.getAndIncrement(); String filenameWithCounter = counter + "/" + ObjectUtility.nvl(res.getFilename(), "binaryData"); BinaryResourceHolder holder = new BinaryResourceHolder(res); if (openUriAction == OpenUriAction.DOWNLOAD) { holder.addHttpResponseInterceptor(new DownloadHttpResponseInterceptor(res.getFilename())); } m_downloads.put(filenameWithCounter, holder, openUriAction); String downloadUrl = BinaryResourceUrlUtility.createDynamicAdapterResourceUrl(this, filenameWithCounter); handleModelOpenUri(downloadUrl, openUriAction); }
Source:
boolean attackUrl() { String urlStr = this.getUrlField().getSelectedItem().toString(); URL url; try { url = new URL(urlStr); new URI(urlStr, true); } catch (Exception e) { getExtensionQuickStart().getView() .showWarningDialog(Constant.messages.getString("quickstart.url.warning.invalid")); this.getUrlField().requestFocusInWindow(); return false; } this.getExtensionQuickStart().getQuickStartParam().addRecentUrl(urlStr); getAttackButton().setEnabled(false); getStopButton().setEnabled(true); getExtensionQuickStart().attack(url, spiderCheckBox.isSelected()); return true; }

Target:
boolean attackUrl() { Object item = this.getUrlField().getSelectedItem(); if (item == null || DEFAULT_VALUE_URL_FIELD.equals(item.toString())) { getExtensionQuickStart().getView() .showWarningDialog(Constant.messages.getString("quickstart.url.warning.invalid")); this.getUrlField().requestFocusInWindow(); return false; } String urlStr = item.toString(); URL url; try { url = new URL(urlStr); new URI(urlStr, true); } catch (Exception e) { getExtensionQuickStart().getView() .showWarningDialog(Constant.messages.getString("quickstart.url.warning.invalid")); this.getUrlField().requestFocusInWindow(); return false; } this.getExtensionQuickStart().getQuickStartParam().addRecentUrl(urlStr); getAttackButton().setEnabled(false); getStopButton().setEnabled(true); getExtensionQuickStart().attack(url, spiderCheckBox.isSelected()); return true; }
Source:
private ClientCache initClient() { try { clientCache = new ClientCacheFactory().addPoolLocator(getLocatorHost(), getLocatorPort()).create(); } catch (CacheClosedException ex) { LOG.info("error initiating client ", ex); } return clientCache; }

Target:
private ClientCache initClient() { try { clientCache = new ClientCacheFactory().addPoolLocator(getLocatorHost(), getLocatorPort()).create(); } catch (CacheClosedException ex) { throw new RuntimeException("Exception while creating cache", ex); } return clientCache; }
Source:
private Topic resolveOrCreateDbpediaTopic(String title, Topic.Type topicType, String namespace, String value, Publisher publisher) { Maybe<Topic> resolved = topicStore.topicFor(namespace, value); if (resolved.hasValue()) { Topic topic = resolved.requireValue(); topic.setPublisher(publisher); topic.setTitle(title); topic.setType(topicType); topicStore.write(topic); return topic; } throw new IllegalStateException(String.format( "Topic store failed to createDefault Topic with namespace %s and value %s", namespace, value )); }

Target:
private Topic resolveOrCreateDbpediaTopic(String title, Topic.Type topicType, String namespace, String value, Publisher publisher) { Maybe<Topic> resolved = topicStore.topicFor(namespace, value); if (resolved.hasValue()) { Topic topic = resolved.requireValue(); topic.setPublisher(publisher); topic.setTitle(title); topic.setType(topicType); topicStore.write(topic); return topic; } throw new IllegalStateException(String.format( "Topic store failed to create Topic with namespace %s and value %s", namespace, value )); }
Source:
public void testResetWhenLongSessionTimeoutConfiguredWithForceOption() throws Exception { appID = testId + "-with-force-option"; streamsConfig.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); streamsConfig.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "" + STREAMS_CONSUMER_TIMEOUT * 100); streams = new KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig); streams.start(); final List<KeyValue<Long, Long>> result = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig, OUTPUT_TOPIC, 10); streams.close(); streams = new KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig); streams.cleanUp(); int exitCode = tryCleanGlobal(false, null, null); Assert.assertEquals(1, exitCode); exitCode = tryCleanGlobal(false, "--force", null); Assert.assertEquals(0, exitCode); waitForEmptyConsumerGroup(adminClient, appID, TIMEOUT_MULTIPLIER * CLEANUP_CONSUMER_TIMEOUT); assertInternalTopicsGotDeleted(null); streams.start(); final List<KeyValue<Long, Long>> resultRerun = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig, OUTPUT_TOPIC, 10); streams.close(); assertThat(resultRerun, equalTo(result)); tryCleanGlobal(false, "--force", null); }

Target:
public void testResetWhenLongSessionTimeoutConfiguredWithForceOption() throws Exception { appID = testId + "-with-force-option"; streamsConfig.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); streamsConfig.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "" + STREAMS_CONSUMER_TIMEOUT * 100); streams = new KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig); streams.start(); final List<KeyValue<Long, Long>> result = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig, OUTPUT_TOPIC, 10); streams.close(); streams = new KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig); streams.cleanUp(); final boolean cleanResult = tryCleanGlobal(false, null, null); Assert.assertEquals(false, cleanResult); cleanGlobal(false, "--force", null); assertThat("Group is not empty after cleanGlobal", isEmptyConsumerGroup(adminClient, appID)); assertInternalTopicsGotDeleted(null); streams.start(); final List<KeyValue<Long, Long>> resultRerun = IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig, OUTPUT_TOPIC, 10); streams.close(); assertThat(resultRerun, equalTo(result)); cleanGlobal(false, "--force", null); }
Source:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); if (currentToken == null) currentToken = parser.nextToken(); if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; } catch (JsonParseException e) { if (shouldThrow) throw e; return false; } }

Target:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); if (currentToken == null) currentToken = parser.nextToken(); if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; } catch (Throwable e) { if (shouldThrow) throw e; return false; } }
Source:
public CleanupTaskProvisioner(TopLevelItem tli, List<Node> nodes) { this.tli = tli; this.nodes = new LinkedList<>(nodes); if (threadLimit > 0) { LOGGER.log(Level.INFO, "ThreadLimit Loaded from Environment : {0}", threadLimit); } if (threadLimit > 0) { LOGGER.log(Level.INFO, "ThreadLimit Loaded from Environment : {0}", threadLimit); } if (threadLimit > 0) { LOGGER.log(Level.INFO, "ThreadLimit Loaded from Environment : {0}", threadLimit); } if (threadLimit > 0) { LOGGER.log(Level.INFO, "ThreadLimit Loaded from Environment : {0}", threadLimit); } if (threadLimit > 0) { LOGGER.log(Level.INFO, "ThreadLimit Loaded from Environment : {0}", threadLimit); } }

Target:
public CleanupTaskProvisioner(TopLevelItem tli, List<Node> nodes) { this.tli = tli; this.nodes = new LinkedList<>(nodes); if (threadLimit > 0) { LOGGER.log(Level.INFO, "ThreadLimit Loaded from Environment : {0}", threadLimit); } }
Source:
private List<Map<String, String>> getVolumesToDisconnect(VirtualMachine vm) { List<Map<String, String>> volumesToDisconnect = new ArrayList<>(); List<VolumeVO> volumes = _volsDao.findByInstance(vm.getId()); if (volumes != null) { for (VolumeVO volume : volumes) { StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId()); if (storagePool != null && storagePool.isManaged()) { Map<String, String> info = new HashMap<>(3); info.put(DiskTO.STORAGE_HOST, storagePool.getHostAddress()); info.put(DiskTO.STORAGE_PORT, String.valueOf(storagePool.getPort())); info.put(DiskTO.IQN, volume.get_iScsiName()); volumesToDisconnect.add(info); } } } return volumesToDisconnect; }

Target:
private List<Map<String, String>> getVolumesToDisconnect(VirtualMachine vm) { List<Map<String, String>> volumesToDisconnect = new ArrayList<>(); List<VolumeVO> volumes = _volsDao.findByInstance(vm.getId()); if (CollectionUtils.isEmpty(volumes)) { return volumesToDisconnect; } for (VolumeVO volume : volumes) { StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId()); if (storagePool != null && storagePool.isManaged()) { Map<String, String> info = new HashMap<>(3); info.put(DiskTO.STORAGE_HOST, storagePool.getHostAddress()); info.put(DiskTO.STORAGE_PORT, String.valueOf(storagePool.getPort())); info.put(DiskTO.IQN, volume.get_iScsiName()); volumesToDisconnect.add(info); } } return volumesToDisconnect; }
Source:
public RebalanceProtocol rebalanceProtocol() { final String upgradeFrom = streamsConfig.getString(StreamsConfig.UPGRADE_FROM_CONFIG); if (upgradeFrom != null) { switch (upgradeFrom) { case StreamsConfig.UPGRADE_FROM_0100: case StreamsConfig.UPGRADE_FROM_0101: case StreamsConfig.UPGRADE_FROM_0102: case StreamsConfig.UPGRADE_FROM_0110: case StreamsConfig.UPGRADE_FROM_10: case StreamsConfig.UPGRADE_FROM_11: case StreamsConfig.UPGRADE_FROM_20: case StreamsConfig.UPGRADE_FROM_21: case StreamsConfig.UPGRADE_FROM_22: case StreamsConfig.UPGRADE_FROM_23: log.info("Turning off cooperative rebalancing for upgrade from {}.x", upgradeFrom); return RebalanceProtocol.EAGER; default: throw new IllegalArgumentException("Unknown configuration value for parameter 'upgrade.from': " + upgradeFrom); } } return StreamsPartitionAssignor.DEFAULT_REBALANCE_PROTOCOL; }

Target:
public RebalanceProtocol rebalanceProtocol() { final String upgradeFrom = streamsConfig.getString(StreamsConfig.UPGRADE_FROM_CONFIG); if (upgradeFrom != null) { switch (upgradeFrom) { case StreamsConfig.UPGRADE_FROM_0100: case StreamsConfig.UPGRADE_FROM_0101: case StreamsConfig.UPGRADE_FROM_0102: case StreamsConfig.UPGRADE_FROM_0110: case StreamsConfig.UPGRADE_FROM_10: case StreamsConfig.UPGRADE_FROM_11: case StreamsConfig.UPGRADE_FROM_20: case StreamsConfig.UPGRADE_FROM_21: case StreamsConfig.UPGRADE_FROM_22: case StreamsConfig.UPGRADE_FROM_23: log.info("Turning off cooperative rebalancing for upgrade from {}.x", upgradeFrom); return RebalanceProtocol.EAGER; default: throw new IllegalArgumentException("Unknown configuration value for parameter 'upgrade.from': " + upgradeFrom); } } return RebalanceProtocol.EAGER; }
Source:
private boolean isAbsolutePath(String uri) { return !(uri.startsWith("jndi") | uri.startsWith("file")); }

Target:
private boolean isAbsolutePath(String uri) { return !(uri.startsWith("jndi") || uri.startsWith("file")); }
Source:
public Plan optimize(final Collection<EvaluatorParameters> activeEvaluators, final int availableEvaluators) { if (ctrlTaskContextId == null) { initializeCtrlTaskContextId(); } final Optional<Cost> cost = CostCalculator.calculate(activeEvaluators, ctrlTaskContextId); if (!cost.isPresent()) { return PlanImpl.newBuilder().build(); } final List<OptimizedComputeTask> optimizedComputeTasks = initOptimizedComputeTasks(cost.get(), availableEvaluators - activeEvaluators.size()); final ExpressionsBasedModel model = new ExpressionsBasedModel(); final Variable cmpCostVar = Variable.make("computeCost"); final double commCostWeight = cost.get().getCommunicationCost() / cost.get().getComputeTaskCosts().size(); model.addVariable(cmpCostVar.weight(1.0)); for (final OptimizedComputeTask cmpTask : optimizedComputeTasks) { model.addVariable(cmpTask.getParticipateVariable().weight(commCostWeight)); model.addVariable(cmpTask.getRequestedDataVariable()); } addExpressions(model, cmpCostVar, optimizedComputeTasks, availableEvaluators - 1); final int totalDataUnits = getSumDataUnits(optimizedComputeTasks); final Optimisation.Result result = model.minimise(); LOG.log(Level.FINEST, "ILPSolverOptimizer Optimization Result: {0}", result); makeDataUnitsInteger(optimizedComputeTasks, totalDataUnits); final Plan plan = generatePlan(optimizedComputeTasks); LOG.log(Level.FINE, "ILPSolverOptimizer Plan: {0}", plan); return plan; }

Target:
public Plan optimize(final Collection<EvaluatorParameters> activeEvaluators, final int availableEvaluators) { if (ctrlTaskContextId == null) { initializeCtrlTaskContextId(); } final Optional<Cost> cost = CostCalculator.calculate(activeEvaluators, ctrlTaskContextId); if (!cost.isPresent()) { LOG.log(Level.WARNING, "No controller task present at the moment. Returning empty plan."); return PlanImpl.newBuilder().build(); } final List<OptimizedComputeTask> optimizedComputeTasks = initOptimizedComputeTasks(cost.get(), availableEvaluators - activeEvaluators.size()); final ExpressionsBasedModel model = new ExpressionsBasedModel(); final Variable cmpCostVar = Variable.make("computeCost"); final double commCostWeight = cost.get().getCommunicationCost() / cost.get().getComputeTaskCosts().size(); model.addVariable(cmpCostVar.weight(1.0)); for (final OptimizedComputeTask cmpTask : optimizedComputeTasks) { model.addVariable(cmpTask.getParticipateVariable().weight(commCostWeight)); model.addVariable(cmpTask.getRequestedDataVariable()); } addExpressions(model, cmpCostVar, optimizedComputeTasks, availableEvaluators - 1); final int totalDataUnits = getSumDataUnits(optimizedComputeTasks); final Optimisation.Result result = model.minimise(); LOG.log(Level.FINEST, "ILPSolverOptimizer Optimization Result: {0}", result); makeDataUnitsInteger(optimizedComputeTasks, totalDataUnits); final Plan plan = generatePlan(optimizedComputeTasks); LOG.log(Level.FINE, "ILPSolverOptimizer Plan: {0}", plan); return plan; }
Source:
private static boolean isUserNameOrRoomNameValid(Context context, EditText editText, String text, boolean isName) { int counterSymbols = 0; char[] fullNameTextToCharArray = text.toCharArray(); char[] symbols = {'<', '>', ';', '^'}; for (int i = 0; i < fullNameTextToCharArray.length; i++) { for (int j = 0; j < symbols.length; j++) { if (fullNameTextToCharArray[i] == symbols[j]) { counterSymbols++; break; } } } if (!text.isEmpty()) { if (text.length() < 3) { editText.setError(String.format( context.getString(R.string.error_name_must_be_more_than_2_characters_from_app), context.getString(isName ? R.string.field_name_user_name : R.string.field_name_chat_room_name))); return false; } else if (text.length() > 50){ editText.setError(String.format( context.getString(R.string.error_is_too_long_maximum_is_50_characters_from_app), context.getString(isName ? R.string.field_name_user_name : R.string.field_name_chat_room_name))); return false; } else if (counterSymbols != 0) { editText.setError(String.format( context.getString(R.string.error_name_must_do_not_contain_special_characters_from_app), context.getString(isName ? R.string.field_name_user_name : R.string.field_name_chat_room_name))); return false; } else { return true; } } else { editText.setError(String.format( context.getString(R.string.dlg_not_fullname_field_entered), context.getString(isName ? R.string.field_name_user_name : R.string.field_name_chat_room_name))); return false; } }

Target:
private static boolean isUserNameOrRoomNameValid(Context context, EditText editText, String text, boolean isName) { boolean isCorrect; Pattern p = Pattern.compile("\\A[^><;]{3,50}\\z"); Matcher m = p.matcher(text); isCorrect = m.matches(); if (!isCorrect) { editText.setError(String.format( context.getString(R.string.error_name_must_do_not_contain_special_characters_from_app), context.getString(isName ? R.string.field_name_user_name : R.string.field_name_chat_room_name))); return false; } else { return true; } }
Source:
private DefaultEdge unpackEdge(final Edge<V> input) { if (!(input instanceof JGraphTEdgeAdapter<?>)) { throw new IllegalArgumentException("Wrong edge type!"); } JGraphTEdgeAdapter<V> edge = (JGraphTEdgeAdapter<V>) input; return edge.getInternalEdge(); }

Target:
private DefaultEdge unpackEdge(final Edge<V> input) { if (!(input instanceof JGraphTEdgeAdapter<?>)) { throw new IllegalArgumentException("Wrong edge type."); } JGraphTEdgeAdapter<V> edge = (JGraphTEdgeAdapter<V>) input; return edge.getInternalEdge(); }
Source:
public String toString() { return "Pill: " + this.pillID + ", Account:" + this.accountId + ", Date: " + this.dateHourUTC + ", Offset: " + this.timeZoneOffset + ", Score: " + this.totalHourScore + ", Agitation_Num: " + this.agitationNum + ", Agitation_Tot: " + this.agitationTot; }

Target:
public String toString() { return Objects.toStringHelper(SleepScore.class) .add("pill", pillID) .add("account", accountId) .add("date_bucket_utc", dateBucketUTC) .add("tz_offset", timeZoneOffset) .add("score", this.bucketScore) .add("agitation_num", agitationNum) .add("agitation_tot", agitationTot) .toString(); }
Source:
private List<String> formatChatMessage(final LogRecord record) { return Arrays.asList(getFormatter().format(record).trim().split("\n")); }

Target:
private List<String> formatChatMessage(final LogRecord record) { return Arrays.asList(getFormatter().format(record).trim().split("\\n")); }
Source:
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, int blockSize) { final long length; try { length = data.available(); } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error deatils: " + e.getMessage())); } return convertStreamToByteBuffer(data, length, blockSize); }

Target:
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, int blockSize) { Pair pair = new Pair(); return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(Pair::buffer); }
Source:
public void updateHandler_queryString() { final String oldValue = "foo"; final String newValue = "foo bar"; Response response = db.save(new Foo(null, oldValue)); String query = "field=title&value=" + newValue; String output = db.invokeUpdateHandler("example/example_update", response.getId(), query); Foo foo = db.find(Foo.class, response.getId()); assertNotNull(output); assertEquals(foo.getTitle(), newValue); }

Target:
public void updateHandler_queryString() { final String oldValue = "foo"; final String newValue = "foo bar+plus=equals&ampersand"; Response response = db.save(new Foo(null, oldValue)); Params params = new Params() .addParam("field", "title") .addParam("value", newValue); String output = db.invokeUpdateHandler("example/example_update", response.getId(), params); Foo foo = db.find(Foo.class, response.getId()); assertNotNull(output); assertEquals(foo.getTitle(), newValue); }
Source:
public Diamond3iIterable.Builder start(int start) { this.startDistance = start + 1; return this; }

Target:
public Diamond3iIterable.Builder start(int start) { this.startDistance = start; return this; }
Source:
protected void startScheduler() { ClusterService clusterService = Framework.getService(ClusterService.class); Duration duration; try { String prop = Framework.getProperty(CLUSTER_START_DURATION_PROP); if (isBlank(prop)) { duration = Duration.ZERO; } else { duration = DurationUtils.parse(prop); } } catch (DateTimeParseException e) { duration = Duration.ZERO; } if (duration.isZero() || duration.isNegative()) { duration = Duration.ofMinutes(1); } Duration pollDelay = Duration.ofSeconds(1); clusterService.runAtomically("start-scheduler", duration, pollDelay, () -> { try { setupScheduler(); } catch (IOException | SchedulerException e) { throw new NuxeoException(e); } }); }

Target:
protected void startScheduler() { ClusterService clusterService = Framework.getService(ClusterService.class); String prop = Framework.getProperty(CLUSTER_START_DURATION_PROP); Duration duration = DurationUtils.parsePositive(prop, CLUSTER_START_DURATION_DEFAULT); Duration pollDelay = Duration.ofSeconds(1); clusterService.runAtomically("start-scheduler", duration, pollDelay, () -> { try { setupScheduler(); } catch (IOException | SchedulerException e) { throw new NuxeoException(e); } }); }
Source:
private int persistColumnStats(Hive db) throws HiveException, MetaException, IOException { ColumnStatistics colStats = constructColumnStatsFromInput(); SetPartitionsStatsRequest request = new SetPartitionsStatsRequest(Collections.singletonList(colStats)); if (work.getColStats() != null) { String dbName = colStats.getStatsDesc().getDbName(); String tblName = colStats.getStatsDesc().getTableName(); Table tbl = db.getTable(dbName, tblName); long writeId = work.getWriteId(); if (AcidUtils.isTransactionalTable(tbl)) { ValidWriteIdList writeIds; if (writeId <= 0) { Long tmpWriteId = ReplUtils.getMigrationCurrentTblWriteId(conf); if (tmpWriteId == null) { throw new HiveException("DDLTask : Write id is not set in the config by open txn task for migration"); } writeId = tmpWriteId; } writeIds = new ValidReaderWriteIdList(TableName.getDbTable(dbName, tblName), new long[0], new BitSet(), writeId); request.setValidWriteIdList(writeIds.toString()); request.setWriteId(writeId); } } db.setPartitionColumnStatistics(request); return 0; }

Target:
private int persistColumnStats(Hive db) throws HiveException, MetaException, IOException { ColumnStatistics colStats = constructColumnStatsFromInput(); SetPartitionsStatsRequest request = new SetPartitionsStatsRequest(Collections.singletonList(colStats)); if (work.getColStats() != null) { String dbName = colStats.getStatsDesc().getDbName(); String tblName = colStats.getStatsDesc().getTableName(); Table tbl = db.getTable(dbName, tblName); long writeId = work.getWriteId(); if (AcidUtils.isTransactionalTable(tbl)) { ValidWriteIdList writeIds; if (work.getIsMigratingToTxn()) { Long tmpWriteId = ReplUtils.getMigrationCurrentTblWriteId(conf); if (tmpWriteId == null) { throw new HiveException("DDLTask : Write id is not set in the config by open txn task for migration"); } writeId = tmpWriteId; } writeIds = new ValidReaderWriteIdList(TableName.getDbTable(dbName, tblName), new long[0], new BitSet(), writeId); request.setValidWriteIdList(writeIds.toString()); request.setWriteId(writeId); } } db.setPartitionColumnStatistics(request); return 0; }
Source:
public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria) { Map<String, String> namedGroups = new HashMap<>(); if (userRegex.isPresent()) { Matcher userMatcher = userRegex.get().matcher(criteria.getUser()); if (!userMatcher.matches()) { return Optional.empty(); } namedGroups.putAll(getNamedGroups(userRegex.get(), criteria.getUser())); } if (sourceRegex.isPresent()) { String source = criteria.getSource().orElse(""); if (!sourceRegex.get().matcher(source).matches()) { return Optional.empty(); } namedGroups.putAll(getNamedGroups(sourceRegex.get(), source)); } if (!clientTags.isEmpty() && !criteria.getTags().containsAll(clientTags)) { return Optional.empty(); } if (queryType.isPresent()) { String contextQueryType = criteria.getQueryType().orElse(""); if (!queryType.get().equalsIgnoreCase(contextQueryType)) { return Optional.empty(); } } namedGroups.putIfAbsent("USER", criteria.getUser()); if (criteria.getSource().isPresent()) { namedGroups.putIfAbsent("SOURCE", criteria.getSource().get()); } VariableMap map = new VariableMap(namedGroups); ResourceGroupId id = group.expandTemplate(map); if (VARIABLE_PATTERN.matcher(id.toString()).find()) { List<String> variables = map.getVariables().keySet().stream() .map(Pattern::toString) .map(v -> v.substring(4, v.length() - 3)).collect(Collectors.toList()); throw new IllegalArgumentException(format("Unresolved variable in resource group '%s', available: %s", id, variables)); } return Optional.of(new SelectionContext<>(id, map)); }

Target:
public Optional<SelectionContext<VariableMap>> match(SelectionCriteria criteria) { Map<String, String> variables = new HashMap<>(); if (userRegex.isPresent()) { Matcher userMatcher = userRegex.get().matcher(criteria.getUser()); if (!userMatcher.matches()) { return Optional.empty(); } addVariableValues(userRegex.get(), criteria.getUser(), variables); } if (sourceRegex.isPresent()) { String source = criteria.getSource().orElse(""); if (!sourceRegex.get().matcher(source).matches()) { return Optional.empty(); } addVariableValues(sourceRegex.get(), source, variables); } if (!clientTags.isEmpty() && !criteria.getTags().containsAll(clientTags)) { return Optional.empty(); } if (queryType.isPresent()) { String contextQueryType = criteria.getQueryType().orElse(""); if (!queryType.get().equalsIgnoreCase(contextQueryType)) { return Optional.empty(); } } variables.putIfAbsent(USER_VARIABLE, criteria.getUser()); variables.putIfAbsent(SOURCE_VARIABLE, criteria.getSource().orElse("")); VariableMap map = new VariableMap(variables); ResourceGroupId id = group.expandTemplate(map); return Optional.of(new SelectionContext<>(id, map)); }