auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean isMethodAGetter(final ASTMethod method) { <START> final Pattern p = Pattern.compile("^(string|void)$", Pattern.CASE_INSENSITIVE); <END> final boolean startsWithGet = method.getNode().getMethodInfo().getCanonicalName().startsWith("get"); final boolean voidOrString = p .matcher(method.getNode().getMethodInfo().getEmitSignature().getReturnType().getApexName()).matches(); return (startsWithGet && !voidOrString); }</code><technical_language>compiling a Pattern is expensive. this is a constant string, move this a static final field</technical_language>

Target:
private boolean isMethodAGetter(final ASTMethod method) { final boolean startsWithGet = method.getNode().getMethodInfo().getCanonicalName().startsWith("get"); final boolean voidOrString = IS_STRING_OR_VOID_PATTERN .matcher(method.getNode().getMethodInfo().getEmitSignature().getReturnType().getApexName()).matches(); return (startsWithGet && !voidOrString); }
Source:
<code>public void executeTask() throws MojoExecutionException, MojoFailureException { if (serverId == null) { File currentProperties = wizard.getCurrentServerPath(); if (currentProperties != null) serverId = currentProperties.getName(); } serverId = wizard.promptForExistingServerIdIfMissing(serverId); Server server = Server.loadServer(serverId); File serverPath = server.getServerDirectory(); serverPath.mkdirs(); File userDir = new File(System.getProperty("user.dir")); if (Project.hasProject(userDir)) { Project config = Project.loadProject(userDir); if (config.isOpenmrsModule()) { String artifactId = config.getArtifactId(); String groupId = config.getGroupId(); String version = config.getVersion(); if ((artifactId != null) && (groupId != null) && version != null) { getLog().info("OpenMRS module detected, installing before run..."); Deploy deployer = new Deploy(this); deployer.deployModule(serverPath.getName(), groupId, artifactId, version); } } } try { File tempFolder = createTempReactorProject(server); cleanInstallModule(tempFolder.getPath()); deleteTempReactorProject(tempFolder); deployWatchedModules(server); } catch (MavenInvocationException e) { <START> throw new MojoFailureException(e.getMessage()); <END> } if (Boolean.FALSE.equals(fork)) { new RunTomcat(serverId, port, wizard).execute(); } else { runInFork(server); } }</code><technical_language>try preserve a stacktrace. new MojoFailureException("Failed build watched modules", e);</technical_language>

Target:
public void executeTask() throws MojoExecutionException, MojoFailureException { if (serverId == null) { File currentProperties = wizard.getCurrentServerPath(); if (currentProperties != null) serverId = currentProperties.getName(); } serverId = wizard.promptForExistingServerIdIfMissing(serverId); Server server = Server.loadServer(serverId); File serverPath = server.getServerDirectory(); serverPath.mkdirs(); File userDir = new File(System.getProperty("user.dir")); if (Project.hasProject(userDir)) { Project config = Project.loadProject(userDir); if (config.isOpenmrsModule()) { String artifactId = config.getArtifactId(); String groupId = config.getGroupId(); String version = config.getVersion(); if ((artifactId != null) && (groupId != null) && version != null) { getLog().info("OpenMRS module detected, installing before run..."); Deploy deployer = new Deploy(this); deployer.deployModule(serverPath.getName(), groupId, artifactId, version); } } } if (server.hasWatchedProjects()) { File tempFolder = createTempReactorProject(server); cleanInstallServerProject(tempFolder.getPath()); deleteTempReactorProject(tempFolder); try { deployWatchedModules(server); } catch (MavenInvocationException e) { throw new MojoFailureException("Failed to deploy watched modules", e); } } if (Boolean.FALSE.equals(fork)) { new RunTomcat(serverId, port, wizard).execute(); } else { runInFork(server); } }
Source:
<code>public static Collection testSheetParameters() { List<Object[]> parametersList = new ArrayList<>(); <START> Object[] currentParameterList; <END> File testFile = new File(ConferenceSchedulingScoreRulesXlsxTest.class.getResource(testFileName).getFile()); try (InputStream in = new BufferedInputStream(new FileInputStream(testFile))) { XSSFWorkbook workbook = new XSSFWorkbook(in); ConferenceSolution initialSolution = new ConferenceSchedulingXlsxFileIO(true).read(testFile); TestConferenceSchedulingScoreRulesReader testFileReader = new TestConferenceSchedulingScoreRulesReader(workbook, initialSolution); while ((currentParameterList = testFileReader.nextTestSheetParameterList()) != null) { parametersList.add(currentParameterList); } } catch (IOException | RuntimeException e) { throw new IllegalStateException("Failed reading inputSolutionFile (" + testFile.getName() + ").", e); } return parametersList; }</code><technical_language>This is a nitpicking improve readability a bit - currentParameterList declared right while loop, this is place for time</technical_language>

Target:
public static Collection testSheetParameters() { List<Object[]> parametersList = new ArrayList<>(); File testFile = new File(ConferenceSchedulingScoreRulesXlsxTest.class.getResource(testFileName).getFile()); try (InputStream in = new BufferedInputStream(new FileInputStream(testFile))) { XSSFWorkbook workbook = new XSSFWorkbook(in); ConferenceSolution initialSolution = new ConferenceSchedulingXlsxFileIO(true).read(testFile); TestConferenceSchedulingScoreRulesReader testFileReader = new TestConferenceSchedulingScoreRulesReader(workbook, initialSolution); Object[] currentParameterList; while ((currentParameterList = testFileReader.nextTestSheetParameterList()) != null) { parametersList.add(currentParameterList); } } catch (IOException | RuntimeException e) { throw new IllegalStateException("Failed reading inputSolutionFile (" + testFile.getName() + ").", e); } return parametersList; }
Source:
<code>public static void main(String[] args) { long start = 0; <START> start = System.currentTimeMillis(); <END> System.out.println("createObjectArrays: ..."); createObjectArrays(); System.out.println("createObjectArrays: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("createPrimitiveArrays: ..."); createPrimitiveArrays(); System.out.println("createPrimitiveArrays: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("writeByteArrayOutputStream: ..."); writeByteArrayOutputStream(); System.out.println("writeByteArrayOutputStream: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("concatStrings: ..."); concatStrings(); System.out.println("concatStrings: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("getBytes: ..."); getBytes(); System.out.println("getBytes: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("synchronize: ..."); synch(); System.out.println("synchronize: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("hashtable: ..."); hashtable(); System.out.println("hashtable: " + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); System.out.println("arrayTypeCheck: ..."); arrayTypeCheck(); System.out.println("arrayTypeCheck: " + (System.currentTimeMillis() - start)); }</code><technical_language>In benchmarks, JVM.monotonicTimeMillis (it performance.now() instead of Date.now())</technical_language>

Target:
public static void main(String[] args) { size = 1024; begin(); start = JVM.monotonicTimeMillis(); createObjectArrays(); createPrimitiveArrays(); writeByteArrayOutputStream(); concatStrings(); getBytes(); synch(); hashtable(); arrayTypeCheck(); finish("startup"); size = 1024 * 256; long start = JVM.monotonicTimeMillis(); begin(); createObjectArrays(); finish("createObjectArrays"); begin(); createPrimitiveArrays(); finish("createPrimitiveArrays"); begin(); writeByteArrayOutputStream(); finish("writeByteArrayOutputStream"); begin(); concatStrings(); finish("concatStrings"); begin(); getBytes(); finish("getBytes"); begin(); synch(); finish("synchronize"); begin(); hashtable(); finish("hashtable"); begin(); arrayTypeCheck(); finish("arrayTypeCheck"); System.out.println(); System.out.println("Total: " + (JVM.monotonicTimeMillis() - start)); }
Source:
<code>public static Charge from(LedgerTransaction transaction) { String externalRefundState = null; if (transaction.getRefundSummary() != null ) { externalRefundState = transaction.getRefundSummary().getStatus(); } return new Charge( transaction.getTransactionId(), transaction.getAmount(), null, transaction.getGatewayTransactionId(), transaction.getCorporateCardSurcharge(), externalRefundState, <START> false <END> ); }</code><technical_language>I this true</technical_language>

Target:
public static Charge from(LedgerTransaction transaction) { String externalRefundState = null; String externalStatus = null; if (transaction.getRefundSummary() != null ) { externalRefundState = transaction.getRefundSummary().getStatus(); } if (transaction.getState() != null) { externalStatus = transaction.getState().getStatus(); } return new Charge( transaction.getTransactionId(), transaction.getAmount(), null, externalStatus, transaction.getGatewayTransactionId(), transaction.getCorporateCardSurcharge(), externalRefundState, true ); }
Source:
<code>public String toString() { <START> return "DoubleFirstAggregatorFactory{" + <END> "name='" + name + '\'' + ", fieldName='" + fieldName + '\'' + '}'; }</code><technical_language>DoubleLast</technical_language>

Target:
public String toString() { return "DoubleLastAggregatorFactory{" + "name='" + name + '\'' + ", fieldName='" + fieldName + '\'' + '}'; }
Source:
<code>protected void downloadArtifactTo(final URL artifactUrl, final File pluginFile, final IAsyncResultHandler<File> handler) { HttpClient client; <START> HttpClientOptions clientOpts=new HttpClientOptions(); <END> int port = artifactUrl.getPort(); if (artifactUrl.getProtocol().equals("https")) { clientOpts.setSsl(true); if (port == -1) port = 443; if(artifactUrl.getHost().equals("localhost") ||artifactUrl.getHost().equals("127.0.0.1")){ clientOpts.setProxyOptions(null); }else{ if(sslProxy!=null) clientOpts.setProxyOptions(sslProxy); } }else{ clientOpts.setSsl(false); if (port == -1) port = 80; if(artifactUrl.getHost().equals("localhost") ||artifactUrl.getHost().equals("127.0.0.1")){ clientOpts.setProxyOptions(null); }else{ if(proxy!=null) clientOpts.setProxyOptions(proxy); } } client = vertx.createHttpClient(clientOpts); final HttpClientRequest request = client.get(port, artifactUrl.getHost(), artifactUrl.getPath(), (Handler<HttpClientResponse>) response -> { response.exceptionHandler((Handler<Throwable>) error -> { handler.handle(AsyncResultImpl.create(error, File.class)); }); response.bodyHandler((Handler<Buffer>) buffer -> { try { if(response.statusCode() != 200 ){ handler.handle(AsyncResultImpl.create(null)); return; } Files.write(pluginFile.toPath(), buffer.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE, StandardOpenOption.WRITE); handler.handle(AsyncResultImpl.create(pluginFile)); } catch (IOException e) { handler.handle(AsyncResultImpl.create(e, File.class)); } }); }); request.exceptionHandler((Handler<Throwable>) error -> { handler.handle(AsyncResultImpl.create(error, File.class)); }); request.end(); }</code><technical_language>Style nit: spaces equals assignment</technical_language>

Target:
protected void downloadArtifactTo(final URL artifactUrl, final File pluginFile, final IAsyncResultHandler<File> handler) { HttpClient client; int port = artifactUrl.getPort(); if (artifactUrl.getProtocol().equals("https")) { if (port == -1) port = 443; } else { if (port == -1) port = 80; } client = vertx.createHttpClient(configureHttpClientOptions(artifactUrl)); System.out.println(Messages.format("VertxPluginRegistry.TryDownloadFromRepo", artifactUrl.getHost())); final HttpClientRequest request = client.get(port, artifactUrl.getHost(), artifactUrl.getPath(), (Handler<HttpClientResponse>) response -> { response.exceptionHandler((Handler<Throwable>) error -> { handler.handle(AsyncResultImpl.create(error, File.class)); }); response.bodyHandler((Handler<Buffer>) buffer -> { try { System.out.println(Messages.format("VertxPluginRegistry.ResponseStatusCode", response.request().absoluteURI(), response.statusCode())); if (response.statusCode() != 200) { handler.handle(AsyncResultImpl.create(null)); return; } Files.write(pluginFile.toPath(), buffer.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE, StandardOpenOption.WRITE); handler.handle(AsyncResultImpl.create(pluginFile)); } catch (IOException e) { handler.handle(AsyncResultImpl.create(e, File.class)); } }); }); request.exceptionHandler((Handler<Throwable>) error -> { handler.handle(AsyncResultImpl.create(error, File.class)); }); request.end(); }
Source:
<code>public CertificationBodyDTO update(final CertificationBodyDTO dto) throws EntityRetrievalException { CertificationBodyEntity entity = getEntityById(dto.getId()); if (entity == null) { throw new EntityRetrievalException( "Cannot update entity with id " + dto.getId() + ". Entity does not exist."); } if (dto.getAddress() != null) { try { <START> entity.setAddress(addressDao.create(dto.getAddress())); <END> } catch (final EntityCreationException ex) { LOGGER.error("Could not create new address in the database.", ex); entity.setAddress(null); } } else { entity.setAddress(null); } entity.setWebsite(dto.getWebsite()); entity.setRetired(dto.isRetired()); entity.setRetirementDate(dto.getRetirementDate()); if (dto.getName() != null) { entity.setName(dto.getName()); } if (dto.getAcbCode() != null) { entity.setAcbCode(dto.getAcbCode()); } entity.setLastModifiedUser(AuthUtil.getAuditId()); update(entity); return new CertificationBodyDTO(entity); }</code><technical_language>This update method is calling code create a new address. I feel call saveAddress method in developer dao</technical_language>

Target:
public CertificationBodyDTO update(final CertificationBodyDTO dto) throws EntityRetrievalException { CertificationBodyEntity entity = getEntityById(dto.getId()); if (entity == null) { throw new EntityRetrievalException( "Cannot update entity with id " + dto.getId() + ". Entity does not exist."); } if (dto.getAddress() != null) { try { entity.setAddress(addressDao.saveAddress(dto.getAddress())); } catch (final EntityCreationException ex) { LOGGER.error("Could not create new address in the database.", ex); entity.setAddress(null); } } else { entity.setAddress(null); } entity.setWebsite(dto.getWebsite()); entity.setRetired(dto.isRetired()); entity.setRetirementDate(dto.getRetirementDate()); if (dto.getName() != null) { entity.setName(dto.getName()); } if (dto.getAcbCode() != null) { entity.setAcbCode(dto.getAcbCode()); } entity.setLastModifiedUser(AuthUtil.getAuditId()); update(entity); return new CertificationBodyDTO(entity); }
Source:
<code>public void die() { this.loseLife(); this.scorePoints(Settings.POINTS_PLAYER_DIE); spriteBase.setImage("/Bub" + playerNumber + "Death.png"); spriteBase.setDx(0); spriteBase.setDy(0); if (this.getLives() == 0) { counter = 0; <START> <END> setChanged(); notifyObservers(); destroy(); } else { isDelayed = true; delayRespawn(); } }</code><technical_language>add here: spriteBase.setX(xStartLocation); spriteBase.setY(yStartLocation); set a died player starting position. this work nice adjust starting position of map2.txt, map3.txt place a died player a platform (map2) halfway in wall (map3) <feature</technical_language>

Target:
public void die() { this.loseLife(); this.scorePoints(Settings.POINTS_PLAYER_DIE); location[1] = 0; location[3] = 0; setLocation(location); if (this.getLives() == 0) { counter = 0; setLocation(location); spriteBase.setImage("/Bub" + playerNumber + "Death.png"); setChanged(); notifyObservers(); destroy(); } else { isDelayed = true; delayRespawn(); } }
Source:
<code>public boolean checkObject(Object aObject) { boolean result = false; if (this == aObject) { result = true; } else { <START> result = false; <END> } return result; }</code><technical_language>this assigment is needed, default is false</technical_language>

Target:
public boolean checkObject(Object aObject) { boolean result = false; if (this == aObject) { result = true; } return result; }
Source:
<code>public ResponseEntity addRolesToAnonymous(@RequestBody @Validated RoleListForm roleListForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { <START> if (roleListForm == null) <END> { throw new RequestBodyValidationException("Empty request body", bindingResult); } if (bindingResult.hasErrors()) { String message = "Roles cannot be saved because the submitted form contains errors!"; throw new RequestBodyValidationException(message, bindingResult); } TypeDescriptor sourceType = TypeDescriptor.valueOf(RoleListForm.class); TypeDescriptor targetType = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Role.class)); List<Role> roleList = (List<Role>) conversionService.convert(roleListForm, sourceType, targetType); return processConfig(config -> addRolesToAnonymous(config, Objects.requireNonNull(roleList)), () -> SUCCESSFUL_ASSIGN_ROLES, acceptHeader); }</code><technical_language>above, redundant null check</technical_language>

Target:
public ResponseEntity addRolesToAnonymous(@RequestBody @Validated RoleListForm roleListForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ASSIGN_ROLES, bindingResult); } TypeDescriptor sourceType = TypeDescriptor.valueOf(RoleListForm.class); TypeDescriptor targetType = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Role.class)); List<Role> roleList = (List<Role>) conversionService.convert(roleListForm, sourceType, targetType); return processConfig(config -> addRolesToAnonymous(config, Objects.requireNonNull(roleList)), () -> SUCCESSFUL_ASSIGN_ROLES, acceptHeader); }
Source:
<code>private static void setDeclaredReturnType(Symbol symbol, FunctionDef functionDef) { TypeAnnotation returnTypeAnnotation = functionDef.returnTypeAnnotation(); if (returnTypeAnnotation == null) { return; } if (symbol.is(Symbol.Kind.FUNCTION)) { FunctionSymbolImpl functionSymbol = (FunctionSymbolImpl) symbol; functionSymbol.setDeclaredReturnType(InferredTypes.declaredType(returnTypeAnnotation, builtins)); } else if (symbol.is(Symbol.Kind.AMBIGUOUS)) { AmbiguousSymbolImpl ambiguousSymbol = (AmbiguousSymbolImpl) symbol; <START> setDeclaredReturnType(ambiguousSymbol.getSymbol(functionDef.name()), functionDef); <END> } }</code><technical_language>I find a do differently, needing AmbiguousSymbolImpl store symbolsByDeclarationTree</technical_language>

Target:
private static void setDeclaredReturnType(Symbol symbol, FunctionDef functionDef) { TypeAnnotation returnTypeAnnotation = functionDef.returnTypeAnnotation(); if (returnTypeAnnotation == null) { return; } if (symbol.is(Symbol.Kind.FUNCTION)) { FunctionSymbolImpl functionSymbol = (FunctionSymbolImpl) symbol; functionSymbol.setDeclaredReturnType(InferredTypes.declaredType(returnTypeAnnotation, builtins)); } else if (symbol.is(Symbol.Kind.AMBIGUOUS)) { Optional.ofNullable(((FunctionDefImpl) functionDef).functionSymbol()).ifPresent(functionSymbol -> setDeclaredReturnType(functionSymbol, functionDef)); } }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) <END> return true; if (!(o instanceof StorageOffloadDisk)) return false; if (!super.equals(o)) return false; StorageOffloadDisk that = (StorageOffloadDisk) o; return Objects.equals(volumeMetadata, that.volumeMetadata); }</code><technical_language>please add {}. fails checkstyle validation</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof StorageOffloadDisk)) { return false; } if (!super.equals(o)) { return false; } StorageOffloadDisk that = (StorageOffloadDisk) o; return Objects.equals(volumeMetadata, that.volumeMetadata); }
Source:
<code>public void ehcache2Expiry() throws Exception { CacheManager cacheManager = initCacheManager(); CacheConfiguration cacheConfiguration = new CacheConfiguration().name("cache") .maxEntriesLocalHeap(100) .timeToLiveSeconds(20); cacheManager.addCache(new Cache(cacheConfiguration)); Element element = new Element(10L, "Hello"); <START> element.setTimeToLive(getTimeToLiveInSeconds((Long)element.getObjectKey(), (String)element.getObjectValue())); END> cacheManager.getCache("cache").put(element); System.out.println(cacheManager.getCache("cache").get(10L).getObjectValue()); Thread.sleep(2100); System.out.println(cacheManager.getCache("cache").get(10L)); }</code><technical_language>I example a bit more evolved, TTL if default set it</technical_language>

Target:
public void ehcache2Expiry() throws Exception { int defaultCacheTTLInSeconds = 20; CacheManager cacheManager = initCacheManager(); CacheConfiguration cacheConfiguration = new CacheConfiguration().name("cache") .maxEntriesLocalHeap(100) .timeToLiveSeconds(defaultCacheTTLInSeconds); cacheManager.addCache(new Cache(cacheConfiguration)); Element element = new Element(10L, "Hello"); int ttlInSeconds = getTimeToLiveInSeconds((Long)element.getObjectKey(), (String)element.getObjectValue()); if (ttlInSeconds != defaultCacheTTLInSeconds) { element.setTimeToLive(ttlInSeconds); } cacheManager.getCache("cache").put(element); System.out.println(cacheManager.getCache("cache").get(10L).getObjectValue()); sleep(2100); System.out.println(cacheManager.getCache("cache").get(10L)); }
Source:
<code>public UpdateFirmwareAsyncResponse updateFirmware( @OrganisationIdentification final String organisationIdentification, @RequestPayload final UpdateFirmwareRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime) throws OsgpException { LOGGER.info("UpdateFirmware Request received from organisation for device {}.", organisationIdentification, request.getDeviceIdentification()); <START> final UpdateFirmwareAsyncResponse response = new com.alliander.osgp.adapter.ws.schema.smartmetering.configuration.ObjectFactory() <END> .createUpdateFirmwareAsyncResponse(); try { final String correlationUid = this.configurationService.enqueueUpdateFirmwareRequest( organisationIdentification, request.getDeviceIdentification(), request.getFirmwareIdentification(), MessagePriorityEnum.getMessagePriority(messagePriority), this.configurationMapper.map(scheduleTime, Long.class)); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(request.getDeviceIdentification()); } catch (final Exception e) { this.handleException(e); } return response; }</code><technical_language>I in this endpoint class ObjectFactory is create instances of schema generated types. For this specific case of schema base objects I encountered behavior other new UpdateFirmwareAsyncResponse() factories. For readability consider dropping factory, create object new</technical_language>

Target:
public UpdateFirmwareAsyncResponse updateFirmware( @OrganisationIdentification final String organisationIdentification, @RequestPayload final UpdateFirmwareRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime) throws OsgpException { LOGGER.info("UpdateFirmware Request received from organisation for device {}.", organisationIdentification, request.getDeviceIdentification()); final UpdateFirmwareAsyncResponse response = new UpdateFirmwareAsyncResponse(); try { final String correlationUid = this.configurationService.enqueueUpdateFirmwareRequest( organisationIdentification, request.getDeviceIdentification(), request.getFirmwareIdentification(), MessagePriorityEnum.getMessagePriority(messagePriority), this.configurationMapper.map(scheduleTime, Long.class)); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(request.getDeviceIdentification()); } catch (final Exception e) { this.handleException(e); } return response; }
Source:
<code>private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { <START> logData = read(address, defaultReadOptions); <END> } catch (TrimmedException te) { throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } }</code><technical_language>read(long address) defaultReadOptions</technical_language>

Target:
private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { logData = read(address); } catch (TrimmedException te) { throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } }
Source:
<code>static void loadIntoCache(@NonNull PageTitle title) { L.d("Loading page into cache: " + title.getPrefixedText()); PageClient client = PageClientFactory.create(title.getWikiSite(), title.namespace()); Observable.zip(leadReq(client, title), remainingReq(client, title), (leadRsp, sectionsRsp) -> { PageTitle t = <START> WikipediaApp.getInstance().getTabList().get(WikipediaApp.getInstance().getTabCount() - 2).getBackStackPositionTitle(); <END> if (t != null) { t.setThumbUrl(leadRsp.body().getThumbUrl()); } return true; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(val -> { }, L::e); }</code><technical_language>time network call is complete, guarantee PageTitle want update "second-to-last" in tab list, other tabs opened closed in meantime, lead wrong PageTitle updated</technical_language>

Target:
static void loadIntoCache(@NonNull PageTitle title) { L.d("Loading page into cache: " + title.getPrefixedText()); PageClient client = PageClientFactory.create(title.getWikiSite(), title.namespace()); Observable.zip(leadReq(client, title), remainingReq(client, title), (leadRsp, sectionsRsp) -> leadRsp) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(leadRsp -> { for (int i = WikipediaApp.getInstance().getTabCount() - 1; i >= 0; i--) { PageTitle pageTitle = WikipediaApp.getInstance().getTabList().get(i).getBackStackPositionTitle(); if (pageTitle.equals(title)) { pageTitle.setThumbUrl(leadRsp.body().getThumbUrl()); break; } } }, L::e); }
Source:
<code>public static void start() { SipGateway sipGateway = null; for (AbstractGateway gw : JigasiBundleActivator.getAvailableGateways()) { if (gw instanceof SipGateway) sipGateway = (SipGateway) gw; } if (sipGateway != null) { if (sipGateway.isReady()) { sipChecker = SipHealthPeriodicChecker.create(sipGateway); if (sipChecker != null) { executor.registerRecurringRunnable(sipChecker); } } else { final SipGateway finalSipGw = sipGateway; sipGateway.addGatewayListener(new GatewayListener() { @Override <START> public void onSessionAdded(AbstractGatewaySession session) <END> @Override public void onSessionRemoved(AbstractGatewaySession session) @Override public void onSessionFailed(AbstractGatewaySession session) @Override public void onReady() { finalSipGw.removeGatewayListener(this); start(); } }); } } }</code><technical_language>add default implementations in GatwayListener interface</technical_language>

Target:
public static void start() { SipGateway sipGateway = null; for (AbstractGateway gw : JigasiBundleActivator.getAvailableGateways()) { if (gw instanceof SipGateway) sipGateway = (SipGateway) gw; } if (sipGateway != null) { if (sipGateway.isReady()) { sipChecker = SipHealthPeriodicChecker.create(sipGateway); if (sipChecker != null) { executor.registerRecurringRunnable(sipChecker); } } else { final SipGateway finalSipGw = sipGateway; sipGateway.addGatewayListener(new GatewayListener() { @Override public void onReady() { finalSipGw.removeGatewayListener(this); start(); } }); } } }
Source:
<code>public UserDetails call() throws Exception { try { Jenkins jenkins = Jenkins.getInstance(); UserDetails userDetails = jenkins.getSecurityRealm().loadUserByUsername(idOrFullName); if (userDetails == null) { <START> existanceCache.put(this.idOrFullName, false); <END> throw new NullPointerException("hudson.security.SecurityRealm should never return null. " + jenkins.getSecurityRealm() + " returned null for idOrFullName='" + idOrFullName + "'"); } existanceCache.put(this.idOrFullName, true); return userDetails; } catch (UsernameNotFoundException e) { existanceCache.put(this.idOrFullName, false); throw e; } catch (DataAccessException e) { existanceCache.put(this.idOrFullName, null); throw e; } }</code><technical_language>NIT: Boolean.FALSE</technical_language>

Target:
public UserDetails call() throws Exception { try { Jenkins jenkins = Jenkins.getInstance(); UserDetails userDetails = jenkins.getSecurityRealm().loadUserByUsername(idOrFullName); if (userDetails == null) { existanceCache.put(this.idOrFullName, Boolean.FALSE); throw new NullPointerException("hudson.security.SecurityRealm should never return null. " + jenkins.getSecurityRealm() + " returned null for idOrFullName='" + idOrFullName + "'"); } existanceCache.put(this.idOrFullName, Boolean.TRUE); return userDetails; } catch (UsernameNotFoundException e) { existanceCache.put(this.idOrFullName, Boolean.FALSE); throw e; } catch (DataAccessException e) { existanceCache.invalidate(this.idOrFullName); throw e; } }
Source:
<code>private void findXFriendReferences(ArrayList<TextFileChange> changes, IProgressMonitor monitor) throws CoreException { StateHelper helper = Platform.getPlatformAdmin().getStateHelper(); ExportPackageDescription[] pkgs = helper.getVisiblePackages(fDesc); String id = fDesc.getSymbolicName(); <START> SubMonitor subMonitor = SubMonitor.convert(monitor, "", pkgs.length); END> for (int i = 0; i < pkgs.length; i++) { String[] friends = (String[]) pkgs[i].getDirective(ICoreConstants.FRIENDS_DIRECTIVE); if (friends != null) for (int j = 0; j < friends.length; j++) { if (friends[j].equals(id)) { CreateHeaderChangeOperation op = new CreateHeaderChangeOperation(PluginRegistry.findModel(pkgs[i].getExporter()), Constants.EXPORT_PACKAGE, id, fNewId); op.run(subMonitor.newChild(1)); TextFileChange change = op.getChange(); if (change != null) changes.add(change); break; } } } }</code><technical_language>two-argument constructor</technical_language>

Target:
private void findXFriendReferences(ArrayList<TextFileChange> changes, IProgressMonitor monitor) throws CoreException { StateHelper helper = Platform.getPlatformAdmin().getStateHelper(); ExportPackageDescription[] pkgs = helper.getVisiblePackages(fDesc); String id = fDesc.getSymbolicName(); SubMonitor subMonitor = SubMonitor.convert(monitor, pkgs.length); for (int i = 0; i < pkgs.length; i++) { SubMonitor iterationMonitor = subMonitor.newChild(1); String[] friends = (String[]) pkgs[i].getDirective(ICoreConstants.FRIENDS_DIRECTIVE); if (friends != null) for (int j = 0; j < friends.length; j++) { if (friends[j].equals(id)) { CreateHeaderChangeOperation op = new CreateHeaderChangeOperation(PluginRegistry.findModel(pkgs[i].getExporter()), Constants.EXPORT_PACKAGE, id, fNewId); op.run(iterationMonitor); TextFileChange change = op.getChange(); if (change != null) changes.add(change); break; } } } }
Source:
<code>public void checkAttributeValue(PerunSessionImpl perunSession, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if(attribute.getValue() == null) { throw new WrongAttributeValueException(attribute, "Attribute value cannot be null."); } <START> List<String> vomRoles = (List<String>) attribute.getValue(); <END> try { for (String vomRole : vomRoles) { Matcher matcher = pattern.matcher(vomRole); if(!matcher.matches()) { throw new WrongAttributeValueException(attribute, "Bad group vomsRoles value. It should not contain '<>&' characters."); } } } catch (ClassCastException e) { throw new WrongAttributeValueException(attribute, "Value should be a list of Strings."); } }</code><technical_language>I guess this is a place, ClassCastException thrown, try block, resource version of attribute module</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if(attribute.getValue() == null) { return; } try { List<String> vomRoles = (List<String>) attribute.getValue(); for (String vomRole : vomRoles) { Matcher matcher = pattern.matcher(vomRole); if(!matcher.matches()) { throw new WrongAttributeValueException(attribute, "Bad group vomsRoles value. It should not contain '<>&' characters."); } } } catch (ClassCastException e) { throw new WrongAttributeValueException(attribute, "Value should be a list of Strings."); } }
Source:
<code>@Override public void onLoad(Bundle savedInstanceState) { if (whatToShow == null && savedInstanceState != null) { whatToShow = savedInstanceState.getParcelable(whatToShowKey); } if (whatToShow == null) return; Popup<D, R> view = getView(); if (view == null) return; <START> if (!view.isShowing()) { <END> view.show(whatToShow, !WITH_FLOURISH, this); Bundle popupState = savedInstanceState.getBundle(popupStateKey); if (popupState != null) { view.onRestoreInstanceState(popupState); } } }</code><technical_language>fact I lazy obligate cover entire class. covering new behavior fine</technical_language>

Target:
@Override public void onLoad(Bundle savedInstanceState) { if (whatToShow == null && savedInstanceState != null) { whatToShow = savedInstanceState.getParcelable(whatToShowKey); } if (whatToShow == null) return; Popup<D, R> view = getView(); if (view == null) return; if (!view.isShowing()) { view.show(whatToShow, !WITH_FLOURISH, this); } }
Source:
<code>LoggerNode(final LogContext context) { parent = null; fullName = ""; <START> this.context = context; <END> final LogContextInitializer initializer = context.getInitializer(); final Level initialLevel = initializer.getInitialLevel(fullName); if (initialLevel != null) { level = initialLevel; effectiveLevel = initialLevel.intValue(); } final Handler[] initialHandlers = safeCloneHandlers(initializer.getInitialHandlers(fullName)); if (initialHandlers != null) { handlers = initialHandlers; } children = context.createChildMap(); }</code><technical_language>This needs stay need initialize array empty array avoid NPE in LoggerNode.addHandler()</technical_language>

Target:
LoggerNode(final LogContext context) { parent = null; fullName = ""; this.context = context; final LogContextInitializer initializer = context.getInitializer(); final Level initialLevel = initializer.getInitialLevel(fullName); if (initialLevel != null) { level = initialLevel; effectiveLevel = initialLevel.intValue(); } handlers = safeCloneHandlers(initializer.getInitialHandlers(fullName)); children = context.createChildMap(); }
Source:
<code>protected void performMultiAction(AjaxRequestTarget target, List<ODocument> objects) { super.performMultiAction(target, objects); DBClosure.sudoConsumer(db -> { <START> db.commit(true); <END> db.begin(); db.getMetadata().reload(); }); }</code><technical_language>is here? need commit in initial db, in admin's one</technical_language>

Target:
protected void performMultiAction(AjaxRequestTarget target, List<ODocument> objects) { super.performMultiAction(target, objects); ODatabaseDocument db = getDatabase(); db.commit(true); db.begin(); DBClosure.sudoConsumer(sudoDb -> sudoDb.getMetadata().reload()); }
Source:
<code>private PlanWithProperties arbitraryDistributeUnion( UnionNode node, List<PlanNode> distributedChildren, List<List<VariableReferenceExpression>> distributedOutputLayouts) { <START> if (getNumberOfTableScans(distributedChildren) == 0 && isPartitioningCompatible(extractRemoteExchangePartitioningHandles(distributedChildren))) { <END> return new PlanWithProperties(node.replaceChildren(distributedChildren)); } else { return new PlanWithProperties( new ExchangeNode( idAllocator.getNextId(), REPARTITION, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), node.getOutputVariables()), distributedChildren, distributedOutputLayouts, Optional.empty())); } }</code><technical_language>is this fix related materialized exchanges issue before</technical_language>

Target:
private PlanWithProperties arbitraryDistributeUnion( UnionNode node, List<PlanNode> distributedChildren, List<List<VariableReferenceExpression>> distributedOutputLayouts) { if (getNumberOfTableScans(distributedChildren) == 0 && isSameOrSystemCompatiblePartitions(extractRemoteExchangePartitioningHandles(distributedChildren))) { return new PlanWithProperties(node.replaceChildren(distributedChildren)); } else { return new PlanWithProperties( new ExchangeNode( idAllocator.getNextId(), REPARTITION, REMOTE_STREAMING, new PartitioningScheme(Partitioning.create(FIXED_ARBITRARY_DISTRIBUTION, ImmutableList.of()), node.getOutputVariables()), distributedChildren, distributedOutputLayouts, Optional.empty())); } }
Source:
<code>public void addMacroExtensionAutoCompletions(MacroExtensionAutoCompletionService macroExtensionAutoCompletionService) { if (this.macroExtensionAutoCompletionService != null) { return; } sorted = false; this.macroExtensionAutoCompletionService = macroExtensionAutoCompletionService; List<BasicCompletion> completions = macroExtensionAutoCompletionService.getCompletions(this); <START> List<Completion> completionsCopy = new ArrayList<Completion>(); <END> for (BasicCompletion completion : completions) { completionsCopy.add(completion); } addCompletions(completionsCopy); }</code><technical_language>Remove redundant type arguments: suggestion List<Completion> completionsCopy = new ArrayList<>();</technical_language>

Target:
public void addMacroExtensionAutoCompletions(MacroExtensionAutoCompletionService macroExtensionAutoCompletionService) { if (this.macroExtensionAutoCompletionService != null) { return; } sorted = false; this.macroExtensionAutoCompletionService = macroExtensionAutoCompletionService; List<BasicCompletion> completions = macroExtensionAutoCompletionService.getCompletions(this); List<Completion> completionsCopy = new ArrayList<>(); for (BasicCompletion completion : completions) { completionsCopy.add(completion); } addCompletions(completionsCopy); }
Source:
<code>private boolean doSystemProtectionFilter( HttpServletResponse httpResponse, String targetContextPath, String requestMethod, String userAgentHeader) { String whitelistKey = getMultivaluedMapKey(SYSTEM_PROTECTION_WHITELIST, targetContextPath); String whitelistUserAgent = USER_AGENT_WHITELIST .stream() <START> .filter(regex -> Pattern.matches(regex, targetContextPath)) <END> .findFirst() .orElse(null); if (userAgentHeader != null && whitelistUserAgent != null && !(whitelistKey != null && SYSTEM_PROTECTION_WHITELIST.get(whitelistKey).contains(requestMethod))) { respondForbidden( httpResponse, "Cross-site check failure: Request did not have required X-Requested-With header."); return true; } return false; }</code><technical_language>this userAgentHeader instead of targetContextPath here</technical_language>

Target:
private boolean doSystemProtectionFilter( HttpServletResponse httpResponse, String targetContextPath, String requestMethod, String userAgentHeader) { Pattern whitelistUserAgent = null; if (userAgentHeader != null) { whitelistUserAgent = USER_AGENT_WHITELIST .stream() .filter(regex -> regex.matcher(userAgentHeader).matches()) .findFirst() .orElse(null); } boolean contextPathIsWhitelisted = false; Pattern whitelistKey = getMultivaluedMapKey(SYSTEM_PROTECTION_WHITELIST, targetContextPath); if (whitelistKey != null) { Pattern requestMethodPattern = Pattern.compile(requestMethod); if (SYSTEM_PROTECTION_WHITELIST .get(whitelistKey) .stream() .anyMatch(method -> requestMethodPattern.matcher(method).matches())) { contextPathIsWhitelisted = true; } } if (userAgentHeader != null && whitelistUserAgent == null && !contextPathIsWhitelisted) { respondForbidden(httpResponse, "Cross-site check failure: Request was made from a browser."); return true; } return false; }
Source:
<code>public List<AppAvailableForInstall> parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode(APPS_TAG); List<AppAvailableForInstall> appsList = new ArrayList<>(); parser.next(); int eventType = parser.getEventType(); do { if (eventType == KXmlParser.START_TAG) { String tagName = parser.getName().toLowerCase(); if (APP_TAG.equals(tagName)) { String domain = parser.getAttributeValue(null, DOMAIN_TAG); String appName = parser.getAttributeValue(null, APP_NAME_TAG); String appVersion = parser.getAttributeValue(null, APP_VERSION_TAG); <START> boolean isOnProd = PROD_VALUE.equals(parser.getAttributeValue(null, ENVIRONMENT_TAG)); <END> String profileRef = parser.getAttributeValue(null, PROFILE_REF_TAG); String mediaProfileRef = parser.getAttributeValue(null, MEDIA_PROFILE_REF_TAG); appsList.add(new AppAvailableForInstall(domain, appName, appVersion, isOnProd, profileRef, mediaProfileRef)); } } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return appsList; }</code><technical_language>confused of this boolean</technical_language>

Target:
public List<AppAvailableForInstall> parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode(APPS_TAG); List<AppAvailableForInstall> appsList = new ArrayList<>(); parser.next(); int eventType = parser.getEventType(); do { if (eventType == KXmlParser.START_TAG) { String tagName = parser.getName().toLowerCase(); if (APP_TAG.equals(tagName)) { String domain = parser.getAttributeValue(null, DOMAIN_TAG); String appName = parser.getAttributeValue(null, APP_NAME_TAG); String profileRef = parser.getAttributeValue(null, PROFILE_REF_TAG); String mediaProfileRef = parser.getAttributeValue(null, MEDIA_PROFILE_REF_TAG); appsList.add(new AppAvailableForInstall(domain, appName, profileRef, mediaProfileRef)); } } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return appsList; }
Source:
<code>private static String getFilledValue(Annotation mobileBy) { Method[] values = prepareAnnotationMethods(mobileBy.getClass()); for (Method value : values) { if (!String.class.equals(value.getReturnType())) { continue; } try { <START> String strategyParameter = value.invoke(mobileBy).toString(); <END> if (!"".equals(strategyParameter)) { return value.getName(); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } throw new IllegalArgumentException( "@" + mobileBy.getClass().getSimpleName() + ": one of " + Strategies.strategiesNames() .toString() + " should be filled"); }</code><technical_language>this call return result previous one</technical_language>

Target:
private static String getFilledValue(Annotation mobileBy) { Method[] values = prepareAnnotationMethods(mobileBy.getClass()); for (Method value : values) { if (!String.class.equals(value.getReturnType())) { continue; } try { String strategyParameter = value.invoke(mobileBy).toString(); if (!strategyParameter.isEmpty()) { return value.getName(); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } throw new IllegalArgumentException( "@" + mobileBy.getClass().getSimpleName() + ": one of " + Strategies.strategiesNames() .toString() + " should be filled"); }
Source:
<code>protected void requestCredentialsUpdate(Context context, Account account) { try { if (account == null) { account = getAccount(); } OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(account, context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken( account.type, cred.getAuthToken() ); } else { am.clearPassword(account); } } } Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account); updateAccountCredentials.putExtra( AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS); } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { <START> Snackbar snackbar = Snackbar.make( <END> findViewById(android.R.id.content), R.string.auth_account_does_not_exist, Snackbar.LENGTH_LONG ); snackbar.show(); } }</code><technical_language>before, create a new method show snackbar, passing error message parameter, rest of snackbar parameters everytime show snackbar</technical_language>

Target:
protected void requestCredentialsUpdate(Context context, Account account) { try { if (account == null) { account = getAccount(); } OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(account, context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken( account.type, cred.getAuthToken() ); } else { am.clearPassword(account); } } } Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account); updateAccountCredentials.putExtra( AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS); } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { showSnackMessage(getString(R.string.auth_account_does_not_exist)); } }
Source:
<code>public LinkedListImpl(Comparator<E> comparator, ToLongFunction<E> supplier) { iters = createIteratorArray(INITIAL_ITERATOR_ARRAY_SIZE); this.comparator = comparator; this.idSupplier = supplier; if (idSupplier != null) { <START> this.nodeMap = new LongObjectHashMap<>(this.size); <END> } else { this.nodeMap = null; } }</code><technical_language>this.size is 0</technical_language>

Target:
public LinkedListImpl(Comparator<E> comparator, ToLongFunction<E> supplier) { iters = createIteratorArray(INITIAL_ITERATOR_ARRAY_SIZE); this.comparator = comparator; this.idSupplier = supplier; if (idSupplier != null) { this.nodeMap = newLongHashMap(); } else { this.nodeMap = null; } }
Source:
<code>public void testCalculationOfBlockSizeWithMissingStats() { when(circuitBreaker.getLimit()).thenReturn(-1L); RamBlockSizeCalculator blockSizeCalculator = new RamBlockSizeCalculator( defaultBlockSize, circuitBreaker, 10, 10 ); <START> assertThat(blockSizeCalculator.getAsInt(), is(500)); <END> when(circuitBreaker.getLimit()).thenReturn(110L); when(circuitBreaker.getUsed()).thenReturn(10L); RamBlockSizeCalculator blockCalculatorNoNumberOrRowsStats = new RamBlockSizeCalculator( defaultBlockSize, circuitBreaker, 10, -1 ); assertThat(blockCalculatorNoNumberOrRowsStats.getAsInt(), is(500)); RamBlockSizeCalculator blockCalculatorNoRowSizeStats = new RamBlockSizeCalculator( defaultBlockSize, circuitBreaker, -1, 10 ); assertThat(blockCalculatorNoRowSizeStats.getAsInt(), is(500)); }</code><technical_language>FALLBACK_SIZE? (this suggestion, I forgot send ;-)</technical_language>

Target:
public void testCalculationOfBlockSizeWithMissingStats() { when(circuitBreaker.getLimit()).thenReturn(-1L); RamBlockSizeCalculator blockSizeCalculator = new RamBlockSizeCalculator( defaultBlockSize, circuitBreaker, 10, 10 ); assertThat(blockSizeCalculator.getAsInt(), is(RamBlockSizeCalculator.FALLBACK_SIZE)); when(circuitBreaker.getLimit()).thenReturn(110L); when(circuitBreaker.getUsed()).thenReturn(10L); RamBlockSizeCalculator blockCalculatorNoNumberOrRowsStats = new RamBlockSizeCalculator( defaultBlockSize, circuitBreaker, 10, -1 ); assertThat(blockCalculatorNoNumberOrRowsStats.getAsInt(), is(RamBlockSizeCalculator.FALLBACK_SIZE)); RamBlockSizeCalculator blockCalculatorNoRowSizeStats = new RamBlockSizeCalculator( defaultBlockSize, circuitBreaker, -1, 10 ); assertThat(blockCalculatorNoRowSizeStats.getAsInt(), is(RamBlockSizeCalculator.FALLBACK_SIZE)); }