auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected NIOServerCnxn createConnection(SocketChannel sock, SelectionKey sk, SelectorThread selectorThread) throws IOException { NIOServerCnxn cnxn = null; <START> if (serverCnxnClassCtr != null) { <END> try { cnxn = serverCnxnClassCtr.newInstance(zkServer, sock, sk, this, selectorThread); } catch (InstantiationException e1) { LOG.debug("Can not instantiate class for " + serverCnxnClassCtr.getName() + ". Using NIOServerCnxn"); } catch (IllegalAccessException e1) { LOG.debug("IllegalAccessException for " + serverCnxnClassCtr.getName() + ". Using NIOServerCnxn"); } catch (InvocationTargetException e1) { LOG.debug("InvocationTargetException for " + serverCnxnClassCtr.getName() + ". Using NIOServerCnxn"); } catch (Throwable t) { LOG.debug("Unknown Exception while dealing with: . Using NIOServerCnxn", serverCnxnClassCtr.getName()); } } if (cnxn == null) { cnxn = new NIOServerCnxn(zkServer, sock, sk, this, selectorThread); } return cnxn; }</code><technical_language>set serverCnxnClassCtr NIOServerCnxn default avoid right constructor time want create a new connection (a bit of a hot path)</technical_language>

Target:
protected NIOServerCnxn createConnection(SocketChannel sock, SelectionKey sk, SelectorThread selectorThread) throws IOException { try { return serverCnxnClassCtr.newInstance(zkServer, sock, sk, this, selectorThread); } catch (Throwable t) { throw new IOException("Can not instantiate class for " + serverCnxnClassCtr.getName(), t); } }
Source:
<code>private Mac getHMAC() throws NoSuchAlgorithmException, CloneNotSupportedException, InvalidKeyException { lock.readLock().lock(); try { if (lastSecretKey != null && !isKeyExpired()) { if (hmac != null) { return (Mac) hmac.clone(); } else { Mac hmac = Mac.getInstance("HmacSHA256"); hmac.init(lastSecretKey); return hmac; <START> } <END> } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (hmac == null) { hmac = Mac.getInstance("HmacSHA256"); hmac.init(generateSecretKey()); } else if (isKeyExpired()) { hmac.init(generateSecretKey()); } return (Mac) hmac.clone(); } catch (CloneNotSupportedException ex) { Mac hmac = this.hmac; this.hmac = null; return hmac; } finally { lock.writeLock().unlock(); } }</code><technical_language>is purpose of this new code ? If clone is supported new hmac generation result in this.hmac=null. Is avoid generate hmac in write lock</technical_language>

Target:
private Mac getHMAC() throws GeneralSecurityException { lock.readLock().lock(); try { if (lastSecretKey != null && !isKeyExpired()) { return createHMAC(); } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (lastSecretKey == null) { generateSecretKey(); hmac = Mac.getInstance("HmacSHA256"); hmac.init(lastSecretKey); return (Mac) hmac.clone(); } else if (isKeyExpired()) { generateSecretKey(); } return createHMAC(); } catch (CloneNotSupportedException ex) { Mac hmac = this.hmac; this.hmac = null; return hmac; } finally { lock.writeLock().unlock(); } }
Source:
<code>public void run() { final IndirectClient client = getClient(); final MockWebContext context = MockWebContext.create(); final String url = client.getRedirectAction(context).getLocation(); logger.warn("Redirect to: \n{}", url); logger.warn("Use credentials: / {}", getLogin(), getPassword()); if (canCancel()) { logger.warn("You can CANCEL the authentication."); } logger.warn("Returned url (copy/paste the fragment starting before the question mark of the query string):"); final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name()); final String returnedUrl = scanner.nextLine().trim(); populateContextWithUrl(context, returnedUrl); <START> final CommonProfile profile = (CommonProfile) client.getCredentials(context).map(credentials -> <END> client.getUserProfile((Credentials) credentials, context) ).orElse(null); logger.debug("userProfile: {}", profile); if (profile != null || !canCancel()) { verifyProfile(profile); logger.warn("## Java serialization"); final JavaSerializationHelper javaSerializationHelper = new JavaSerializationHelper(); byte[] bytes = javaSerializationHelper.serializeToBytes(profile); final CommonProfile profile2 = (CommonProfile) javaSerializationHelper.unserializeFromBytes(bytes); verifyProfile(profile2); } logger.warn("################"); logger.warn("Test successful!"); }</code><technical_language>orElse(null) :)</technical_language>

Target:
public void run() { final IndirectClient client = getClient(); final MockWebContext context = MockWebContext.create(); final String url = client.getRedirectAction(context).getLocation(); logger.warn("Redirect to: \n{}", url); logger.warn("Use credentials: / {}", getLogin(), getPassword()); if (canCancel()) { logger.warn("You can CANCEL the authentication."); } logger.warn("Returned url (copy/paste the fragment starting before the question mark of the query string):"); final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name()); final String returnedUrl = scanner.nextLine().trim(); populateContextWithUrl(context, returnedUrl); client.getCredentials(context).map(credentials -> client.getUserProfile((Credentials) credentials, context) ).ifPresent( p -> { CommonProfile profile = (CommonProfile) p; logger.debug("userProfile: {}", profile); if (!canCancel()) { verifyProfile(profile); logger.warn("## Java serialization"); final JavaSerializationHelper javaSerializationHelper = new JavaSerializationHelper(); byte[] bytes = javaSerializationHelper.serializeToBytes(profile); final CommonProfile profile2 = (CommonProfile) javaSerializationHelper.unserializeFromBytes(bytes); verifyProfile(profile2); } } ); logger.warn("################"); logger.warn("Test successful!"); }
Source:
<code>private ListenableFuture<QueryResult<Content>> executeSingleQuery(final Query<Content> query) { final Id contentId = query.getOnlyId(); return Futures.transform(resolve(query, contentId), (ResolvedEquivalents<Content> input) -> { List<Content> equivs = input.get(contentId).asList(); if (equivs.isEmpty()) { throw new UncheckedQueryExecutionException(new NotFoundException(contentId)); } <START> if (equivs.size() == 1) { <END> Content resource = equivs.get(0); return QueryResult.singleResult(resource, query.getContext()); } else { return QueryResult.listResult(equivs, query.getContext(), equivs.size()); } } ); }</code><technical_language>this additional check added</technical_language>

Target:
private ListenableFuture<QueryResult<Content>> executeSingleQuery(final Query<Content> query) { final Id contentId = query.getOnlyId(); return Futures.transform(resolve(query, contentId), (ResolvedEquivalents<Content> input) -> { List<Content> equivs = input.get(contentId).asList(); if (equivs.isEmpty()) { throw new UncheckedQueryExecutionException(new NotFoundException(contentId)); } Content resource = equivs.get(0); return QueryResult.singleResult(resource, query.getContext()); } ); }
Source:
<code>Timer.Sample timerStart(String consumerName, String lifecycle) { if (consumerName == null || consumerName.length() == 0) return null; if (lifecycle == null || lifecycle.length() == 0) return null; <START> Map<String, Timer.Sample> queueTimers = timers.get(consumerName); <END> if (queueTimers == null) { queueTimers = new HashMap<>(); timers.put(consumerName, queueTimers); } String threadLifecycle = lifecycle + Thread.currentThread().getId(); Timer.Sample sampler = queueTimers.get(threadLifecycle); if (sampler == null) { sampler = Timer.start(registry); queueTimers.put(threadLifecycle, sampler); } return sampler; }</code><technical_language>Minor: good case for computeIfAbsent</technical_language>

Target:
Timer.Sample timerStart(String consumerName, String lifecycle) { if (consumerName == null || consumerName.length() == 0) return null; if (lifecycle == null || lifecycle.length() == 0) return null; String threadLifecycle = lifecycle + Thread.currentThread().getId(); String compositeKey = consumerName + threadLifecycle; return timers.computeIfAbsent(compositeKey, k -> Timer.start(registry)); }
Source:
<code>private static SiriusContext fromUnknownEObject(EObject obj) { Session session = <START> SessionManager.INSTANCE.getSession(obj); <END> Resource res = EcoreUtil.getRootContainer(obj).eResource(); EObject semanticElement = null; if (session != null && res != null && session.getSemanticResources().contains(res)) { semanticElement = obj; } return new SiriusContext(obj, session, null, null, semanticElement); }</code><technical_language>Session.of is usefull object</technical_language>

Target:
private static SiriusContext fromUnknownEObject(EObject obj) { Session session = Session.of(obj).orElse(null); Resource res = EcoreUtil.getRootContainer(obj).eResource(); EObject semanticElement = null; if (session != null && res != null && session.getSemanticResources().contains(res)) { semanticElement = obj; } return new SiriusContext(obj, session, null, null, semanticElement); }
Source:
<code><START> public void getPayment_ReturnsPaymentWithCaptureUrl() { <END> publicAuthMock.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID); connectorMock.respondWithChargeFoundAndCaptureUrl(250, GATEWAY_ACCOUNT_ID, CHARGE_ID, CAPTURED, RETURN_URL, DESCRIPTION, REFERENCE, EMAIL, PAYMENT_PROVIDER, CREATED_DATE, SupportedLanguage.ENGLISH, true, REFUND_SUMMARY, SETTLEMENT_SUMMARY, CARD_DETAILS, 0L, 250L); getPaymentResponse(API_KEY, CHARGE_ID) .statusCode(200) .contentType(JSON) .body("_links.capture.href", is(paymentLocationFor(CHARGE_ID) + "/capture")) .body("_links.capture.method", is("POST")); }</code><technical_language>move this test private methods please</technical_language>

Target:
public void getPayment_ReturnsPaymentWithCaptureUrl() { publicAuthMock.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID); connectorMock.respondWithChargeFound(AMOUNT, GATEWAY_ACCOUNT_ID, CHARGE_ID, AWAITING_CAPTURE_REQUEST, RETURN_URL, DESCRIPTION, REFERENCE, EMAIL, PAYMENT_PROVIDER, CREATED_DATE, SupportedLanguage.ENGLISH, true, CHARGE_TOKEN_ID, REFUND_SUMMARY, SETTLEMENT_SUMMARY, CARD_DETAILS, 0L, 0L); getPaymentResponse(API_KEY, CHARGE_ID) .statusCode(200) .contentType(JSON) .body("_links.capture.href", is(paymentLocationFor(CHARGE_ID) + "/capture")) .body("_links.capture.method", is("POST")); }
Source:
<code><START> private void storeWindowIfNeeded(Application application, Accumulator<Object> children, List<WeakReference<Activity>> activities){ <END> List<View>windows = WindowFetcher.getWindowViews(application); if (windows == null){ return; } for (View view : windows) { if (belongToActivity(view, activities)) { continue; } children.store(view); } }</code><technical_language>style nits: spaces {, variable names, functions, etc</technical_language>

Target:
private void storeWindowIfNeeded(Application application, Accumulator<Object> children, List<WeakReference<Activity>> activities) { List<View> rootViews = WindowRootViewCompat.get(application).getRootViews(); for (View view : rootViews) { if (!isDecorViewOfActivity(view, activities)) { children.store(view); } } }
Source:
<code>public SweepDelay(long configPause) { <START> this.initialPause = Math.min(Math.max(MIN_PAUSE_MILLIS, configPause), MAX_PAUSE_MILLIS); <END> this.currentPause = new AtomicLong(initialPause); }</code><technical_language>question want place a cap MAX_PAUSE_MILLIS: a bit unexpected if user configures gap 10 seconds for reason throw away. if ok I sense fail more aggressively. In other words for initial = max(min, config) min = 1 max = max(5000, config) Note if this route need some special integer mathematics in line 47..</technical_language>

Target:
SweepDelay(long configPause) { this.maxPauseMillis = Math.max(DEFAULT_MAX_PAUSE_MILLIS, configPause); this.initialPause = Math.max(MIN_PAUSE_MILLIS, configPause); this.currentPause = new AtomicLong(initialPause); }
Source:
<code>public void readEmptyServerObject() throws Exception { final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas2.yaml").toURI()))); final OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); final SwaggerParseResult result = deserializer.deserialize(rootNode); Assert.assertNotNull(result); final OpenAPI openAPI = result.getOpenAPI(); Assert.assertNotNull(openAPI); <START> assertEquals(openAPI.getServers().get(0).getUrl(),"/"); <END> }</code><technical_language>I double-check this behavior @webron. if assume if is value</technical_language>

Target:
public void readEmptyServerObject() throws Exception { final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas2.yaml.template").toURI()))); final OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); final SwaggerParseResult result = deserializer.deserialize(rootNode); Assert.assertNotNull(result); final OpenAPI openAPI = result.getOpenAPI(); Assert.assertNotNull(openAPI); assertEquals(openAPI.getServers().get(0).getUrl(),"/"); }
Source:
<code>public void startUp(IngestJobContext context) throws IngestModuleException { this.context = context; try { fileManager = Case.getOpenCase().getServices().getFileManager(); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); <START> } <END> }</code><technical_language>Ingest modules need throw IngestModuleException if is error in startUp, a user readable exception message, is displayed user. need wrap NoCurrentCaseException in IngestModuleException throw, log here</technical_language>

Target:
public void startUp(IngestJobContext context) throws IngestModuleException { this.context = context; try { fileManager = Case.getOpenCase().getServices().getFileManager(); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); throw new IngestModuleException(Bundle.ThunderbirdMboxFileIngestModule_noOpenCase_errMsg(), ex); } }
Source:
<code>public void testCategoryAttributeList() { MetacardImpl metacard = new MetacardImpl(); metacard.setAttribute(Core.TITLE, "The Title"); List<HtmlExportCategory> categoryList = new ArrayList<>(); categoryList.add(new HtmlCategoryModel("Core", coreList)); HtmlMetacardModel metacardModel = new HtmlMetacardModel(metacard, categoryList); HtmlExportCategory category = metacardModel.getCategories().get(0); <START> assertTrue(category.getAttributeList().contains(Core.TITLE)); <END> }</code><technical_language>Or, assertThat(category.getAttributeList(), hasItem(Core.TITLE)) (this print a more useful message test fails)</technical_language>

Target:
public void testCategoryAttributeList() { MetacardImpl metacard = new MetacardImpl(); metacard.setAttribute(Core.TITLE, METACARD_TITLE); List<HtmlExportCategory> categoryList = new ArrayList<>(); categoryList.add(new HtmlCategoryModel("Core", coreList)); HtmlMetacardModel metacardModel = new HtmlMetacardModel(metacard, categoryList); HtmlExportCategory category = metacardModel.getCategories().get(0); assertThat(category.getAttributes(), hasItem(Core.TITLE)); }
Source:
<code>public void scheduleJobs() { SchedulerUtil sched = getSchedulUtil(); int refreshRate = Config.<Integer> getValue(ConfigValues.VdsRefreshRate) * 1000; registeredJobs.add(sched.scheduleAFixedDelayJob( this, "onTimer", new Class[0], new Object[0], refreshRate, refreshRate, TimeUnit.MILLISECONDS)); double availableUpdatesRefreshRate = Config.<Double> getValue(ConfigValues.HostPackagesUpdateTimeInHours); final int HOURS_TO_MINUTES = 60; long rateInMinutes = Math.round(availableUpdatesRefreshRate * HOURS_TO_MINUTES); registeredJobs.add(sched.scheduleAFixedDelayJob( this, "availableUpdates", new Class[0], new Object[0], RandomUtils.nextInt(HOURS_TO_MINUTES) + 1, rateInMinutes, TimeUnit.MINUTES)); vmsRefresher = getVmStatsRefresherFactory().create(this); vmsRefresher.startMonitoring(); hostRefresher = new <START> RefreshHostOnHostConnectionChangeEvent(this); <END> hostRefresher.startMonitoring(); }</code><technical_language>resourceManager here. pass construction</technical_language>

Target:
public void scheduleJobs() { SchedulerUtil sched = getSchedulUtil(); int refreshRate = Config.<Integer> getValue(ConfigValues.VdsRefreshRate) * 1000; registeredJobs.add(sched.scheduleAFixedDelayJob( this, "onTimer", new Class[0], new Object[0], refreshRate, refreshRate, TimeUnit.MILLISECONDS)); double availableUpdatesRefreshRate = Config.<Double> getValue(ConfigValues.HostPackagesUpdateTimeInHours); final int HOURS_TO_MINUTES = 60; long rateInMinutes = Math.round(availableUpdatesRefreshRate * HOURS_TO_MINUTES); registeredJobs.add(sched.scheduleAFixedDelayJob( this, "availableUpdates", new Class[0], new Object[0], RandomUtils.nextInt(HOURS_TO_MINUTES) + 1, rateInMinutes, TimeUnit.MINUTES)); vmsRefresher = getVmStatsRefresherFactory().create(this); vmsRefresher.startMonitoring(); hostRefresher = new RefreshHostOnHostConnectionChangeEvent(this, resourceManager); hostRefresher.startMonitoring(); }
Source:
<code>public CdRom get() { <START> if (QueryHelper.hasMatrixParam(getUriInfo(), CURRENT_CONSTRAINT_PARAMETER)) { <END> VM vm = collection.lookupEntity(guid); if (vm == null) { return notFound(); } if (vm.getCurrentCd() != null) { vm.setIsoPath(vm.getCurrentCd()); } return addLinks(populate(map(vm), vm)); } else { return super.get(); } }</code><technical_language>check of parameter, existence. If URL is "...;current=false" return persistent CDROM, current</technical_language>

Target:
public CdRom get() { final boolean getCurrent = QueryHelper.hasMatrixParam(getUriInfo(), CURRENT_CONSTRAINT_PARAMETER) && !"false".equalsIgnoreCase(QueryHelper.getMatrixConstraint(getUriInfo(), CURRENT_CONSTRAINT_PARAMETER)); if (getCurrent) { VM vm = collection.lookupEntity(guid); if (vm == null) { return notFound(); } if (vm.getCurrentCd() != null) { vm.setIsoPath(vm.getCurrentCd()); } return addLinks(populate(map(vm), vm)); } else { return super.get(); } }
Source:
<code>public String toString() { if (m_tableName == null) { return m_name + "(" + m_index + ")"; } else { <START> return getName(); <END> } }</code><technical_language>Question: If tablename is null, in case is m_index defined (from constructor definition be)? this function is intended if this is for debugging/information thn useful return m_index</technical_language>

Target:
public String toString() { if (getAlias() != null && !getAlias().equals(getColumnName())) { return getAlias() + "(" + getIndex() + ")"; } else { return getName(); } }
Source:
<code>public void pathologicalInputOrderingTest() { final GraphUtils.Graph<Integer> graph = new GraphUtils.Graph<>(); final int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, h = 6, g = 7; graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addNode(f); graph.addNode(h); graph.addNode(e); graph.addNode(g); graph.addEdge(a, h); graph.addEdge(b, f); graph.addEdge(c, h); graph.addEdge(d, f); graph.addEdge(e, h); graph.addEdge(e, f); graph.addEdge(g, a); final Map<Integer, Integer> clusters = graph.cluster(); assertEquals(clusters.size(), 8); <START> final Integer repCluster = clusters.get(a); <END> IntStream.range(0,7).forEach(i -> assertEquals(clusters.get(i), repCluster)); }</code><technical_language>hmm. add getNodes getEdges methods Graph getNodes().stream() instead of clunky range(0,7)</technical_language>

Target:
public void pathologicalInputOrderingTest() { final GraphUtils.Graph<Integer> graph = new GraphUtils.Graph<>(); final int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, h = 6, g = 7; graph.addNode(a); graph.addNode(b); graph.addNode(c); graph.addNode(d); graph.addNode(f); graph.addNode(h); graph.addNode(e); graph.addNode(g); graph.addEdge(a, h); graph.addEdge(b, f); graph.addEdge(c, h); graph.addEdge(d, f); graph.addEdge(e, h); graph.addEdge(e, f); graph.addEdge(g, a); final Map<Integer, Integer> clusters = graph.cluster(); assertEquals(clusters.size(), 8); final Integer repCluster = clusters.get(a); graph.getNodes().forEach(i -> assertEquals(clusters.get(i), repCluster)); }
Source:
<code>protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException { boolean isModified= isDocumentModified(); <START> super.releaseDocument(document, pm); <END> try { fCUnit.discardWorkingCopy(); } finally { if (isModified && !isDocumentAcquired()) { if (fCUnit.isWorkingCopy()) fCUnit.reconcile( ICompilationUnit.NO_AST, false , null , null ); else fCUnit.makeConsistent(pm); } } }</code><technical_language>I this code, Lars, want SubMonitor fix this progress monitoring bug while in here. pm is in this method</technical_language>

Target:
protected void releaseDocument(IDocument document, IProgressMonitor pm) throws CoreException { boolean isModified= isDocumentModified(); SubMonitor subMonitor= SubMonitor.convert(pm, 2); super.releaseDocument(document, subMonitor.newChild(1)); try { fCUnit.discardWorkingCopy(); } finally { if (isModified && !isDocumentAcquired()) { if (fCUnit.isWorkingCopy()) fCUnit.reconcile( ICompilationUnit.NO_AST, false , null , subMonitor.newChild(1)); else fCUnit.makeConsistent(subMonitor.newChild(1)); } } subMonitor.setWorkRemaining(0); }
Source:
<code>private void setAccount() throws OrmException, IOException, InvalidSshKeyException, UnloggedFailure { <START> if (!username.matches(Account.USER_NAME_PATTERN)) { <END> throw die("Username '" + username + "'" + " must contain only letters, numbers, _, - or ."); } final Account account; AccountExternalId.Key key = new AccountExternalId.Key(AccountExternalId.SCHEME_USERNAME, username); AccountExternalId accExtId = db.accountExternalIds().get(key); if (accExtId != null) { account = db.accounts().get(accExtId.getAccountId()); } else { throw die("Could not find user : " + username); } Account.Id id = account.getId(); if (newEmail != null) { link(id, newEmail); } if (oldEmail != null) { deleteMail(id, oldEmail); } if (fullName != null && realm.allowsEdit(FieldName.FULL_NAME)) { account.setFullName(fullName); } if (active) { account.setActive(true); } else if (inactive) { account.setActive(false); } final String readAddKey = readSshKey(addSshKey); if (readAddKey != null) { addSshKey(readAddKey, account); } final String readDeleteKey = readSshKey(deleteSshKey); if (readDeleteKey != null) { deleteSshKeys(readDeleteKey, account); } db.accounts().update(Collections.singleton(account)); byIdCache.evict(id); db.close(); }</code><technical_language>[optional] Is this check needed? I this check command simply fail 'Could find user' if invalid username is given. For this good enough</technical_language>

Target:
private void setAccount() throws OrmException, IOException, UnloggedFailure { final Account account = db.accounts().get(id); if (!addEmails.isEmpty()) { for (String email : addEmails) { link(id, email); } } if (!deleteEmails.isEmpty()) { for (String email : deleteEmails) { deleteMail(id, email); } } if (fullName != null) { if (realm.allowsEdit(FieldName.FULL_NAME)) { account.setFullName(fullName); } else { throw new UnloggedFailure(1, "The realm doesn't allow editing names"); } } if (active) { account.setActive(true); } else if (inactive) { account.setActive(false); } addSshKeys = readSshKey(addSshKeys); if (!addSshKeys.isEmpty()) { for (String sshKey : addSshKeys) { addSshKey(sshKey, account); } } deleteSshKeys = readSshKey(deleteSshKeys); if (!deleteSshKeys.isEmpty()) { for (String sshKey : deleteSshKeys) { deleteSshKey(sshKey, account); } } db.accounts().update(Collections.singleton(account)); byIdCache.evict(id); db.close(); }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.workspacePath); <START> builder.append("|"); <END> builder.append(this.fieldDescriptor); return builder.toString(); }</code><technical_language>Better: '|'</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.workspacePath); builder.append('|'); builder.append(this.fieldDescriptor); return builder.toString(); }
Source:
<code>public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { Locale userLocale = (Locale) request.getAttribute(LocaleFilter.LOCALE); if (userLocale == null) { log.warn("Detected Locale is null, setting to default: " + LocaleFilter.DEFAULT_LOCALE); userLocale = LocaleFilter.DEFAULT_LOCALE; } List<BrandingTheme> brandingThemes = brandingManager.getBrandingThemes( <START> request.getServletContext().getInitParameter(APPLICATION_TYPE)); <END> request.setAttribute(THEMES_KEY, brandingThemes); ResourceBundle bundle = ResourceBundle.getBundle(BRANDING_BASE_NAME, userLocale, BrandingResourceBundle.getBrandingControl(BLANK)); Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, userLocale)); chain.doFilter(request, response); }</code><technical_language>+1 for controlling applicationType servlet context param application, more sense providing configuration in source code</technical_language>

Target:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { Locale userLocale = (Locale) request.getAttribute(LocaleFilter.LOCALE); if (userLocale == null) { log.warn("Detected Locale is null, setting to default: " + LocaleFilter.DEFAULT_LOCALE); userLocale = LocaleFilter.DEFAULT_LOCALE; } List<BrandingTheme> brandingThemes = brandingManager.getBrandingThemes(); request.setAttribute(THEMES_KEY, brandingThemes); request.setAttribute(APPLICATION_TYPE, request.getServletContext().getInitParameter(APPLICATION_TYPE)); ResourceBundle bundle = ResourceBundle.getBundle(BRANDING_BASE_NAME, userLocale, BrandingResourceBundle.getBrandingControl(BLANK)); Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, userLocale)); chain.doFilter(request, response); }
Source:
<code>public String toString() { return toStringHelper(this) .add("server", server) .add("user", user) .add("clientTags", clientTags) .add("clientInfo", clientInfo) .add("catalog", catalog) .add("schema", schema) <START> .add("traceToken", traceToken.orElse(null)) <END> .add("timeZone", timeZone) .add("locale", locale) .add("properties", properties) .add("transactionId", transactionId) .toString(); }</code><technical_language>Add .omitNullValues() toString() call</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("server", server) .add("user", user) .add("clientTags", clientTags) .add("clientInfo", clientInfo) .add("catalog", catalog) .add("schema", schema) .add("traceToken", traceToken.orElse(null)) .add("timeZone", timeZone) .add("locale", locale) .add("properties", properties) .add("transactionId", transactionId) .omitNullValues() .toString(); }
Source:
<code>CallArgsImpl addDefaultArgs(CallArgsImpl callArgsImpl) { if(defaultArgs == null || defaultArgs.size()==0) return callArgsImpl; CallerImpl callerImpl = (com.marklogic.client.dataservices.impl.CallManagerImpl.CallerImpl) caller; List<CallField> newCallFields = new ArrayList<CallField>(); if(callArgsImpl.getCallFields()!=null && callArgsImpl.getCallFields().size()!=0) newCallFields.addAll(callArgsImpl.getCallFields()); <START> newCallFields.addAll(defaultArgs); <END> return new CallArgsImpl(callerImpl.getEndpoint(), newCallFields); }</code><technical_language>addDefaultArgs() add CallField for parameters exist in supplied call args. story foresee this, in checking current implementation, assignedParams field of CallArgsImpl need copied augmented added default fields. assignedParams is a Set, easy check a field exists in current call args while iterating default call fields. If existing call fields list is empty null (a good check), assignedParams assumed null. In this case, callFields assignedParams created defaults</technical_language>

Target:
CallArgsImpl addDefaultArgs(CallArgsImpl callArgsImpl) { if(defaultArgs == null || defaultArgs.size()==0) return callArgsImpl; CallerImpl callerImpl = (com.marklogic.client.dataservices.impl.CallManagerImpl.CallerImpl) caller; List<CallField> newCallFields = new ArrayList<CallField>(); Set<String> assignedParams = new HashSet<String>(); if(callArgsImpl.getCallFields()!=null && callArgsImpl.getCallFields().size()!=0) { newCallFields.addAll(callArgsImpl.getCallFields()); assignedParams.addAll(callArgsImpl.getAssignedParams()); } for(CallField i: defaultArgs) { if(!assignedParams.contains(i.getParamName())) { assignedParams.add(i.getParamName()); newCallFields.add(i); } } return new CallArgsImpl(callerImpl.getEndpoint(), newCallFields); }
Source:
<code>public List<ASTAnyTypeBodyDeclaration> getDeclarations() { <START> return findChildrenOfType(ASTAnnotationTypeBody.class) <END> .get(0).findChildrenOfType(ASTAnyTypeBodyDeclaration.class); }</code><technical_language>getFirstChildOfType here. I think, need check for null, empty AnnotationTypeDeclaration a AnnotationBody</technical_language>

Target:
public List<ASTAnyTypeBodyDeclaration> getDeclarations() { return getFirstChildOfType(ASTAnnotationTypeBody.class) .findChildrenOfType(ASTAnyTypeBodyDeclaration.class); }
Source:
<code>private void removeDoneFiles(List<String> dataFileNames) { for (String dataFileName : dataFileNames) { <START> File doneFile = new File(StringUtils.substringBeforeLast(dataFileName, ".") + ".done"); <END> if (doneFile.exists()) { doneFile.delete(); } } }</code><technical_language>Is a constant replace ".done" literal</technical_language>

Target:
private void removeDoneFiles(List<String> dataFileNames) { fileStorageService.removeDoneFiles(dataFileNames); }
Source:
<code>public IdentityClientOptions() { <START> Configuration configuration = Configuration.getGlobalConfiguration().clone(); <END> authorityHost = configuration.contains(configuration.PROPERTY_AZURE_AUTHORITY_HOST) ? configuration.get(configuration.PROPERTY_AZURE_AUTHORITY_HOST) : DEFAULT_AUTHORITY_HOST; maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); }</code><technical_language>Is a need a short lived clone of global configuration? If load static memory environment setting accessed quicker in future</technical_language>

Target:
public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration(); authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, KnownAuthorityHosts.AZURE_CLOUD); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); }
Source:
<code>public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (value.equals(FIRST_EDITION)) { return Optional.of(Localization.lang("edition of book reported as just 1")); } if (bibDatabaseContextEdition.isBiblatexMode() && !ONLY_NUMERALS_OR_LITERALS.test(value.trim())) { return Optional.of(Localization.lang("should contain an integer or a literal")); } if (!bibDatabaseContextEdition.isBiblatexMode()) { <START> if(!isFirstCharDigit(value)) <END> if (!allowIntegerEdition) { if (!FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } } else { if (!ONLY_NUMERALS.test(value.trim()) && !FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } } } return Optional.empty(); }</code><technical_language>Please follow code style: Space if, braces. In case I understood code correctly, this statement is a fail-fast one. In this case, I change code java if (isFirstCharDigit(value) { return Optional.empty(); }</technical_language>

Target:
public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (value.equals(FIRST_EDITION)) { return Optional.of(Localization.lang("edition of book reported as just 1")); } if (bibDatabaseContextEdition.isBiblatexMode() && !ONLY_NUMERALS_OR_LITERALS.test(value.trim())) { return Optional.of(Localization.lang("should contain an integer or a literal")); } if (!bibDatabaseContextEdition.isBiblatexMode()) { if (!isFirstCharDigit(value) && (!allowIntegerEdition) && !FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } else { if (!ONLY_NUMERALS.test(value.trim()) && !FIRST_LETTER_CAPITALIZED.test(value.trim())) { return Optional.of(Localization.lang("should have the first letter capitalized")); } } } return Optional.empty(); }
Source:
<code>public double[] getMzValues() { double[] mzValues = null; <START> Integer numOfDataPoints = this.numOfDataPoints; <END> if (getMzBinaryDataInfo().getArrayLength() != numOfDataPoints) { logger.warn( "m/z binary data array contains a different array length from the default array length of the scan (#" + getScanNumber() + ")"); } Integer precision; EnumSet<MzMLBinaryDataInfo.MzMLCompressionType> compressions = EnumSet.noneOf(MzMLBinaryDataInfo.MzMLCompressionType.class); try { switch (getMzBinaryDataInfo().getBitLength()) { case THIRTY_TWO_BIT_FLOAT: case THIRTY_TWO_BIT_INTEGER: precision = 32; break; case SIXTY_FOUR_BIT_FLOAT: case SIXTY_FOUR_BIT_INTEGER: precision = 64; break; default: precision = null; } compressions.add(getMzBinaryDataInfo().getCompressionType()); InputStream encodedIs = new ByteBufferInputStreamAdapter(mappedByteBufferInputStream, getMzBinaryDataInfo().getPosition(), getMzBinaryDataInfo().getEncodedLength()); InputStream decodedIs = Base64.getDecoder().wrap(encodedIs); byte[] decodedData = IOUtils.toByteArray(decodedIs); mzValues = MzMLMZPeaksDecoder .decode(decodedData, decodedData.length, precision, numOfDataPoints, compressions) .getDecodedArray(); } catch (Exception e) { throw (new MSDKRuntimeException(e)); } return mzValues; }</code><technical_language>I need create Integer numOfDataPoints, this.numOfDataPoints</technical_language>

Target:
public double[] getMzValues() { double[] mzValues = null; if (getMzBinaryDataInfo().getArrayLength() != numOfDataPoints) { logger.warn( "m/z binary data array contains a different array length from the default array length of the scan (#" + getScanNumber() + ")"); } Integer precision; EnumSet<MzMLBinaryDataInfo.MzMLCompressionType> compressions = EnumSet.noneOf(MzMLBinaryDataInfo.MzMLCompressionType.class); try { switch (getMzBinaryDataInfo().getBitLength()) { case THIRTY_TWO_BIT_FLOAT: case THIRTY_TWO_BIT_INTEGER: precision = 32; break; case SIXTY_FOUR_BIT_FLOAT: case SIXTY_FOUR_BIT_INTEGER: precision = 64; break; default: precision = null; } compressions.add(getMzBinaryDataInfo().getCompressionType()); InputStream encodedIs = new ByteBufferInputStreamAdapter(mappedByteBufferInputStream, getMzBinaryDataInfo().getPosition(), getMzBinaryDataInfo().getEncodedLength()); InputStream decodedIs = Base64.getDecoder().wrap(encodedIs); byte[] decodedData = IOUtils.toByteArray(decodedIs); mzValues = MzMLMZPeaksDecoder .decode(decodedData, decodedData.length, precision, numOfDataPoints, compressions) .getDecodedArray(); } catch (Exception e) { throw (new MSDKRuntimeException(e)); } return mzValues; }
Source:
<code><START> protected IFile createBookmarksFile(IFolder bookmarksFolder, String editorInputType, IProgressMonitor monitor) throws CoreException, OperationCanceledException { <END> IFile file = getBookmarksFile(); if (!file.exists()) { final IFile bookmarksFile = bookmarksFolder.getFile(BOOKMARKS_HIDDEN_FILE); if (!bookmarksFile.exists()) { final InputStream source = new ByteArrayInputStream(new byte[0]); bookmarksFile.create(source, IResource.FORCE | IResource.HIDDEN, monitor); } file.createLink(bookmarksFile.getLocation(), IResource.REPLACE | IResource.HIDDEN, monitor); file.setPersistentProperty(TmfCommonConstants.TRACETYPE, editorInputType); } return file; }</code><technical_language>create submonitors in this method</technical_language>

Target:
protected IFile createBookmarksFile(IFolder bookmarksFolder, String editorInputType, IProgressMonitor monitor) throws CoreException, OperationCanceledException { SubMonitor subMonitor = SubMonitor.convert(monitor, 2); IFile file = getBookmarksFile(); if (!file.exists()) { final IFile bookmarksFile = bookmarksFolder.getFile(BOOKMARKS_HIDDEN_FILE); if (!bookmarksFile.exists()) { final InputStream source = new ByteArrayInputStream(new byte[0]); bookmarksFile.create(source, IResource.FORCE | IResource.HIDDEN, subMonitor.split(1)); } file.createLink(bookmarksFile.getLocation(), IResource.REPLACE | IResource.HIDDEN, subMonitor.split(1)); file.setPersistentProperty(TmfCommonConstants.TRACETYPE, editorInputType); } return file; }
Source:
<code>protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException { Collection<Player> targets; if (args.length > 0) { targets = new ArrayList<>(); <START> for (int i = 0; args.length > i; i++) { <END> targets.add(getPlayer(server, sender, args, i).getBase()); } } else { targets = ess.getOnlinePlayers(); } ess.getTNTListener().enable(); for (Player player : targets) { if (player == null) { continue; } player.sendMessage(tl("nuke")); final Location loc = player.getLocation(); final World world = loc.getWorld(); for (int x = -10; x <= 10; x += 5) { for (int z = -10; z <= 10; z += 5) { world.spawn(new Location(world, loc.getBlockX() + x, world.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z), TNTPrimed.class); } } } }</code><technical_language>suggestion for (int i = 0; i < args.length; ++i) {</technical_language>

Target:
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException { Collection<Player> targets; if (args.length > 0) { targets = new ArrayList<>(); for (int i = 0; i < args.length; ++i) { targets.add(getPlayer(server, sender, args, i).getBase()); } } else { targets = ess.getOnlinePlayers(); } ess.getTNTListener().enable(); for (Player player : targets) { if (player == null) { continue; } player.sendMessage(tl("nuke")); final Location loc = player.getLocation(); final World world = loc.getWorld(); for (int x = -10; x <= 10; x += 5) { for (int z = -10; z <= 10; z += 5) { world.spawn(new Location(world, loc.getBlockX() + x, world.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z), TNTPrimed.class); } } } }
Source:
<code>public void returnsCorrectInputWithByteArray() throws Exception { final byte[] bytes = new Utf8String("ByteArray returnsCorrectInput!").asBytes(); MatcherAssert.assertThat( <START> "ByteArray doesn't provide correct bytes", <END> new BytesOf(new Body.ByteArray(bytes)).asBytes(), new IsEqual<>(bytes) ); }</code><technical_language>@Serranya Please, add name "body content" message more clear specific. generic</technical_language>

Target:
public void returnsCorrectInputWithByteArray() throws Exception { final byte[] bytes = new Utf8String("ByteArray returnsCorrectInput!").asBytes(); MatcherAssert.assertThat( "Body content of Body.ByteArray doesn't provide the correct bytes", new BytesOf(new Body.ByteArray(bytes)).asBytes(), new IsEqual<>(bytes) ); }
Source:
<code>public synchronized void addUserTuneListener(UserTuneListener listener) { <START> userTuneListeners.add(listener); <END> }</code><technical_language>synchronized (userTuneListeners) { userTuneListeners.add(listener) } here</technical_language>

Target:
public void addUserTuneListener(UserTuneListener listener) { synchronized (userTuneListeners) { userTuneListeners.add(listener); } }
Source:
<code>public boolean canHandleSelection(Object selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; <START> Object element = structuredSelection.getFirstElement(); <END> if (element instanceof SpecHierarchyImpl) { return true; } } return false; }</code><technical_language>selection is null? Otherwise, a null check call getFirstElement() is in order</technical_language>

Target:
public boolean canHandleSelection(Object selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (!(structuredSelection.getFirstElement() == null)) { Object element = structuredSelection.getFirstElement(); if (element instanceof SpecHierarchyImpl) { return true; } } } return false; }
Source:
<code>public synchronized void commit() throws IOException { if (logStream != null) { logStream.flush(); } for (FileOutputStream log : streamsToFlush) { log.flush(); if (forceSync) { long startSyncNS = System.nanoTime(); FileChannel channel = log.getChannel(); channel.force(false); syncElapsedMS = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startSyncNS); if (syncElapsedMS > fsyncWarningThresholdMS) { if(serverStats != null) { serverStats.incrementFsyncThresholdExceedCount(); } LOG.warn("fsync-ing the write ahead log in " + Thread.currentThread().getName() + " took " + syncElapsedMS + "ms which will adversely effect operation latency. " <START> + "File size is " + channel.size() + " bytes and " <END> + FSYNC_WARNING_THRESHOLD_MS_PROPERTY + " is " + fsyncWarningThresholdMS + ". " + "See the ZooKeeper troubleshooting guide"); } } } while (streamsToFlush.size() > 1) { streamsToFlush.removeFirst().close(); } }</code><technical_language>cleaner change logger format placeholder {}</technical_language>

Target:
public synchronized void commit() throws IOException { if (logStream != null) { logStream.flush(); } for (FileOutputStream log : streamsToFlush) { log.flush(); if (forceSync) { long startSyncNS = System.nanoTime(); FileChannel channel = log.getChannel(); channel.force(false); syncElapsedMS = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startSyncNS); if (syncElapsedMS > fsyncWarningThresholdMS) { if(serverStats != null) { serverStats.incrementFsyncThresholdExceedCount(); } LOG.warn("fsync-ing the write ahead log in " + Thread.currentThread().getName() + " took " + syncElapsedMS + "ms which will adversely effect operation latency. " + "File size is " + channel.size() + " bytes. " + "See the ZooKeeper troubleshooting guide"); } } } while (streamsToFlush.size() > 1) { streamsToFlush.removeFirst().close(); } }
Source:
<code>protected JsonMessageHandlerForRequestProcessor jsonMessageHandlerForRequestProcessor(String pluginVersion) { <START> throw new UnsupportedOperationException("Fetch PluginSettings is not supported by Authorization Endpoint."); <END> }</code><technical_language>message mentions wrong endpoint</technical_language>

Target:
protected JsonMessageHandlerForRequestProcessor jsonMessageHandlerForRequestProcessor(String pluginVersion) { throw new UnsupportedOperationException("Fetch PluginSettings is not supported by Task Endpoint."); }
Source:
<code>private String getConnectionSettingsDetectionScriptName() { final String osName = System.getProperty("os.name"); if (osName.toLowerCase().startsWith("win")) { return "script.bat"; } else if (osName.toLowerCase().startsWith("mac") <START> || osName.toLowerCase().contains("nix")) { END> return "script.sh"; } else { return null; } }</code><technical_language>Linux return a string "nix" in it. returns Linux. intend this catch Linux well</technical_language>

Target:
private String getConnectionSettingsDetectionScriptName() { final String osName = System.getProperty("os.name"); if (osName.toLowerCase().startsWith("win")) { return "script.bat"; } else if (osName.toLowerCase().startsWith("mac") || osName.toLowerCase().contains("linux") || osName.toLowerCase().contains("nix")) { return "script.sh"; } else { return null; } }
Source:
<code>private static final String escapeWhitespace(String value) { <START> return value.replaceAll("[\n\r\t]", " "); END> }</code><technical_language>this replace CRLF 2 blanks, is this intended</technical_language>

Target:
private static final String escapeWhitespace(String value) { final StringBuilder escaped = new StringBuilder(value); final int length = escaped.length(); for (int i = 0; i < length; i++) { char c = escaped.charAt(i); if (c != ' ' && Character.isWhitespace(c)) escaped.setCharAt(i, ' '); } return escaped.toString(); }
Source:
<code>public InputStream getInputStream() { try { return channel.getInputStream(); } catch (IOException e) { <START> e.printStackTrace(); <END> return null; } }</code><technical_language>Exception logged</technical_language>

Target:
public InputStream getInputStream() { try { return channel.getInputStream(); } catch (IOException e) { Activator.log(e); return null; } }
Source:
<code>public static String toString(Node node, int indent, Map<String, String> namespaces, Optional<String> optionalCharset) { String charset = optionalCharset.orElse(StandardCharsets.UTF_8.toString()); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); if (indent > -1) { transformer.setOutputProperty(OutputKeys.INDENT, TRANSFORMER_INDENT_TRUE); transformer.setOutputProperty(TRANSFORMER_INDENT_VALUE, Integer.toString(indent)); } transformer.setOutputProperty(OutputKeys.ENCODING, charset); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); transformer.transform(new DOMSource(toDocument(node, namespaces)), new StreamResult(buffer)); return new String(buffer.toByteArray(), charset); } catch (TransformerException | UnsupportedEncodingException e) { String message = e.getMessage(); <START> throw new RuntimeException(message != null ? message : e.getClass().getSimpleName(), e); <END> } }</code><technical_language>Is a RuntimeException a good solution in this case</technical_language>

Target:
public static String toString(Node node, int indent, Map<String, String> namespaces, Optional<String> optionalCharset) { String charset = optionalCharset.orElse(StandardCharsets.UTF_8.toString()); try { try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { toStream(node, buffer, indent, namespaces, optionalCharset); return new String(buffer.toByteArray(), charset); } } catch (IOException e) { String message = e.getMessage(); throw new IllegalArgumentException(message != null ? message : e.getClass().getSimpleName(), e); } }
Source:
<code><START> public void testImportPMML2() throws IOException { <END> try (Reader defsReader = getReader("pmml/KiePMMLTree.dmn", DMNRuntimeTest.class);) { final Definitions defs = getDefinitions(defsReader, "<LINK_0>", "TestTreeDMN"); ValidatorImportReaderResolver resolver = (ns, name, i) -> { if (ns.equals(defs.getNamespace()) && name.equals(defs.getName()) && i.equals(defs.getImport().get(0).getLocationURI())) { return getReader("pmml/test_tree.pmml", DMNRuntimeTest.class); } else { return null; } }; final List<DMNMessage> messages = validator.validateUsing(Validation.VALIDATE_MODEL, Validation.VALIDATE_COMPILATION) .usingImports(resolver) .theseModels(defs); assertThat(ValidatorUtil.formatMessages(messages), messages.size(), is(0)); } }</code><technical_language>good me, abstracting provision of imports user of DMNValidator</technical_language>

Target:
public void testImportPMML2() throws IOException { try (Reader defsReader = getReader("KiePMMLScoreCard_wInputType.dmn", DMNRuntimePMMLTest.class);) { final Definitions defs = getDefinitions(defsReader, "<LINK_1>", "KiePMMLScoreCard"); ValidatorImportReaderResolver resolver = (ns, name, i) -> { if (ns.equals(defs.getNamespace()) && name.equals(defs.getName()) && i.equals(defs.getImport().get(0).getLocationURI())) { return getReader("test_scorecard.pmml", DMNRuntimePMMLTest.class); } else { return null; } }; final List<DMNMessage> messages = validator.validateUsing(Validation.VALIDATE_MODEL, Validation.VALIDATE_COMPILATION) .usingImports(resolver) .theseModels(defs); assertThat(ValidatorUtil.formatMessages(messages), messages.size(), is(0)); } }