auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void doSignUp() { String emailAddress = mEmailEditText.getText().toString(); String password = mPasswordEditText.getText().toString(); String confirmPassword = mPasswordConfirmEditText.getText().toString(); String firstName = mFirstNameEditText.getText().toString(); String lastName = mLastNameEditText.getText().toString(); if (isValidEmail(emailAddress) && confirmPasswords(password, confirmPassword)) { mErrorTextView.setVisibility(View.INVISIBLE); mErrorString = ""; mErrorTextView.setText(mErrorString); User user = new User(); user.setEmail(emailAddress); user.setPassword(password); user.setFirstName(firstName); user.setLastName(lastName); user.needsOnBoarding(); new SignUpTask(this).executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, user); } else { mErrorTextView.setText(mErrorString); mErrorTextView.setVisibility(View.VISIBLE); } }

Target:
private void doSignUp() { String emailAddress = mEmailEditText.getText().toString(); String password = mPasswordEditText.getText().toString(); String confirmPassword = mPasswordConfirmEditText.getText().toString(); String firstName = mFirstNameEditText.getText().toString(); String lastName = mLastNameEditText.getText().toString(); if (isValidEmail(emailAddress) && confirmPasswords(password, confirmPassword)) { mErrorTextView.setVisibility(View.INVISIBLE); mErrorString = ""; mErrorTextView.setText(mErrorString); User user = new User(); user.setEmail(emailAddress); user.setPassword(password); user.setFirstName(firstName); user.setLastName(lastName); user.onBoardingComplete(false); new SignUpTask(this).executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, user); } else { mErrorTextView.setText(mErrorString); mErrorTextView.setVisibility(View.VISIBLE); } }
Source:
public Object combine(Object lhs, Object rhs) { return (((SerializablePair<Long, Double>) lhs).lhs <= ((SerializablePair<Long, Double>) rhs).lhs) ? lhs : rhs; }

Target:
public Object combine(Object lhs, Object rhs) { return TIME_COMPARATOR.compare(lhs, rhs) <= 0 ? lhs : rhs; }
Source:
public FieldBuilderOptions setConverter(MemberNameConverter converter) { this.converter = Objects.requireNonNull(converter, "The serializer cannot be null"); return this; }

Target:
public FieldBuilderOptions setConverter(MemberNameConverter converter) { this.converter = Objects.requireNonNull(converter, "The converter cannot be null"); return this; }
Source:
public double deltaStickyStrike(IborFutureOption futureOption, RatesProvider prov, NormalVolatilityIborFutureParameters parameters, double futurePrice) { ArgChecker.isTrue(futureOption.getPremiumStyle().equals(FutureOptionPremiumStyle.DAILY_MARGIN), "premium style should be DAILY_MARGIN"); EuropeanVanillaOption option = createOption(futureOption, parameters); NormalFunctionData normalPoint = createData(createKey(futureOption, futurePrice, parameters), parameters); double[] priceAdjoint = new double[3]; NORMAL_FUNCTION.getPriceAdjoint(option, normalPoint, priceAdjoint); return priceAdjoint[0]; }

Target:
public double deltaStickyStrike(IborFutureOption futureOption, RatesProvider prov, NormalVolatilityIborFutureParameters parameters, double futurePrice) { ArgChecker.isTrue(futureOption.getPremiumStyle().equals(FutureOptionPremiumStyle.DAILY_MARGIN), "premium style should be DAILY_MARGIN"); EuropeanVanillaOption option = createOption(futureOption, parameters); NormalFunctionData normalPoint = createData(createKey(futureOption, futurePrice, parameters), parameters); return NORMAL_FUNCTION.getDelta(option, normalPoint); }
Source:
protected boolean checkPermissions(final List<PermissionSubject> permSubjects) { for (PermissionSubject permSubject : permSubjects) { if (!checkSinglePermission(permSubject, getReturnValue().getCanDoActionMessages())) { log.infoFormat("No permission found for user {0} or one of the groups he is member of, when running action {1}," + " on object {2} for {3} with id {4}.", getCurrentUser().getId(), getActionType(), permSubject.getObjectType().getVdcObjectTranslation(), permSubject.getActionGroup(), permSubject.getObjectId()); return false; } } return true; }

Target:
protected boolean checkPermissions(final List<PermissionSubject> permSubjects) { for (PermissionSubject permSubject : permSubjects) { if (!checkSinglePermission(permSubject, getReturnValue().getCanDoActionMessages())) { log.infoFormat("No permission found for user {0} or one of the groups he is member of," + " when running action {1}, Required permissions are: Action type: {2} Action group: {3}" + " Object type: {4} Object ID: {5}.", getCurrentUser().getId(), getActionType(), permSubject.getActionGroup().getRoleType().name(), permSubject.getActionGroup().name(), permSubject.getObjectType().getVdcObjectTranslation(), permSubject.getObjectId()); return false; } } return true; }
Source:
private void assertBlockSize(Block block) { long expectedBlockSize = copyBlockViaBlockSerde(block).getSizeInBytes(); assertEquals(block.getSizeInBytes(), expectedBlockSize); assertEquals(block.getRegionSizeInBytes(0, block.getPositionCount()), expectedBlockSize); List<Block> splitBlock = splitBlock(block, 2); Block firstHalf = splitBlock.get(0); long expectedFirstHalfSize = copyBlockViaBlockSerde(firstHalf).getSizeInBytes(); assertEquals(firstHalf.getSizeInBytes(), expectedFirstHalfSize); assertEquals(block.getRegionSizeInBytes(0, firstHalf.getPositionCount()), expectedFirstHalfSize); Block secondHalf = splitBlock.get(1); long expectedSecondHalfSize = copyBlockViaBlockSerde(secondHalf).getSizeInBytes(); assertEquals(secondHalf.getSizeInBytes(), expectedSecondHalfSize); assertEquals(block.getRegionSizeInBytes(firstHalf.getPositionCount(), secondHalf.getPositionCount()), expectedSecondHalfSize); boolean[] positions = new boolean[block.getPositionCount()]; for (int i = 0; i < firstHalf.getPositionCount(); ++i) { positions[i] = true; } assertEquals(firstHalf.getSizeInBytes(), block.getPositionsSizeInBytes(positions)); fill(positions, true); assertEquals(block.getSizeInBytes(), block.getPositionsSizeInBytes(positions)); for (int i = 0; i < firstHalf.getPositionCount(); ++i) { positions[i] = false; } assertEquals(secondHalf.getSizeInBytes(), block.getPositionsSizeInBytes(positions)); }

Target:
private void assertBlockSize(Block block) { long expectedBlockSize = copyBlockViaBlockSerde(block).getSizeInBytes(); assertEquals(block.getSizeInBytes(), expectedBlockSize); assertEquals(block.getRegionSizeInBytes(0, block.getPositionCount()), expectedBlockSize); List<Block> splitBlock = splitBlock(block, 2); Block firstHalf = splitBlock.get(0); long expectedFirstHalfSize = copyBlockViaBlockSerde(firstHalf).getSizeInBytes(); assertEquals(firstHalf.getSizeInBytes(), expectedFirstHalfSize); assertEquals(block.getRegionSizeInBytes(0, firstHalf.getPositionCount()), expectedFirstHalfSize); Block secondHalf = splitBlock.get(1); long expectedSecondHalfSize = copyBlockViaBlockSerde(secondHalf).getSizeInBytes(); assertEquals(secondHalf.getSizeInBytes(), expectedSecondHalfSize); assertEquals(block.getRegionSizeInBytes(firstHalf.getPositionCount(), secondHalf.getPositionCount()), expectedSecondHalfSize); boolean[] positions = new boolean[block.getPositionCount()]; fill(positions, 0, firstHalf.getPositionCount(), true); assertEquals(block.getPositionsSizeInBytes(positions), expectedFirstHalfSize); fill(positions, true); assertEquals(block.getPositionsSizeInBytes(positions), expectedBlockSize); fill(positions, 0, firstHalf.getPositionCount(), false); assertEquals(block.getPositionsSizeInBytes(positions), expectedSecondHalfSize); }
Source:
private int chooseFromCandidates() { for (int port : candidatePorts) { if (!usedPorts.contains(port) && canBind(port)) { return port; } } throw new ISE("All ports are Used.."); }

Target:
private int chooseFromCandidates() { for (int port : candidatePorts) { if (!usedPorts.contains(port) && canBind(port)) { return port; } } throw new ISE("All ports are used..."); }
Source:
private static EcsClientConfig buildEcsClientConfig(String clusterName, Config ecsConfig) { return EcsClientConfig.builder() .withClusterName(clusterName) .withLaunchType(ecsConfig.getOptional("launch_type", String.class)) .withAccessKeyId(ecsConfig.get("access_key_id", String.class)) .withSecretAccessKey(ecsConfig.get("secret_access_key", String.class)) .withRegion(ecsConfig.get("region", String.class)) .withSubnets(ecsConfig.getOptional("subnets", String.class)) .withMaxRetries(ecsConfig.get("max_retries", int.class, DEFAULT_MAX_RETRIES)) .withCapacityProviderName(ecsConfig.getOptional("capacity_provider_name", String.class)) .withContainerCpu(ecsConfig.getOptional("container_cpu", Integer.class)) .withContainerMemory(ecsConfig.getOptional("memory", Integer.class)) .withStartedBy(ecsConfig.getOptional("startedBy", String.class)) .withAssignPublicIp(ecsConfig.get("assign_public_ip", boolean.class, true)) .withPlacementStrategyType(ecsConfig.getOptional("placement_strategy_type", String.class)) .withPlacementStrategyField(ecsConfig.getOptional("placement_strategy_field", String.class)) .withTaskCpu(ecsConfig.getOptional("task_cpu", String.class)) .withTaskMemory(ecsConfig.getOptional("task_memory", String.class)) .build(); }

Target:
private static EcsClientConfig buildEcsClientConfig(String clusterName, Config ecsConfig) { return EcsClientConfig.builder() .withClusterName(clusterName) .withLaunchType(ecsConfig.getOptional("launch_type", String.class)) .withAccessKeyId(ecsConfig.get("access_key_id", String.class)) .withSecretAccessKey(ecsConfig.get("secret_access_key", String.class)) .withRegion(ecsConfig.get("region", String.class)) .withSubnets(ecsConfig.getOptional("subnets", String.class)) .withMaxRetries(ecsConfig.get("max_retries", int.class, DEFAULT_MAX_RETRIES)) .withCapacityProviderName(ecsConfig.getOptional("capacity_provider_name", String.class)) .withContainerCpu(ecsConfig.getOptional("container_cpu", Integer.class)) .withContainerMemory(ecsConfig.getOptional("container_memory", Integer.class)) .withStartedBy(ecsConfig.getOptional("startedBy", String.class)) .withAssignPublicIp(ecsConfig.get("assign_public_ip", boolean.class, true)) .withPlacementStrategyType(ecsConfig.getOptional("placement_strategy_type", String.class)) .withPlacementStrategyField(ecsConfig.getOptional("placement_strategy_field", String.class)) .withTaskCpu(ecsConfig.getOptional("task_cpu", String.class)) .withTaskMemory(ecsConfig.getOptional("task_memory", String.class)) .build(); }
Source:
public void onUpgrade(@NonNull final SQLiteDatabase db, final int oldVersion, final int newVersion) { if (oldVersion < 7) { resetDatabase(db); return; } int upgradeTo = oldVersion + 1; while (upgradeTo <= newVersion) { switch (upgradeTo) { case 8: db.execSQL(Contract.Church.SQL_V8_CREATE_TABLE); break; case 9: db.execSQL(Contract.Church.SQL_V9_ALTER_DIRTY); db.execSQL(Contract.MeasurementDetails.SQL_V9_ALTER_LOCAL); db.execSQL(Contract.MeasurementDetails.SQL_V9_ALTER_PERSONAL); break; default: resetDatabase(db); return; } upgradeTo++; } }

Target:
public void onUpgrade(@NonNull final SQLiteDatabase db, final int oldVersion, final int newVersion) { if (oldVersion < 7) { resetDatabase(db); return; } int upgradeTo = oldVersion + 1; while (upgradeTo <= newVersion) { switch (upgradeTo) { case 8: db.execSQL(Contract.Church.SQL_V8_CREATE_TABLE); break; case 9: db.execSQL(Contract.Church.SQL_V9_ALTER_DIRTY); break; case 10: db.execSQL(Contract.MeasurementDetails.SQL_V10_ALTER_LOCAL); db.execSQL(Contract.MeasurementDetails.SQL_V10_ALTER_PERSONAL); break; default: resetDatabase(db); return; } upgradeTo++; } }
Source:
public void testPost() throws Exception { String expectedResponse = "Customer added : Customer{name='TestCreate', surname='TestCreate', id=3}"; int customerId = 3; Customer customer = new Customer("TestCreate", "TestCreate", customerId); Response response = createCustomer(customer); System.out.println(response.readEntity(String.class)); File file = new File("target/test/consumerTest/create.txt"); byte[] encoded = Files.readAllBytes(file.toPath()); String responseBody = new String(encoded); Assert.assertEquals(expectedResponse, responseBody); Assert.assertEquals(customer, getCustomer(customerId)); deleteCustomer(customerId); }

Target:
public void testPost() throws Exception { String expectedResponse = "Customer added : Customer{name='TestCreate', surname='TestCreate', id=3}"; int customerId = 3; Customer customer = new Customer("TestCreate", "TestCreate", customerId); Response response = createCustomer(customer); File file = new File("target/test/consumerTest/create.txt"); byte[] encoded = Files.readAllBytes(file.toPath()); String responseBody = new String(encoded); Assert.assertEquals(expectedResponse, responseBody); Assert.assertEquals(customer, getCustomer(customerId)); deleteCustomer(customerId); }
Source:
protected void executeQueryCommand() { VDSBrokerFrontend vdsBroker = getBackend().getResourceManager(); VDSReturnValue imagesListResult = vdsBroker.RunVdsCommand(VDSCommandType.GetImagesList, new GetImagesListVDSCommandParameters(getParameters().getDomainId(), DbFacade.getInstance() .getStoragePoolDAO() .getAllForStorageDomain( getParameters().getDomainId()).get(0).getId())); List<Guid> imagesList = (List<Guid>) imagesListResult.getReturnValue(); List<DiskImage> fromDao = getDbFacade().getDiskImageDao().getAllSnapshotsForStorageDomain(getParameters().getDomainId()); for (DiskImage image : fromDao) { if (imagesList.contains(image.getId())) { imagesList.remove(image.getId()); } } if (imagesList.isEmpty()) { logger.info("List is empty."); } else { logger.info("UUIDs found: " + StringUtils.join(imagesList, ",")); } getQueryReturnValue().setReturnValue(imagesList); }

Target:
protected void executeQueryCommand() { VDSBrokerFrontend vdsBroker = getBackend().getResourceManager(); VDSReturnValue imagesListResult = vdsBroker.RunVdsCommand(VDSCommandType.GetImagesList, new GetImagesListVDSCommandParameters(getParameters().getStorageDomainId(), DbFacade.getInstance() .getStoragePoolDao() .getAllForStorageDomain( getParameters().getStorageDomainId()).get(0).getId())); List<Guid> imagesList = (List<Guid>) imagesListResult.getReturnValue(); List<DiskImage> fromDao = getDbFacade().getDiskImageDao().getAllSnapshotsForStorageDomain(getParameters().getStorageDomainId()); for (DiskImage image : fromDao) { imagesList.remove(image.getId()); } if (imagesList.isEmpty()) { logger.info("List is empty."); } else { logger.info("UUIDs found: " + StringUtils.join(imagesList, ",")); } getQueryReturnValue().setReturnValue(imagesList); }
Source:
public void createsHostsConfiguration() throws IOException { final File path = this.temp.newFolder(); final SSHD sshd = new SSHD(path); final int port = sshd.start(); final File key = this.temp.newFile(); FileUtils.write(key, sshd.key()); final String file = Joiner.on('\n').join( "Thindeck-LoadBalancer-Host: localhost", String.format("Thindeck-LoadBalancer-Port: %d", port), String.format("Thindeck-LoadBalancer-User: %s", sshd.login()), String.format( "Thindeck-LoadBalancer-Key-File: %s", key.toString() ), String.format( "Thindeck-LoadBalancer-Directory: %s", path.toString() ), StringUtils.EMPTY ); Manifests.append( new ByteArrayInputStream(file.getBytes()) ); final String host = "host"; final int hport = 1234; final String server = "server"; final int sport = 567; final String shosts = String.format("%s.hosts.conf", host); final File fhosts = new File(path, shosts); FileUtils.writeStringToFile( fhosts, Joiner.on('\n').join( "upstream example_servers {", " server 10.0.0.1:80;", " server 10.0.0.2:80;", "}" ) ); new Nginx().update(host, hport, server, sport); MatcherAssert.assertThat( FileUtils.readFileToString(fhosts), Matchers.equalTo( Joiner.on('\n').join( "upstream example_servers {", " server 10.0.0.1:80;", " server 10.0.0.2:80;", String.format(" server %s:%d;", server, sport), "}" ) ) ); }

Target:
public void createsHostsConfiguration() throws IOException { final File path = this.temp.newFolder(); final SSHD sshd = new SSHD(path); final int port = sshd.start(); final File key = this.temp.newFile(); FileUtils.write(key, sshd.key()); this.manifest(path, sshd.login(), port, key); final String host = "host"; final int sport = 567; final String server = "server"; final File fhosts = this.hosts(path, host); new Nginx().update(host, 1234, server, sport); MatcherAssert.assertThat( FileUtils.readFileToString(fhosts), Matchers.equalTo( Joiner.on('\n').join( "upstream example_servers {", " server 10.0.0.1:80;", " server 10.0.0.2:80;", String.format(" server %s:%d;", server, sport), "}" ) ) ); }
Source:
public void init() { meter = metricRegistry.meter("persistence"); nodeInfoCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterAccess(300, TimeUnit.SECONDS) .build(new CacheLoader<NodeInfoKey, Optional<NodeInfo>>() { @Override public Optional<NodeInfo> load(NodeInfoKey key) throws Exception { return getNodeInfo(key.location, key.ipAddress); } }); }

Target:
public void init() { meter = metricRegistry.meter("persistence"); nodeInfoCache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(300, TimeUnit.SECONDS) .build(new CacheLoader<NodeInfoKey, Optional<NodeInfo>>() { @Override public Optional<NodeInfo> load(NodeInfoKey key) throws Exception { return getNodeInfo(key.location, key.ipAddress); } }); }
Source:
public void clearAllRevisions(String siddhiAppName) { File targetDirectory = new File(folder + File.separator + siddhiAppName); File[] files = targetDirectory.listFiles(); if (files == null || files.length == 0) { log.info("No revisions were found with the Siddhi App " + siddhiAppName); return; } for (File file : files) { if (file.exists()) { if (!file.delete()) { log.error("file is not deleted successfully!"); throw new CannotClearSiddhiAppStateException("Persistence state " + "file is not deleted : " + file.getPath()); } } } }

Target:
public void clearAllRevisions(String siddhiAppName) { File targetDirectory = new File(folder + File.separator + siddhiAppName); File[] files = targetDirectory.listFiles(); if (files == null || files.length == 0) { log.info("No revisions were found to delete for the Siddhi App " + siddhiAppName); return; } for (File file : files) { if (file.exists()) { if (!file.delete()) { log.error("file is not deleted successfully : " + file.getName()); throw new CannotClearSiddhiAppStateException("Persistence state " + "file is not deleted : " + file.getName()); } } } }
Source:
public void should_fail_if_try_to_build_settlement_on_existing_settlement() { String userToken1 = loginUser(USER_NAME_1, USER_PASSWORD_1); String userToken2 = loginUser(USER_NAME_2, USER_PASSWORD_2); String userToken3 = loginUser(USER_NAME_3, USER_PASSWORD_3); int gameId = createNewGame(userToken1, false).path("gameId"); int node_id = viewGame(userToken1, gameId).path("map.nodes[0].nodeId"); joinPublicGame(userToken2, gameId); joinPublicGame(userToken3, gameId); setUserReady(userToken1, gameId); setUserReady(userToken2, gameId); setUserReady(userToken3, gameId); viewGame(userToken1, gameId) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(node_id)) .body("map.nodes[0].building", nullValue()) .body("status", equalTo("PLAYING")); buildSettlement(userToken1, gameId, node_id) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(node_id)) .body("map.nodes[0].building.ownerGameUserId", is(1)) .body("map.nodes[0].building.built", equalTo("SETTLEMENT")) .body("status", equalTo("PLAYING")); buildSettlement(userToken2, gameId, node_id) .then() .statusCode(400) .body("errorCode", equalTo("ERROR")); }

Target:
public void should_fail_if_try_to_build_settlement_on_existing_settlement() { String userToken1 = loginUser(USER_NAME_1, USER_PASSWORD_1); String userToken2 = loginUser(USER_NAME_2, USER_PASSWORD_2); String userToken3 = loginUser(USER_NAME_3, USER_PASSWORD_3); int gameId = createNewGame(userToken1, false).path("gameId"); int nodeIdToBuild = viewGame(userToken1, gameId).path("map.nodes[0].nodeId"); int gameUserId1 = viewGame(userToken1, gameId).path("gameUsers[0].id"); joinPublicGame(userToken2, gameId); joinPublicGame(userToken3, gameId); setUserReady(userToken1, gameId); setUserReady(userToken2, gameId); setUserReady(userToken3, gameId); viewGame(userToken1, gameId) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(nodeIdToBuild)) .body("map.nodes[0].building", nullValue()) .body("status", equalTo("PLAYING")); buildSettlement(userToken1, gameId, nodeIdToBuild) .then() .statusCode(200); viewGame(userToken1, gameId) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(nodeIdToBuild)) .body("map.nodes[0].building.ownerGameUserId", is(gameUserId1)) .body("map.nodes[0].building.built", equalTo("SETTLEMENT")) .body("status", equalTo("PLAYING")); buildSettlement(userToken2, gameId, nodeIdToBuild) .then() .statusCode(400) .body("errorCode", equalTo("ERROR")); }
Source:
public static byte[] writeBigDecimal(final BigDecimal num) { if (num == null) { return new byte[0]; } BigInteger sig = new BigInteger(num.unscaledValue().toString()); byte[] sigBytes = sig.toByteArray(); int scale = num.scale(); ByteBuffer bb = ByteBuffer.allocate(sigBytes.length + 8); return bb.putInt(scale).putInt(sigBytes.length).put(sigBytes).array(); }

Target:
public static byte[] writeBigDecimal(final BigDecimal num) { if (num == null) { return new byte[0]; } final byte[] unscaled = num.unscaledValue().toByteArray(); final ByteBuffer buf = ByteBuffer.allocate(VarintUtils.signedIntByteLength(num.scale()) + 4 + unscaled.length); VarintUtils.writeSignedInt(num.scale(), buf); buf.putInt(unscaled.length); buf.put(unscaled); return buf.array(); }
Source:
public LoginPage() { driver = SeleniumDriverManager.getManager().getDriver(); driver.get(baseUrl); PageFactory.initElements(driver, this); }

Target:
public LoginPage() { driver = SeleniumDriverManager.getManager().getDriver(); driver.get(URL_ADMIN); PageFactory.initElements(driver, this); }
Source:
public void sendOneWay(MessageOut message, int id, InetAddressAndPort to) { if (logger.isTraceEnabled()) logger.trace("{} sending to {}@{}", FBUtilities.getBroadcastAddressAndPort(), message.verb, id, to); if (to.equals(FBUtilities.getBroadcastAddressAndPort())) logger.warn("Message-to-self going over MessagingService", message); for (IMessageSink ms : messageSinks) if (!ms.allowOutgoingMessage(message, id, to)) return; OutboundMessagingPool outboundMessagingPool = getMessagingConnection(to); if (outboundMessagingPool != null) outboundMessagingPool.sendMessage(message, id); }

Target:
public void sendOneWay(MessageOut message, int id, InetAddressAndPort to) { if (logger.isTraceEnabled()) logger.trace("{} sending to {}@{}", FBUtilities.getBroadcastAddressAndPort(), message.verb, id, to); if (to.equals(FBUtilities.getBroadcastAddressAndPort())) logger.trace("Message-to-self going over MessagingService", message); for (IMessageSink ms : messageSinks) if (!ms.allowOutgoingMessage(message, id, to)) return; OutboundMessagingPool outboundMessagingPool = getMessagingConnection(to); if (outboundMessagingPool != null) outboundMessagingPool.sendMessage(message, id); }
Source:
private void configureRequestInterception() { final Network network = _dts.getNetwork(); network.setRequestInterception(ImmutableList.of(new RequestPattern())); network.onRequestIntercepted(event -> { final URI uri = URI.create(event.getRequest().getUrl()); final String origin = uri.getScheme() + "://" + uri.getAuthority(); final OriginConfig originConfig = _originConfigs.get(origin); if (originConfig == null || !originConfig.isRequestAllowed(uri.getPath())) { System.out.println("Cancelling request to " + uri); network.continueInterceptedRequest( event.getInterceptionId(), ErrorReason.ABORTED, null, null, null, null, null, null ); return; } final ImmutableMap<String, Object> headers = ImmutableMap.<String, Object>builder() .putAll(event.getRequest().getHeaders()) .putAll(originConfig.getAdditionalHeaders()) .build(); network.continueInterceptedRequest( event.getInterceptionId(), null, null, event.getRequest().getUrl(), event.getRequest().getMethod(), event.getRequest().getPostData(), headers, null ); }); }

Target:
private void configureRequestInterception() { final Network network = _dts.getNetwork(); network.setRequestInterception(ImmutableList.of(new RequestPattern())); network.onRequestIntercepted(event -> { final String url = event.getRequest().getUrl(); if (!_originConfigs.isRequestAllowed(url)) { System.out.println("Cancelling request to " + url); network.continueInterceptedRequest( event.getInterceptionId(), ErrorReason.ABORTED, null, null, null, null, null, null ); return; } final ImmutableMap<String, Object> headers = ImmutableMap.<String, Object>builder() .putAll(event.getRequest().getHeaders()) .putAll(_originConfigs.getAdditionalHeaders(url)) .build(); network.continueInterceptedRequest( event.getInterceptionId(), null, null, url, event.getRequest().getMethod(), event.getRequest().getPostData(), headers, null ); }); }
Source:
void setTaskCompletionStatus(boolean status) { taskCompletionStatus = status; }

Target:
protected void setTaskCompletionStatus(boolean status) { taskCompletionStatus = status; }
Source:
private List<ProjectId> fillStorage(int count) { List<ProjectId> ids = newLinkedList(); for (int i = 0; i < count; i++) { ProjectId id = newId(); Project state = givenProject(id, format("project-%d", i)); Any packedState = AnyPacker.pack(state); EntityRecord rawRecord = EntityRecord .newBuilder() .setState(packedState) .setVersion(GivenVersion.withNumber(1)) .build(); EntityRecordWithColumns record = withLifecycleColumns(rawRecord); storage.write(id, record); ids.add(id); } return ids; }

Target:
private List<ProjectId> fillStorage(int count) { List<ProjectId> ids = newArrayListWithCapacity(count); for (int i = 0; i < count; i++) { ProjectId id = newId(); Project state = givenProject(id, format("project-%d", i)); Any packedState = AnyPacker.pack(state); EntityRecord rawRecord = EntityRecord .newBuilder() .setState(packedState) .setVersion(GivenVersion.withNumber(1)) .build(); EntityRecordWithColumns record = withLifecycleColumns(rawRecord); storage.write(id, record); ids.add(id); } return ids; }
Source:
public void MercurySmartBannerTest_001_ButtonName_FixPosition_Close() { SmartBannerComponentObject banner = new SmartBannerComponentObject(driver); wikiURL = urlBuilder.getUrlForWiki(WIKIS[0][0]); banner.openArticleOnWikiByNameWithCbAndNoAds(wikiURL, WIKIS[0][1]); MobileEmulationTouchActions touchActions = new MobileEmulationTouchActions(driver); Assertion.assertTrue( banner.isSmartBannerVisible(), "Smart banner is closed" ); Assertion.assertEquals(banner.isButtonVisible() == true, true, "Button is not visible"); int lastSmartBannerPosition = banner.getSmartBannerPosition(); touchActions.scrollBy(0, 100); boolean result = lastSmartBannerPosition == banner.getSmartBannerPosition(); PageObjectLogging.log( "Position", "is fixed", "is floated", result ); banner.scrollToTopAndWaitForShareBarToBeHidden(); banner.clickCloseButton(); result = !banner.isSmartBannerVisible(); PageObjectLogging.log( "Smart banner", "is closed", "is visible", result ); }

Target:
public void MercurySmartBannerTest_001_ButtonName_FixPosition_Close() { SmartBannerComponentObject banner = new SmartBannerComponentObject(driver); wikiURL = urlBuilder.getUrlForWiki(WIKIS[0][0]); banner.openArticleOnWikiByNameWithCbAndNoAds(wikiURL, WIKIS[0][1]); JavascriptActions jsActions = new JavascriptActions(driver); Assertion.assertTrue( banner.isSmartBannerVisible(), "Smart banner is closed" ); Assertion.assertTrue(banner.isButtonVisible(), "Button is not visible"); int lastSmartBannerPosition = banner.getSmartBannerPosition(); jsActions.scrollBy(0, 100); boolean result = lastSmartBannerPosition == banner.getSmartBannerPosition(); PageObjectLogging.log( "Position", "is fixed", "is floated", result ); banner.scrollToTopAndWaitForShareBarToBeHidden(); banner.clickCloseButton(); result = !banner.isSmartBannerVisible(); PageObjectLogging.log( "Smart banner", "is closed", "is visible", result ); }
Source:
public void getUserTransactionsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserTransactions("foobar", new RetrofitPromise<List<Transaction>>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/transactions", MOCK_URL)); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Range", "foobar"))); }

Target:
public void getUserTransactionsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserTransactions("foobar", new RetrofitPromise<List<Transaction>>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/transactions", MOCK_URL)); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Range", "foobar"))); }
Source:
synchronized void connect() { RestHighLevelClient me = client; if (me == null) { synchronized (ElasticSearchAuditDestination.class) { me = client; if (client == null) { String urls = PropertiesUtil.getProperty("ranger.audit.solr.url"); String protocol = getProperty("ranger.audit.solr.url", "http"); int port = Integer.parseInt(getProperty("ranger.audit.solr.port", "8080")); if (urls != null) { urls = urls.trim(); } if (urls != null && urls.equalsIgnoreCase("NONE")) { urls = null; } try { me = client = new RestHighLevelClient( RestClient.builder( MiscUtil.toArray(urls, ",").stream() .map(x -> new HttpHost(x, port, protocol)) .<HttpHost>toArray(i -> new HttpHost[i]) )); ; } catch (Throwable t) { logger.fatal("Can't connect to Solr server. urls=" + urls, t); } } } } }

Target:
synchronized void connect() { if (client == null) { synchronized (ElasticSearchAuditDestination.class) { if (client == null) { String urls = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_URLS); String protocol = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PROTOCOL, "http"); String user = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_USER, ""); String password = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PWRD, ""); int port = Integer.parseInt(PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PORT, "9200")); this.index = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_INDEX, "audit"); logger.warn(String.format("Initializing ElasticSearch (URLs: %s; Protocol: %s; Port: %s)", urls, protocol, port)); if (urls != null) { urls = urls.trim(); } if (urls != null && urls.equalsIgnoreCase("NONE")) { logger.warn(String.format("Clearing URI config value: %s", urls)); urls = null; } try { final CredentialsProvider credentialsProvider; if(!user.isEmpty()) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); } else { credentialsProvider = null; } client = new RestHighLevelClient( RestClient.builder( MiscUtil.toArray(urls, ",").stream() .map(x -> new HttpHost(x, port, protocol)) .<HttpHost>toArray(i -> new HttpHost[i]) ).setHttpClientConfigCallback(clientBuilder -> (credentialsProvider != null) ? clientBuilder.setDefaultCredentialsProvider(credentialsProvider) : clientBuilder)); } catch (Throwable t) { logger.fatal("Can't connect to ElasticSearch server" + "." + " urls=" + urls, t); } } } } }
Source:
public void testNumberItemScale() throws BindingConfigParseException { String bindingConfig = "kaku#outside:weather,property=temperature"; PilightBindingConfig config = provider.parseBindingConfig(testItem, bindingConfig); Assert.assertNotNull(config); DecimalType number0 = (DecimalType) binding.getState("23", config); Assert.assertEquals(number0.toBigDecimal().compareTo(new BigDecimal("23")), 0); config.setScale(1); DecimalType number1 = (DecimalType) binding.getState("23.3", config); Assert.assertEquals(number1.toBigDecimal().compareTo(new BigDecimal("23.3")), 0); config.setScale(0); DecimalType number2 = (DecimalType) binding.getState("2.3", config); Assert.assertEquals(number2.toBigDecimal().compareTo(new BigDecimal("23")), 0); config.setScale(2); DecimalType number3 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number3.toBigDecimal().compareTo(new BigDecimal("2.33")), 0); config.setScale(-1); DecimalType number4 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number4.toBigDecimal().compareTo(new BigDecimal("2330")), 0); config.setScale(1); DecimalType number5 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number5.toBigDecimal().compareTo(new BigDecimal("23.3")), 0); }

Target:
public void testNumberItemScale() throws BindingConfigParseException { String bindingConfig = "kaku#outside:weather,property=temperature"; PilightBindingConfig config = provider.parseBindingConfig(testItem, bindingConfig); Assert.assertNotNull(config); DecimalType number0 = (DecimalType) binding.getState("23", config); Assert.assertEquals(number0.toBigDecimal().compareTo(new BigDecimal("23")), 0); config.setScale(1); DecimalType number1 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number1.toBigDecimal().compareTo(new BigDecimal("23.3")), 0); config.setScale(2); DecimalType number2 = (DecimalType) binding.getState("2233", config); Assert.assertEquals(number2.toBigDecimal().compareTo(new BigDecimal("22.33")), 0); config.setScale(-1); DecimalType number3 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number3.toBigDecimal().compareTo(new BigDecimal("2330")), 0); }
Source:
public void notifyChanged(Notification notification) { final int eventType = notification.getEventType(); if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } }

Target:
public void notifyChanged(Notification notification) { int eventType = notification.getEventType(); if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } }
Source:
public void shouldCheckpointEvenIfNoChanges() throws Exception { CheckpointCounter checkpointCounter = new CheckpointCounter(); try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); for ( int i = 0; i < 2; i++ ) { } index.checkpoint( unlimited() ); assertEquals( 1, checkpointCounter.count() ); } }

Target:
public void shouldCheckpointEvenIfNoChanges() throws Exception { CheckpointCounter checkpointCounter = new CheckpointCounter(); try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); index.checkpoint( unlimited() ); assertEquals( 1, checkpointCounter.count() ); } }
Source:
public static void importProject(Project project, String projectName, File projectRoot) throws IOException, ConfigurationException { GradleProjectImporter projectImporter = GradleProjectImporter.getInstance(); projectImporter.importProject(projectName, projectRoot, false, new GradleSyncListener() { @Override public void syncStarted(@NotNull Project project) { } @Override public void syncEnded(@NotNull Project project) { } @Override public void syncFailed(@NotNull Project project, @NotNull final String errorMessage) { fail(errorMessage); } }, project, null); }

Target:
public static void importProject(Project project, String projectName, File projectRoot) throws IOException, ConfigurationException { GradleProjectImporter projectImporter = GradleProjectImporter.getInstance(); boolean generateSources = false; projectImporter.importProject(projectName, projectRoot, generateSources, new GradleSyncListener() { @Override public void syncStarted(@NotNull Project project) { } @Override public void syncEnded(@NotNull Project project) { } @Override public void syncFailed(@NotNull Project project, @NotNull final String errorMessage) { fail(errorMessage); } }, project, null); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { patientPhoto = getResizedPortraitImage(output.getPath()); Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } else { output = null; } } else if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) { try { ParcelFileDescriptor parcelFileDescriptor = getActivity().getContentResolver().openFileDescriptor(data.getData(), getString(R.string.file_read_mode)); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); patientPhoto = image; Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } catch (Exception e) { logger.e(getString(R.string.gallery_image_request_failed_message), e); } } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { patientPhoto = getResizedPortraitImage(output.getPath()); Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } else { output = null; } } else if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) { try { ParcelFileDescriptor parcelFileDescriptor = getActivity().getContentResolver().openFileDescriptor(data.getData(), ApplicationConstants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); patientPhoto = image; Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } catch (Exception e) { logger.e("Error getting image from gallery.", e); } } }
Source:
private HttpUriRequest buildRequest(String endpoint, String token) { HttpGet request = new HttpGet(endpoint); request.addHeader("User-Agent", "openshift-resetclient-java"); request.addHeader("Authorization", "Bearer " + token); return request; }

Target:
private HttpUriRequest buildRequest(String endpoint, String token) { HttpGet request = new HttpGet(endpoint); request.addHeader("User-Agent", "openshift-restclient-java"); request.addHeader("Authorization", "Bearer " + token); return request; }
Source:
public void connect() throws IOException { try { clientCache = new ClientCacheFactory().addPoolLocator(getLocatorHost(), getLocatorPort()).create(); } catch (CacheClosedException ex) { LOG.info("error initiating client ", ex); } region = clientCache.getRegion(getRegionName()); if (region == null) { region = clientCache.<Object, Object> createClientRegionFactory(ClientRegionShortcut.PROXY).create( getRegionName()); } }

Target:
public void connect() throws IOException { try { clientCache = new ClientCacheFactory().addPoolLocator(getLocatorHost(), getLocatorPort()).create(); } catch (Exception ex) { throw new RuntimeException(ex); } region = clientCache.getRegion(getRegionName()); if (region == null) { region = clientCache.<Object, Object> createClientRegionFactory(ClientRegionShortcut.PROXY).create( getRegionName()); } }
Source:
public void setSessionLifetime(int lifetime) { sessionLifetime = lifetime; }

Target:
public synchronized void setSessionLifetime(int lifetime) { sessionLifetime = lifetime; }
Source:
public void testRemove() throws Exception { final IgniteCache<Integer, Integer> cache = grid(2).getOrCreateCache(getConfig()); GridTestSafeThreadFactory factory = new GridTestSafeThreadFactory(cacheMode().name()+"_remove"); for (TransactionConcurrency concurrency : TransactionConcurrency.values()) for (TransactionIsolation isolation : TransactionIsolation.values()) { cache.put(1, 1); try (Transaction tx = grid(2).transactions().txStart(concurrency, isolation)) { info(concurrency + " " + isolation); tx.savepoint("sp"); assertTrue(cache.remove(1)); Thread t = factory.newThread(new Runnable() { @Override public void run() { assertTrue(cache.remove(1, 1)); } }); t.start(); if (concurrency == TransactionConcurrency.PESSIMISTIC) while (t.getState() != Thread.State.WAITING) factory.checkError(); tx.rollbackToSavepoint("sp"); t.join(3_000); assertEquals("Broken multithreaded rollback to savepoint in " + concurrency + " " + isolation + " transaction.", null, cache.get(1)); tx.commit(); } assertEquals("Broken rollback to savepoint in " + concurrency + " " + isolation + " transaction.", null, cache.get(1)); } }

Target:
public void testRemove() { executeTestForAllCaches( new CIX3<NodeCombination, IgniteCache<Integer, Integer>, CacheConfiguration<Integer, Integer>>() { @Override public void applyx( NodeCombination nodes, IgniteCache<Integer, Integer> cache, CacheConfiguration<Integer, Integer> cfg) throws IgniteCheckedException { int key = generateKey(cfg, nodes.primaryForKey()); IgniteCache<Integer, Integer> cacheAsync = nodes.anotherTxOwner().getOrCreateCache(cfg); for (TxType txType : txTypes) { info("Transaction type " + txType); cache.put(key, 1); try (Transaction tx = nodes.txOwner().transactions().txStart(txType.concurrency, txType.isolation)) { tx.savepoint("sp"); assertTrue(cache.remove(key)); IgniteInternalFuture fut = GridTestUtils.runAsync( () -> assertTrue(cacheAsync.remove(key, 1)), "_remove"); waitForSecondCandidate(txType.concurrency, nodes.primaryForKey(), cache, cacheAsync, key); tx.rollbackToSavepoint("sp"); fut.get(FUT_TIMEOUT); assertEquals("Broken multithreaded rollback to savepoint in " + txType.concurrency + ' ' + txType.isolation + " transaction.", null, cache.get(key)); tx.commit(); } assertEquals("Broken rollback to savepoint in " + txType.concurrency + ' ' + txType.isolation + " transaction.", null, cache.get(key)); } }}); }
Source:
public String internalFragment() { ResolvedType resolvedType = getResolvedType(); if (resolvedType instanceof XmlSchemaExternalType) { return ((XmlSchemaExternalType) resolvedType).getInternalFragment(); } else { return null; } }

Target:
public String internalFragment() { ResolvedType resolvedType = getResolvedType(); if (resolvedType instanceof AbstractExternalType) { return ((AbstractExternalType) resolvedType).getInternalFragment(); } else { return null; } }
Source:
public void setUp() throws IOException { EmittingLogger.registerEmitter(new NoopServiceEmitter()); druidLeaderClient = EasyMock.createMock(DruidLeaderClient.class); config = createMock(LookupListeningAnnouncerConfig.class); lookupExtractorFactory = new MapLookupExtractorFactory( ImmutableMap.<String, String>of( "key", "value" ), true ); container = new LookupExtractorFactoryContainer("v0", lookupExtractorFactory); mapper.registerSubtypes(MapLookupExtractorFactory.class); String temporaryPath = temporaryFolder.newFolder().getAbsolutePath(); lookupReferencesManager = new LookupReferencesManager( new LookupConfig() { @Override public boolean getEnableLookupSyncOnStartup() { return true; } @Override public String getSnapshotWorkingDir() { return temporaryPath; } }, mapper, druidLeaderClient, config, true ); }

Target:
public void setUp() throws IOException { EmittingLogger.registerEmitter(new NoopServiceEmitter()); druidLeaderClient = EasyMock.createMock(DruidLeaderClient.class); config = createMock(LookupListeningAnnouncerConfig.class); lookupExtractorFactory = new MapLookupExtractorFactory( ImmutableMap.<String, String>of( "key", "value" ), true ); container = new LookupExtractorFactoryContainer("v0", lookupExtractorFactory); mapper.registerSubtypes(MapLookupExtractorFactory.class); String temporaryPath = temporaryFolder.newFolder().getAbsolutePath(); lookupReferencesManager = new LookupReferencesManager( new LookupConfig(temporaryFolder.newFolder().getAbsolutePath()), mapper, druidLeaderClient, config, true ); }
Source:
public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true); }

Target:
public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true, false); }
Source:
public void closeConnection(NetworkRequest originalRequest) throws InterruptedException { throw new NotImplementedException(); }

Target:
public void closeConnection(NetworkRequest originalRequest) throws InterruptedException { throw new UnsupportedOperationException(); }
Source:
public Side getEffectiveSide() { Thread thr = Thread.currentThread(); if (thr.getName().equals("Server thread") || thr.getName().startsWith("Netty Epoll Server IO") || thr.getName().startsWith("Netty Server IO")) { return Side.SERVER; } return Side.CLIENT; }

Target:
public Side getEffectiveSide() { final ThreadGroup group = Thread.currentThread().getThreadGroup(); return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : Side.CLIENT; }
Source:
public void fileSystemLimit() throws RocksDBException { RocksDB.loadLibrary(); final File persistedCacheLocation = new File("/tmp/", "diskBackedMap"); SstFileManager sstFileManager = new SstFileManager(Env.getDefault()); sstFileManager.setMaxAllowedSpaceUsage(FileUtils.ONE_KB); sstFileManager.setCompactionBufferSize(FileUtils.ONE_KB); final Options options = new Options().setCreateIfMissing(true) .setSstFileManager(sstFileManager) .setWriteBufferSize(FileUtils.ONE_KB); CorfuTable<String, String> table = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<String, String>>() {}) .setArguments(new RocksDbStreamingMap<String, String>( persistedCacheLocation, options, Serializers.JSON, getRuntime())) .setStreamName("diskBackedMap") .open(); final long ITERATION_COUNT = 100000; final int ENTITY_CHAR_SIZE = 1000; assertThatThrownBy(() -> LongStream.rangeClosed(1, ITERATION_COUNT).forEach(idx -> { String key = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); String value = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); table.put(key, value); String persistedValue = table.get(key); Assertions.assertEquals(value, persistedValue); })).isInstanceOf(UnrecoverableCorfuError.class) .hasCauseInstanceOf(RocksDBException.class); }

Target:
public void fileSystemLimit() throws RocksDBException { RocksDB.loadLibrary(); final File persistedCacheLocation = new File("/tmp/", "diskBackedMap"); SstFileManager sstFileManager = new SstFileManager(Env.getDefault()); sstFileManager.setMaxAllowedSpaceUsage(FileUtils.ONE_KB); sstFileManager.setCompactionBufferSize(FileUtils.ONE_KB); final Options options = new Options().setCreateIfMissing(true) .setSstFileManager(sstFileManager) .setWriteBufferSize(FileUtils.ONE_KB); CorfuTable<String, String> table = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<String, String>>() {}) .setArguments(new PersistedStreamingMap<String, String>( persistedCacheLocation, options, Serializers.JSON, getRuntime())) .setStreamName("diskBackedMap") .open(); final long ITERATION_COUNT = 100000; final int ENTITY_CHAR_SIZE = 1000; assertThatThrownBy(() -> LongStream.rangeClosed(1, ITERATION_COUNT).forEach(idx -> { String key = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); String value = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); table.put(key, value); String persistedValue = table.get(key); Assertions.assertEquals(value, persistedValue); })).isInstanceOf(UnrecoverableCorfuError.class) .hasCauseInstanceOf(RocksDBException.class); }