focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public void storeAll(Map<K, V> map) {
long startNanos = Timer.nanos();
try {
delegate.storeAll(map);
} finally {
storeAllProbe.recordValue(Timer.nanosElapsed(startNanos));
}
} | @Test
public void storeAll() {
Map<String, String> values = new HashMap<>();
values.put("1", "value1");
values.put("2", "value2");
cacheStore.storeAll(values);
verify(delegate).storeAll(values);
assertProbeCalledOnce("storeAll");
} |
public List<R> scanForResourcesPath(Path resourcePath) {
requireNonNull(resourcePath, "resourcePath must not be null");
List<R> resources = new ArrayList<>();
pathScanner.findResourcesForPath(
resourcePath,
canLoad,
processResource(DEFAULT_PACKAGE_NAME, NULL_FILTER, createUriResource(), resources::add));
return resources;
} | @Test
void scanForResourcesDirectory() {
File file = new File("src/test/resources/io/cucumber/core/resource");
List<URI> resources = resourceScanner.scanForResourcesPath(file.toPath());
assertThat(resources, containsInAnyOrder(
new File("src/test/resources/io/cucumber/core/resource/test/resource.txt").toURI(),
new File("src/test/resources/io/cucumber/core/resource/test/other-resource.txt").toURI(),
new File("src/test/resources/io/cucumber/core/resource/test/spaces in name resource.txt").toURI()));
} |
public static boolean getBoolean(String key, boolean def) {
String value = get(key);
if (value == null) {
return def;
}
value = value.trim().toLowerCase();
if (value.isEmpty()) {
return def;
}
if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
return true;
}
if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
return false;
}
logger.warn(
"Unable to parse the boolean system property '{}':{} - using the default value: {}",
key, value, def
);
return def;
} | @Test
public void testGetBooleanDefaultValueWithPropertyNull() {
assertTrue(SystemPropertyUtil.getBoolean("key", true));
assertFalse(SystemPropertyUtil.getBoolean("key", false));
} |
public String getStringArgument(String option) {
return getStringArgument(option, null);
} | @Test
public void testGetStringArgument() throws ParseException {
String[] args = {"--scan", "missing.file", "--artifactoryUsername", "blue42", "--project", "test"};
CliParser instance = new CliParser(getSettings());
try {
instance.parse(args);
Assert.fail("invalid scan argument should have caused an exception");
} catch (FileNotFoundException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid 'scan' argument"));
}
String expResult;
String result = instance.getStringArgument("missingArgument");
Assert.assertNull(result);
expResult = "blue42";
result = instance.getStringArgument(CliParser.ARGUMENT.ARTIFACTORY_USERNAME);
Assert.assertEquals(expResult, result);
} |
@Override
public ChannelBuffer copy() {
return copy(readerIndex, readableBytes());
} | @Test
void copyBoundaryCheck4() {
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(buffer.capacity(), 1));
} |
@Bean("CiConfiguration")
public CiConfiguration provide(Configuration configuration, CiVendor[] ciVendors) {
boolean disabled = configuration.getBoolean(PROP_DISABLED).orElse(false);
if (disabled) {
return new EmptyCiConfiguration();
}
List<CiVendor> detectedVendors = Arrays.stream(ciVendors)
.filter(CiVendor::isDetected)
.toList();
if (detectedVendors.size() > 1) {
List<String> names = detectedVendors.stream().map(CiVendor::getName).toList();
throw MessageException.of("Multiple CI environments are detected: " + names + ". Please check environment variables or set property " + PROP_DISABLED + " to true.");
}
if (detectedVendors.size() == 1) {
CiVendor vendor = detectedVendors.get(0);
LOG.info("Auto-configuring with CI '{}'", vendor.getName());
return vendor.loadConfiguration();
}
return new EmptyCiConfiguration();
} | @Test
public void empty_configuration_if_no_ci_vendors() {
CiConfiguration CiConfiguration = underTest.provide(cli.asConfig(), new CiVendor[0]);
assertThat(CiConfiguration.getScmRevision()).isEmpty();
} |
@Override
public String getIdentifier(UserInfo userInfo, ClientDetailsEntity client) {
String sectorIdentifier = null;
if (!Strings.isNullOrEmpty(client.getSectorIdentifierUri())) {
UriComponents uri = UriComponentsBuilder.fromUriString(client.getSectorIdentifierUri()).build();
sectorIdentifier = uri.getHost(); // calculate based on the host component only
} else {
Set<String> redirectUris = client.getRedirectUris();
UriComponents uri = UriComponentsBuilder.fromUriString(Iterables.getOnlyElement(redirectUris)).build();
sectorIdentifier = uri.getHost(); // calculate based on the host of the only redirect URI
}
if (sectorIdentifier != null) {
// if there's a sector identifier, use that for the lookup
PairwiseIdentifier pairwise = pairwiseIdentifierRepository.getBySectorIdentifier(userInfo.getSub(), sectorIdentifier);
if (pairwise == null) {
// we don't have an identifier, need to make and save one
pairwise = new PairwiseIdentifier();
pairwise.setIdentifier(UUID.randomUUID().toString());
pairwise.setUserSub(userInfo.getSub());
pairwise.setSectorIdentifier(sectorIdentifier);
pairwiseIdentifierRepository.save(pairwise);
}
return pairwise.getIdentifier();
} else {
return null;
}
} | @Test(expected = IllegalArgumentException.class)
public void testGetIdentifier_multipleRedirectError() {
String pairwise5 = service.getIdentifier(userInfoRegular, pairwiseClient5);
} |
public void addOtherTesseractConfig(String key, String value) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
Matcher m = ALLOWABLE_OTHER_PARAMS_PATTERN.matcher(key);
if (!m.find()) {
throw new IllegalArgumentException("Key contains illegal characters: " + key);
}
m.reset(value);
if (!m.find()) {
throw new IllegalArgumentException("Value contains illegal characters: " + value);
}
otherTesseractConfig.put(key.trim(), value.trim());
userConfigured.add("otherTesseractConfig");
} | @Test
public void testBadOtherValueControl() {
TesseractOCRConfig config = new TesseractOCRConfig();
assertThrows(IllegalArgumentException.class, () -> {
config.addOtherTesseractConfig("bad", "bad\u0001bad");
});
} |
public URI getHttpPublishUri() {
if (httpPublishUri == null) {
final URI defaultHttpUri = getDefaultHttpUri();
LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri);
return defaultHttpUri;
} else {
final InetAddress inetAddress = toInetAddress(httpPublishUri.getHost());
if (Tools.isWildcardInetAddress(inetAddress)) {
final URI defaultHttpUri = getDefaultHttpUri(httpPublishUri.getPath());
LOG.warn("\"{}\" is not a valid setting for \"http_publish_uri\". Using default <{}>.", httpPublishUri, defaultHttpUri);
return defaultHttpUri;
} else {
return Tools.normalizeURI(httpPublishUri, httpPublishUri.getScheme(), GRAYLOG_DEFAULT_PORT, httpPublishUri.getPath());
}
}
} | @Test
public void testHttpPublishUriIPv6WildcardKeepsPath() throws RepositoryException, ValidationException {
final Map<String, String> properties = ImmutableMap.of(
"http_bind_address", "[::]:9000",
"http_publish_uri", "http://[::]:9000/api/");
jadConfig.setRepository(new InMemoryRepository(properties)).addConfigurationBean(configuration).process();
assertThat(configuration.getHttpPublishUri())
.hasPath("/api/")
.isNotEqualTo(URI.create("http://[::]:9000/api/"));
} |
@Override
public Schema getSourceSchema() {
if (schema == null) {
try {
Schema.Parser parser = new Schema.Parser();
schema = parser.parse(schemaString);
} catch (Exception e) {
throw new HoodieSchemaException("Failed to parse schema: " + schemaString, e);
}
}
return schema;
} | @Test
public void validateOneOfSchemaGeneration() throws IOException {
TypedProperties properties = new TypedProperties();
properties.setProperty(ProtoClassBasedSchemaProviderConfig.PROTO_SCHEMA_CLASS_NAME.key(), WithOneOf.class.getName());
ProtoClassBasedSchemaProvider protoToAvroSchemaProvider = new ProtoClassBasedSchemaProvider(properties, null);
Schema protoSchema = protoToAvroSchemaProvider.getSourceSchema();
Schema.Parser parser = new Schema.Parser();
Schema expectedSchema = parser.parse(getClass().getClassLoader().getResourceAsStream("schema-provider/proto/oneof_schema.avsc"));
Assertions.assertEquals(expectedSchema, protoSchema);
} |
protected void subscribeOverride(final ConsumerConfig config, ConfigListener listener) {
try {
if (overrideObserver == null) { // 初始化
overrideObserver = new ZookeeperOverrideObserver();
}
overrideObserver.addConfigListener(config, listener);
final String overridePath = buildOverridePath(rootPath, config);
final AbstractInterfaceConfig registerConfig = getRegisterConfig(config);
// 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, overridePath, true);
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
if (LOGGER.isDebugEnabled(config.getAppName())) {
LOGGER.debug("Receive zookeeper event: " + "type=[" + event.getType() + "]");
}
switch (event.getType()) {
case CHILD_ADDED: //新增IP级配置
overrideObserver.addConfig(config, overridePath, event.getData());
break;
case CHILD_REMOVED: //删除IP级配置
overrideObserver.removeConfig(config, overridePath, event.getData(), registerConfig);
break;
case CHILD_UPDATED:// 更新IP级配置
overrideObserver.updateConfig(config, overridePath, event.getData());
break;
default:
break;
}
}
});
pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
INTERFACE_OVERRIDE_CACHE.put(overridePath, pathChildrenCache);
overrideObserver.updateConfigAll(config, overridePath, pathChildrenCache.getCurrentData());
} catch (Exception e) {
throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SUB_PROVIDER_OVERRIDE, EXT_NAME), e);
}
} | @Test
public void testOverrideObserver() throws InterruptedException {
ConsumerConfig<?> consumerConfig = new ConsumerConfig();
consumerConfig.setInterfaceId(TEST_SERVICE_NAME)
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setSubscribe(true)
.setSerialization("java")
.setInvokeType("sync")
.setTimeout(4444);
// 订阅Consumer Config
CountDownLatch latch = new CountDownLatch(1);
MockConfigListener configListener = new MockConfigListener();
configListener.setCountDownLatch(latch);
registry.subscribeOverride(consumerConfig, configListener);
Map<String, String> attributes = new ConcurrentHashMap<String, String>();
attributes.put(RpcConstants.CONFIG_KEY_TIMEOUT, "3333");
attributes.put(RpcConstants.CONFIG_KEY_APP_NAME, "test-server");
attributes.put(RpcConstants.CONFIG_KEY_SERIALIZATION, "java");
configListener.attrUpdated(attributes);
Map<String, String> configData = configListener.getData();
Assert.assertEquals(3, configData.size());
consumerConfig.setInterfaceId(TEST_SERVICE_NAME)
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server1"))
.setProxy("javassist")
.setSubscribe(true)
.setSerialization("java")
.setInvokeType("sync")
.setTimeout(5555);
configListener = new MockConfigListener();
configListener.setCountDownLatch(latch);
registry.subscribeOverride(consumerConfig, configListener);
attributes.put(RpcConstants.CONFIG_KEY_TIMEOUT, "4444");
attributes.put(RpcConstants.CONFIG_KEY_APP_NAME, "test-server2");
configListener.attrUpdated(attributes);
configData = configListener.getData();
Assert.assertEquals(3, configData.size());
latch.await(2000, TimeUnit.MILLISECONDS);
Assert.assertEquals(3, configData.size());
} |
@Deprecated
public static MaskTree decodeMaskUriFormat(StringBuilder toparse) throws IllegalMaskException
{
return decodeMaskUriFormat(toparse.toString());
} | @Test(dataProvider = "invalidArrayRangeProvider")
public void invalidArrayRange(String uriMask, String errorMessage)
{
try
{
URIMaskUtil.decodeMaskUriFormat(uriMask);
fail("Excepted to throw an exception with a message: " + errorMessage);
}
catch (IllegalMaskException e)
{
assertTrue(e.getMessage().contains(errorMessage));
}
} |
@PostMapping("delete")
public String deleteProduct(@ModelAttribute("product") Product product) {
this.productsRestClient.deleteProduct(product.id());
return "redirect:/catalogue/products/list";
} | @Test
void deleteProduct_RedirectsToProductsListPage() {
// given
var product = new Product(1, "Товар №1", "Описание товара №1");
// when
var result = this.controller.deleteProduct(product);
// then
assertEquals("redirect:/catalogue/products/list", result);
verify(this.productsRestClient).deleteProduct(1);
verifyNoMoreInteractions(this.productsRestClient);
} |
public List<UserInfo> listUser(String addr, String filter, long millis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
ListUsersRequestHeader requestHeader = new ListUsersRequestHeader(filter);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.AUTH_LIST_USER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, millis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return RemotingSerializable.decodeList(response.getBody(), UserInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
} | @Test
public void assertListUser() throws RemotingException, InterruptedException, MQBrokerException {
mockInvokeSync();
setResponseBody(Collections.singletonList(createUserInfo()));
List<UserInfo> actual = mqClientAPI.listUser(defaultBrokerAddr, "", defaultTimeout);
assertNotNull(actual);
assertEquals("username", actual.get(0).getUsername());
assertEquals("password", actual.get(0).getPassword());
assertEquals("userStatus", actual.get(0).getUserStatus());
assertEquals("userType", actual.get(0).getUserType());
} |
@Override
public void start() {
Optional<String> passcodeOpt = configuration.get(WEB_SYSTEM_PASS_CODE.getKey())
// if present, result is never empty string
.map(StringUtils::trimToNull);
if (passcodeOpt.isPresent()) {
logState("enabled");
configuredPasscode = passcodeOpt.get();
} else {
logState("disabled");
configuredPasscode = null;
}
} | @Test
public void passcode_is_disabled_if_blank_configuration() {
configurePasscode("");
underTest.start();
assertThat(logTester.logs(Level.INFO)).contains("System authentication by passcode is disabled");
} |
@Override
public CompletableFuture<JobStatus> getJobTerminationFuture() {
return jobTerminationFuture;
} | @Test
void testInitialRequirementLowerBoundBeyondAvailableSlotsCausesImmediateFailure()
throws Exception {
final JobGraph jobGraph = createJobGraph();
final DefaultDeclarativeSlotPool declarativeSlotPool =
createDeclarativeSlotPool(jobGraph.getJobID());
final int availableSlots = 1;
JobResourceRequirements initialJobResourceRequirements =
createRequirementsWithEqualLowerAndUpperParallelism(PARALLELISM);
final AdaptiveScheduler scheduler =
prepareSchedulerWithNoTimeouts(jobGraph, declarativeSlotPool)
.withConfigurationOverride(
conf -> {
conf.set(
JobManagerOptions.RESOURCE_WAIT_TIMEOUT,
Duration.ofMillis(1));
return conf;
})
.setJobResourceRequirements(initialJobResourceRequirements)
.build();
final SubmissionBufferingTaskManagerGateway taskManagerGateway =
createSubmissionBufferingTaskManagerGateway(PARALLELISM, scheduler);
startJobWithSlotsMatchingParallelism(
scheduler, declarativeSlotPool, taskManagerGateway, availableSlots);
// the job will fail because not enough slots are available
FlinkAssertions.assertThatFuture(scheduler.getJobTerminationFuture())
.eventuallySucceeds()
.isEqualTo(JobStatus.FAILED);
// no task was ever submitted because we failed immediately
assertThat(taskManagerGateway.submittedTasks).isEmpty();
} |
@Override
public Object evaluate(final Map<String, Object> requestData,
final PMMLRuntimeContext context) {
throw new KiePMMLException("KiePMMLModelWithSources is not meant to be used for actual evaluation");
} | @Test
void evaluate() {
assertThatExceptionOfType(KiePMMLException.class).isThrownBy(() -> {
kiePMMLModelWithSources.evaluate(Collections.EMPTY_MAP, new PMMLRuntimeContextTest());
});
} |
public void ensureActiveGroup() {
while (!ensureActiveGroup(time.timer(Long.MAX_VALUE))) {
log.warn("still waiting to ensure active group");
}
} | @Test
public void testWakeupAfterJoinGroupReceived() throws Exception {
setupCoordinator();
mockClient.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
mockClient.prepareResponse(body -> {
boolean isJoinGroupRequest = body instanceof JoinGroupRequest;
if (isJoinGroupRequest)
// wakeup after the request returns
consumerClient.wakeup();
return isJoinGroupRequest;
}, joinGroupFollowerResponse(1, memberId, leaderId, Errors.NONE));
mockClient.prepareResponse(syncGroupResponse(Errors.NONE));
AtomicBoolean heartbeatReceived = prepareFirstHeartbeat();
try {
coordinator.ensureActiveGroup();
fail("Should have woken up from ensureActiveGroup()");
} catch (WakeupException ignored) {
}
assertEquals(1, coordinator.onJoinPrepareInvokes);
assertEquals(0, coordinator.onJoinCompleteInvokes);
assertFalse(heartbeatReceived.get());
coordinator.ensureActiveGroup();
assertEquals(1, coordinator.onJoinPrepareInvokes);
assertEquals(1, coordinator.onJoinCompleteInvokes);
awaitFirstHeartbeat(heartbeatReceived);
} |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
@Category(ValidatesRunner.class)
public void testMapAsEntrySetSideInput() {
final PCollectionView<Map<String, Integer>> view =
pipeline
.apply("CreateSideInput", Create.of(KV.of("a", 1), KV.of("b", 3)))
.apply(View.asMap());
PCollection<KV<String, Integer>> output =
pipeline
.apply("CreateMainInput", Create.of(2 /* size */))
.apply(
"OutputSideInputs",
ParDo.of(
new DoFn<Integer, KV<String, Integer>>() {
@ProcessElement
public void processElement(ProcessContext c) {
assertEquals((int) c.element(), c.sideInput(view).size());
assertEquals((int) c.element(), c.sideInput(view).entrySet().size());
for (Entry<String, Integer> entry : c.sideInput(view).entrySet()) {
c.output(KV.of(entry.getKey(), entry.getValue()));
}
}
})
.withSideInputs(view));
PAssert.that(output).containsInAnyOrder(KV.of("a", 1), KV.of("b", 3));
pipeline.run();
} |
public static Integer[] getPreselectedTagsArray(Note note, List<Tag> tags) {
List<Integer> t = new ArrayList<>();
for (String noteTag : TagsHelper.retrieveTags(note).keySet()) {
for (Tag tag : tags) {
if (tag.getText().equals(noteTag)) {
t.add(tags.indexOf(tag));
break;
}
}
}
return t.toArray(new Integer[]{});
} | @Test
public void getPreselectedTagsArray() {
final Tag anotherTag = new Tag("#anotherTag", 1);
Note anotherNote = new Note();
anotherNote.setContent(TAG1.getText() + " " + TAG2.getText() + " " + anotherTag);
note.setContent(note.getContent().replace(TAG4.toString(), ""));
List<Tag> tags = Arrays.asList(TAG1, TAG2, TAG3, TAG4, anotherTag);
List<Note> notes = Arrays.asList(note, anotherNote);
Integer[] preselectedTags = TagsHelper.getPreselectedTagsArray(notes, tags);
assertEquals(4, preselectedTags.length);
for (Integer preselectedTag : preselectedTags) {
assertNotEquals((int) preselectedTag, tags.indexOf(TAG4));
}
} |
public static FlinkJobServerDriver fromParams(String[] args) {
return fromConfig(parseArgs(args));
} | @Test(timeout = 30_000)
public void testJobServerDriverWithoutExpansionService() throws Exception {
FlinkJobServerDriver driver = null;
Thread driverThread = null;
final PrintStream oldErr = System.err;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream newErr = new PrintStream(baos);
try {
System.setErr(newErr);
driver =
FlinkJobServerDriver.fromParams(
new String[] {"--job-port=0", "--artifact-port=0", "--expansion-port=-1"});
driverThread = new Thread(driver);
driverThread.start();
boolean success = false;
while (!success) {
newErr.flush();
String output = baos.toString(StandardCharsets.UTF_8.name());
if (output.contains("JobService started on localhost:")
&& output.contains("ArtifactStagingService started on localhost:")) {
success = true;
} else if (output.contains("ExpansionService started on localhost:")) {
throw new RuntimeException("ExpansionService started but should not.");
}
{
Thread.sleep(100);
}
}
assertThat(driver.getJobServerUrl(), is(not(nullValue())));
assertThat(
baos.toString(StandardCharsets.UTF_8.name()), containsString(driver.getJobServerUrl()));
assertThat(driverThread.isAlive(), is(true));
} catch (Throwable t) {
// restore to print exception
System.setErr(oldErr);
throw t;
} finally {
System.setErr(oldErr);
if (driver != null) {
driver.stop();
}
if (driverThread != null) {
driverThread.interrupt();
driverThread.join();
}
}
} |
@VisibleForTesting
void authenticateLoginCredentials() throws Exception {
KettleClientEnvironment.init();
if ( client == null ) {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
client = Client.create( clientConfig );
client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );
}
WebResource resource = client.resource( url + AUTHENTICATION + AdministerSecurityAction.NAME );
String response = resource.get( String.class );
if ( !response.equals( "true" ) ) {
throw new Exception( Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.ERROR_0012.ACCESS_DENIED" ) );
}
} | @Test
public void authenticateLoginCredentials() throws Exception {
RepositoryCleanupUtil util = mock( RepositoryCleanupUtil.class );
doCallRealMethod().when( util ).authenticateLoginCredentials();
setInternalState( util, "url", "http://localhost:8080/pentaho" );
setInternalState( util, "username", "admin" );
setInternalState( util, "password", "Encrypted 2be98afc86aa7f2e4bb18bd63c99dbdde" );
WebResource resource = mock( WebResource.class );
doReturn( "true" ).when( resource ).get( String.class );
Client client = mock( Client.class );
doCallRealMethod().when( client ).addFilter( any( HTTPBasicAuthFilter.class ) );
doCallRealMethod().when( client ).getHeadHandler();
doReturn( resource ).when( client ).resource( anyString() );
try( MockedStatic<Client> mockedClient = mockStatic( Client.class) ) {
mockedClient.when( () -> Client.create( any( ClientConfig.class ) ) ).thenReturn( client );
when( Client.create( any( ClientConfig.class ) ) ).thenReturn( client );
util.authenticateLoginCredentials();
// the expected value is: "Basic <base64 encoded username:password>"
assertEquals( "Basic " + new String( Base64.getEncoder().encode( "admin:password".getBytes( "utf-8" ) ) ),
getInternalState( client.getHeadHandler(), "authentication" ) );
}
} |
static Object parseCell(String cell, Schema.Field field) {
Schema.FieldType fieldType = field.getType();
try {
switch (fieldType.getTypeName()) {
case STRING:
return cell;
case INT16:
return Short.parseShort(cell);
case INT32:
return Integer.parseInt(cell);
case INT64:
return Long.parseLong(cell);
case BOOLEAN:
return Boolean.parseBoolean(cell);
case BYTE:
return Byte.parseByte(cell);
case DECIMAL:
return new BigDecimal(cell);
case DOUBLE:
return Double.parseDouble(cell);
case FLOAT:
return Float.parseFloat(cell);
case DATETIME:
return Instant.parse(cell);
default:
throw new UnsupportedOperationException(
"Unsupported type: " + fieldType + ", consider using withCustomRecordParsing");
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
e.getMessage() + " field " + field.getName() + " was received -- type mismatch");
}
} | @Test
public void givenValidByteCell_parses() {
Byte byteNum = Byte.parseByte("4");
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("4", byteNum);
Schema schema = Schema.builder().addByteField("a_byte").addInt32Field("an_integer").build();
assertEquals(
cellToExpectedValue.getValue(),
CsvIOParseHelpers.parseCell(
cellToExpectedValue.getKey().toString(), schema.getField("a_byte")));
} |
public static void copyBytes(InputStream in, OutputStream out,
int buffSize, boolean close)
throws IOException {
try {
copyBytes(in, out, buffSize);
if(close) {
out.close();
out = null;
in.close();
in = null;
}
} finally {
if(close) {
closeStream(out);
closeStream(in);
}
}
} | @Test
public void testCopyBytesWithCountShouldThrowOutTheStreamClosureExceptions()
throws Exception {
InputStream inputStream = Mockito.mock(InputStream.class);
OutputStream outputStream = Mockito.mock(OutputStream.class);
Mockito.doReturn(-1).when(inputStream).read(new byte[4096], 0, 1);
Mockito.doThrow(new IOException("Exception in closing the stream")).when(
outputStream).close();
try {
IOUtils.copyBytes(inputStream, outputStream, (long) 1, true);
fail("Should throw out the exception");
} catch (IOException e) {
assertEquals("Not throwing the expected exception.",
"Exception in closing the stream", e.getMessage());
}
Mockito.verify(inputStream, Mockito.atLeastOnce()).close();
Mockito.verify(outputStream, Mockito.atLeastOnce()).close();
} |
public String getBindingActualTable(final String dataSource, final String logicTable, final String otherLogicTable, final String otherActualTable) {
Optional<ShardingTable> otherShardingTable = Optional.ofNullable(shardingTables.get(otherLogicTable));
int index = otherShardingTable.map(optional -> optional.findActualTableIndex(dataSource, otherActualTable)).orElse(-1);
if (-1 == index) {
throw new ActualTableNotFoundException(dataSource, otherActualTable);
}
Optional<ShardingTable> shardingTable = Optional.ofNullable(shardingTables.get(logicTable));
if (shardingTable.isPresent()) {
return shardingTable.get().getActualDataNodes().get(index).getTableName();
}
throw new BindingTableNotFoundException(dataSource, logicTable, otherActualTable);
} | @Test
void assertGetBindingActualTablesFailureWhenLogicTableNotFound() {
assertThrows(BindingTableNotFoundException.class, () -> createBindingTableRule().getBindingActualTable("ds0", "No_Logic_Table", "LOGIC_TABLE", "table_1"));
} |
StringBuilder codeForComplexFieldExtraction(Descriptors.FieldDescriptor desc, String fieldNameInCode,
String javaFieldType, int indent, int varNum, String decoderMethod, String additionalExtractions) {
StringBuilder code = new StringBuilder();
if (StringUtils.isBlank(additionalExtractions)) {
additionalExtractions = "";
}
if (desc.isRepeated()) {
varNum++;
String listVarName = "list" + varNum;
code.append(completeLine(String.format("List<Object> %s = new ArrayList<>()", listVarName), indent));
code.append(addIndent(
String.format("for (%s row: msg.%s()) {", javaFieldType, getProtoFieldListMethodName(fieldNameInCode)),
indent));
if (!StringUtils.isBlank(decoderMethod)) {
code.append(completeLine(
String.format("%s.add(%s(row%s))", listVarName, decoderMethod, additionalExtractions),
++indent));
} else {
code.append(completeLine(String.format("%s.add(row%s)", listVarName, additionalExtractions), ++indent));
}
code.append(addIndent("}", --indent));
code.append(addIndent(String.format("if (!%s.isEmpty()) {", listVarName), indent));
code.append(completeLine(
String.format("msgMap.put(\"%s\", %s.toArray())", desc.getName(), listVarName),
++indent));
code.append(addIndent("}", --indent));
} else if (desc.hasPresence()) {
code.append(addIndent(String.format("if (msg.%s()) {", hasPresenceMethodName(fieldNameInCode)), indent));
code.append(completeLine(putFieldInMsgMapCode(
desc.getName(), getProtoFieldMethodName(fieldNameInCode), decoderMethod, additionalExtractions),
++indent));
code.append(addIndent("}", --indent));
} else {
code.append(completeLine(putFieldInMsgMapCode(
desc.getName(), getProtoFieldMethodName(fieldNameInCode), decoderMethod, additionalExtractions),
indent));
}
return code;
} | @Test
public void testCodeForComplexFieldExtractionNonRepeated() {
MessageCodeGen messageCodeGen = new MessageCodeGen();
// Message type
Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(NESTED_MESSAGE);
String fieldNameInCode = ProtobufInternalUtils.underScoreToCamelCase(fd.getName(), true);
String javaType = ProtoBufUtils.getFullJavaName(fd.getMessageType());
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "decodeNestedMessage", "").toString(),
" if (msg.hasNestedMessage()) {\n"
+ " msgMap.put(\"nested_message\", decodeNestedMessage(msg.getNestedMessage()));\n" + " }\n");
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "decodeNestedMessage", null).toString(),
" if (msg.hasNestedMessage()) {\n"
+ " msgMap.put(\"nested_message\", decodeNestedMessage(msg.getNestedMessage()));\n" + " }\n");
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "decodeNestedMessage", ".toString()").toString(),
" if (msg.hasNestedMessage()) {\n"
+ " msgMap.put(\"nested_message\", decodeNestedMessage(msg.getNestedMessage().toString()));\n"
+ " }\n");
// Complex type with no presence i.e Scalar type with additional Extractions eg bytes, enum, bool
fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(BOOL_FIELD);
fieldNameInCode = ProtobufInternalUtils.underScoreToCamelCase(fd.getName(), true);
javaType = "String";
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "String.valueOf", "").toString(),
" msgMap.put(\"bool_field\", String.valueOf(msg.getBoolField()));\n");
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "String.valueOf", null).toString(),
" msgMap.put(\"bool_field\", String.valueOf(msg.getBoolField()));\n");
fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(ENUM_FIELD);
fieldNameInCode = ProtobufInternalUtils.underScoreToCamelCase(fd.getName(), true);
javaType = "String";
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "", ".name()").toString(),
" msgMap.put(\"enum_field\", msg.getEnumField().name());\n");
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, null, ".name()").toString(),
" msgMap.put(\"enum_field\", msg.getEnumField().name());\n");
assertEquals(messageCodeGen.codeForComplexFieldExtraction(
fd, fieldNameInCode, javaType, 1, 1, "String.valueOf", ".name()").toString(),
" msgMap.put(\"enum_field\", String.valueOf(msg.getEnumField().name()));\n");
} |
public static Schema fromTableSchema(TableSchema tableSchema) {
return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build());
} | @Test
public void testFromTableSchema_map_array() {
Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_MAP_TYPE);
assertEquals(MAP_ARRAY_TYPE, beamSchema);
} |
public static Rank rank(Query query, QueryChain... ranks) {
return new Rank(query, ranks);
} | @Test
void rank() {
String q = Q.select("*")
.from("sd1")
.where(Q.rank(
Q.p("f1").contains("v1"),
Q.p("f2").contains("v2"),
Q.p("f3").eq(3))
)
.build();
assertEquals(q, "yql=select * from sd1 where rank(f1 contains \"v1\", f2 contains \"v2\", f3 = 3)");
} |
public static void renameKey(Map<String, Object> map, String originalKey, String newKey) {
if (map.containsKey(originalKey)) {
final Object value = map.remove(originalKey);
map.put(newKey, value);
}
} | @Test
public void renameKeyHandlesEmptyMap() {
final Map<String, Object> map = new HashMap<>();
MapUtils.renameKey(map, "foo", "bar");
assertThat(map).isEmpty();
} |
@Override
public String convert(ILoggingEvent event) {
Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
if (mdcPropertyMap == null) {
return defaultValue;
}
if (key == null) {
return outputMDCForAllKeys(mdcPropertyMap);
} else {
String value = mdcPropertyMap.get(key);
if (value != null) {
return value;
} else {
return defaultValue;
}
}
} | @Test
public void testConvertWithOneEntry() {
String k = "MDCConverterTest_k"+diff;
String v = "MDCConverterTest_v"+diff;
MDC.put(k, v);
ILoggingEvent le = createLoggingEvent();
String result = converter.convert(le);
assertEquals(k+"="+v, result);
} |
@Override
public AlterReplicaLogDirsResult alterReplicaLogDirs(Map<TopicPartitionReplica, String> replicaAssignment, final AlterReplicaLogDirsOptions options) {
final Map<TopicPartitionReplica, KafkaFutureImpl<Void>> futures = new HashMap<>(replicaAssignment.size());
for (TopicPartitionReplica replica : replicaAssignment.keySet())
futures.put(replica, new KafkaFutureImpl<>());
Map<Integer, AlterReplicaLogDirsRequestData> replicaAssignmentByBroker = new HashMap<>();
for (Map.Entry<TopicPartitionReplica, String> entry: replicaAssignment.entrySet()) {
TopicPartitionReplica replica = entry.getKey();
String logDir = entry.getValue();
int brokerId = replica.brokerId();
AlterReplicaLogDirsRequestData value = replicaAssignmentByBroker.computeIfAbsent(brokerId,
key -> new AlterReplicaLogDirsRequestData());
AlterReplicaLogDir alterReplicaLogDir = value.dirs().find(logDir);
if (alterReplicaLogDir == null) {
alterReplicaLogDir = new AlterReplicaLogDir();
alterReplicaLogDir.setPath(logDir);
value.dirs().add(alterReplicaLogDir);
}
AlterReplicaLogDirTopic alterReplicaLogDirTopic = alterReplicaLogDir.topics().find(replica.topic());
if (alterReplicaLogDirTopic == null) {
alterReplicaLogDirTopic = new AlterReplicaLogDirTopic().setName(replica.topic());
alterReplicaLogDir.topics().add(alterReplicaLogDirTopic);
}
alterReplicaLogDirTopic.partitions().add(replica.partition());
}
final long now = time.milliseconds();
for (Map.Entry<Integer, AlterReplicaLogDirsRequestData> entry: replicaAssignmentByBroker.entrySet()) {
final int brokerId = entry.getKey();
final AlterReplicaLogDirsRequestData assignment = entry.getValue();
runnable.call(new Call("alterReplicaLogDirs", calcDeadlineMs(now, options.timeoutMs()),
new ConstantNodeIdProvider(brokerId)) {
@Override
public AlterReplicaLogDirsRequest.Builder createRequest(int timeoutMs) {
return new AlterReplicaLogDirsRequest.Builder(assignment);
}
@Override
public void handleResponse(AbstractResponse abstractResponse) {
AlterReplicaLogDirsResponse response = (AlterReplicaLogDirsResponse) abstractResponse;
for (AlterReplicaLogDirTopicResult topicResult: response.data().results()) {
for (AlterReplicaLogDirPartitionResult partitionResult: topicResult.partitions()) {
TopicPartitionReplica replica = new TopicPartitionReplica(
topicResult.topicName(), partitionResult.partitionIndex(), brokerId);
KafkaFutureImpl<Void> future = futures.get(replica);
if (future == null) {
log.warn("The partition {} in the response from broker {} is not in the request",
new TopicPartition(topicResult.topicName(), partitionResult.partitionIndex()),
brokerId);
} else if (partitionResult.errorCode() == Errors.NONE.code()) {
future.complete(null);
} else {
future.completeExceptionally(Errors.forCode(partitionResult.errorCode()).exception());
}
}
}
// The server should send back a response for every replica. But do a sanity check anyway.
completeUnrealizedFutures(
futures.entrySet().stream().filter(entry -> entry.getKey().brokerId() == brokerId),
replica -> "The response from broker " + brokerId +
" did not contain a result for replica " + replica);
}
@Override
void handleFailure(Throwable throwable) {
// Only completes the futures of brokerId
completeAllExceptionally(
futures.entrySet().stream()
.filter(entry -> entry.getKey().brokerId() == brokerId)
.map(Map.Entry::getValue),
throwable);
}
}, now);
}
return new AlterReplicaLogDirsResult(new HashMap<>(futures));
} | @Test
public void testAlterReplicaLogDirsUnrequested() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
createAlterLogDirsResponse(env, env.cluster().nodeById(0), Errors.NONE, 1, 2);
TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic", 1, 0);
Map<TopicPartitionReplica, String> logDirs = new HashMap<>();
logDirs.put(tpr1, "/data1");
AlterReplicaLogDirsResult result = env.adminClient().alterReplicaLogDirs(logDirs);
assertNull(result.values().get(tpr1).get());
}
} |
public boolean hasOperationPermissionDefined() {
return !operationConfig.equals(new OperationConfig());
} | @Test
public void shouldReturnTrueIfOperationPermissionDefined() {
Authorization authorization = new Authorization(new OperationConfig(new AdminUser(new CaseInsensitiveString("baby"))));
assertThat(authorization.hasOperationPermissionDefined(), is(true));
} |
@Override
public ConnectorInfo connectorInfo(String connector) {
final ClusterConfigState configState = configBackingStore.snapshot();
if (!configState.contains(connector))
return null;
Map<String, String> config = configState.rawConnectorConfig(connector);
return new ConnectorInfo(
connector,
config,
configState.tasks(connector),
connectorType(config)
);
} | @Test
public void testConnectorInfo() {
AbstractHerder herder = testHerder();
when(plugins.newConnector(anyString())).thenReturn(new SampleSourceConnector());
when(herder.plugins()).thenReturn(plugins);
when(configStore.snapshot()).thenReturn(SNAPSHOT);
ConnectorInfo info = herder.connectorInfo(CONN1);
assertEquals(CONN1, info.name());
assertEquals(CONN1_CONFIG, info.config());
assertEquals(Arrays.asList(TASK0, TASK1, TASK2), info.tasks());
assertEquals(ConnectorType.SOURCE, info.type());
} |
static void checkNotInDisallowedList(String clsName) {
if (DEFAULT_DISALLOWED_LIST_SET.contains(clsName)) {
throw new InsecureException(String.format("%s hit disallowed list", clsName));
}
} | @Test
public void testCheckHitDisallowedList() {
// Hit the disallowed list.
Assert.assertThrows(
InsecureException.class,
() -> DisallowedList.checkNotInDisallowedList("java.rmi.server.UnicastRemoteObject"));
Assert.assertThrows(
InsecureException.class,
() ->
DisallowedList.checkNotInDisallowedList(
"com.sun.jndi.rmi.registry.BindingEnumeration"));
Assert.assertThrows(
InsecureException.class,
() -> DisallowedList.checkNotInDisallowedList(java.beans.Expression.class.getName()));
Assert.assertThrows(
InsecureException.class,
() -> DisallowedList.checkNotInDisallowedList(UnicastRemoteObject.class.getName()));
// Not in the disallowed list.
DisallowedList.checkNotInDisallowedList("java.util.HashMap");
} |
@Override
public void recover() {
final List<MappedFile> mappedFiles = this.mappedFileQueue.getMappedFiles();
if (!mappedFiles.isEmpty()) {
int index = mappedFiles.size() - 3;
if (index < 0) {
index = 0;
}
MappedFile mappedFile = mappedFiles.get(index);
ByteBuffer byteBuffer = mappedFile.sliceByteBuffer();
int mappedFileOffset = 0;
long processOffset = mappedFile.getFileFromOffset();
while (true) {
for (int i = 0; i < mappedFileSize; i += CQ_STORE_UNIT_SIZE) {
byteBuffer.position(i);
long offset = byteBuffer.getLong();
int size = byteBuffer.getInt();
byteBuffer.getLong(); //tagscode
byteBuffer.getLong(); //timestamp
long msgBaseOffset = byteBuffer.getLong();
short batchSize = byteBuffer.getShort();
if (offset >= 0 && size > 0 && msgBaseOffset >= 0 && batchSize > 0) {
mappedFileOffset += CQ_STORE_UNIT_SIZE;
this.maxMsgPhyOffsetInCommitLog = offset;
} else {
log.info("Recover current batch consume queue file over, " + "file:{} offset:{} size:{} msgBaseOffset:{} batchSize:{} mappedFileOffset:{}",
mappedFile.getFileName(), offset, size, msgBaseOffset, batchSize, mappedFileOffset);
if (mappedFileOffset != mappedFileSize) {
mappedFile.setWrotePosition(mappedFileOffset);
mappedFile.setFlushedPosition(mappedFileOffset);
mappedFile.setCommittedPosition(mappedFileOffset);
}
break;
}
}
index++;
if (index >= mappedFiles.size()) {
log.info("Recover last batch consume queue file over, last mapped file:{} ", mappedFile.getFileName());
break;
} else {
mappedFile = mappedFiles.get(index);
byteBuffer = mappedFile.sliceByteBuffer();
processOffset = mappedFile.getFileFromOffset();
mappedFileOffset = 0;
log.info("Recover next batch consume queue file: " + mappedFile.getFileName());
}
}
processOffset += mappedFileOffset;
mappedFileQueue.setFlushedWhere(processOffset);
mappedFileQueue.setCommittedWhere(processOffset);
mappedFileQueue.truncateDirtyFiles(processOffset);
reviseMaxAndMinOffsetInQueue();
}
} | @Test
public void testLoad() throws IOException {
scq = new SparseConsumeQueue(topic, queueId, path, BatchConsumeQueue.CQ_STORE_UNIT_SIZE, defaultMessageStore);
String file1 = UtilAll.offset2FileName(111111);
String file2 = UtilAll.offset2FileName(222222);
long phyOffset = 10;
long queueOffset = 1;
ByteBuffer bb = ByteBuffer.allocate(BatchConsumeQueue.CQ_STORE_UNIT_SIZE);
fillByteBuf(bb, phyOffset, queueOffset);
Files.createDirectories(Paths.get(path, topic, String.valueOf(queueId)));
Files.write(Paths.get(path, topic, String.valueOf(queueId), file1), bb.array(),
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
bb.clear();
fillByteBuf(bb, phyOffset + 1, queueOffset + 1);
Files.write(Paths.get(path, topic, String.valueOf(queueId), file2), bb.array(),
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
scq.load();
scq.recover();
assertEquals(scq.get(queueOffset + 1).getPos(), phyOffset + 1);
} |
@Override
public String render(String text) {
if (StringUtils.isBlank(text)) {
return "";
}
if (regex.isEmpty() || link.isEmpty()) {
Comment comment = new Comment();
comment.escapeAndAdd(text);
return comment.render();
}
try {
Matcher matcher = Pattern.compile(regex).matcher(text);
int start = 0;
Comment comment = new Comment();
while (hasMatch(matcher)) {
comment.escapeAndAdd(text.substring(start, matcher.start()));
comment.add(dynamicLink(matcher));
start = matcher.end();
}
comment.escapeAndAdd(text.substring(start));
return comment.render();
} catch (PatternSyntaxException e) {
LOGGER.warn("Illegal regular expression: {} - {}", regex, e.getMessage());
}
return text;
} | @Test
// #2324
public void shouldRenderAllPossibleMatches() throws Exception {
String link = "http://mingle05/projects/cce/cards/${ID}";
String regex = "#(\\d+)";
trackingTool = new DefaultCommentRenderer(link, regex);
String result = trackingTool.render("#111, #222: checkin message; #333: another message");
assertThat(result,
is("<a href=\"http://mingle05/projects/cce/cards/111\" target=\"story_tracker\">#111</a>, "
+ "<a href=\"http://mingle05/projects/cce/cards/222\" "
+ "target=\"story_tracker\">#222</a>: checkin message; "
+ "<a href=\"http://mingle05/projects/cce/cards/333\" "
+ "target=\"story_tracker\">#333</a>: another message"));
} |
@Override
public double quantile(double p) {
if (p < 0.0 || p > 1.0) {
throw new IllegalArgumentException("Invalid p: " + p);
}
return Beta.inverseRegularizedIncompleteBetaFunction(alpha, beta, p);
} | @Test
public void testQuantile() {
System.out.println("quantile");
BetaDistribution instance = new BetaDistribution(2, 5);
instance.rand();
assertEquals(0.008255493, instance.quantile(0.001), 1E-5);
assertEquals(0.09259526, instance.quantile(0.1), 1E-5);
assertEquals(0.1398807, instance.quantile(0.2), 1E-5);
assertEquals(0.1818035, instance.quantile(0.3), 1E-5);
assertEquals(0.2225835, instance.quantile(0.4), 1E-5);
assertEquals(0.26445, instance.quantile(0.5), 1E-5);
assertEquals(0.5103163, instance.quantile(0.9), 1E-5);
assertEquals(0.7056863, instance.quantile(0.99), 1E-5);
} |
public boolean hasPermission(NacosUser nacosUser, Permission permission) {
//update password
if (AuthConstants.UPDATE_PASSWORD_ENTRY_POINT.equals(permission.getResource().getName())) {
return true;
}
List<RoleInfo> roleInfoList = getRoles(nacosUser.getUserName());
if (CollectionUtils.isEmpty(roleInfoList)) {
return false;
}
// Global admin pass:
for (RoleInfo roleInfo : roleInfoList) {
if (AuthConstants.GLOBAL_ADMIN_ROLE.equals(roleInfo.getRole())) {
nacosUser.setGlobalAdmin(true);
return true;
}
}
// Old global admin can pass resource 'console/':
if (permission.getResource().getName().startsWith(AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX)) {
return false;
}
// For other roles, use a pattern match to decide if pass or not.
for (RoleInfo roleInfo : roleInfoList) {
List<PermissionInfo> permissionInfoList = getPermissions(roleInfo.getRole());
if (CollectionUtils.isEmpty(permissionInfoList)) {
continue;
}
for (PermissionInfo permissionInfo : permissionInfoList) {
String permissionResource = permissionInfo.getResource().replaceAll("\\*", ".*");
String permissionAction = permissionInfo.getAction();
if (permissionAction.contains(permission.getAction()) && Pattern.matches(permissionResource,
joinResource(permission.getResource()))) {
return true;
}
}
}
return false;
} | @Test
void hasPermission() {
Permission permission = new Permission();
permission.setAction("rw");
permission.setResource(Resource.EMPTY_RESOURCE);
NacosUser nacosUser = new NacosUser();
nacosUser.setUserName("nacos");
boolean res = nacosRoleService.hasPermission(nacosUser, permission);
assertFalse(res);
Permission permission2 = new Permission();
permission2.setAction("rw");
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
permission2.setResource(resource);
boolean res2 = nacosRoleService.hasPermission(nacosUser, permission2);
assertTrue(res2);
} |
public static Map<String, ResourceModel> buildResourceModels(final Set<Class<?>> restliAnnotatedClasses)
{
Map<String, ResourceModel> rootResourceModels = new HashMap<>();
Map<Class<?>, ResourceModel> resourceModels = new HashMap<>();
for (Class<?> annotatedClass : restliAnnotatedClasses)
{
processResourceInOrder(annotatedClass, resourceModels, rootResourceModels);
}
return rootResourceModels;
} | @Test(dataProvider = "finderSupportedResourceTypeData")
public void testFinderSupportedResourceType(Class<?> resourceClass)
{
try
{
RestLiApiBuilder.buildResourceModels(Collections.singleton(resourceClass));
}
catch (Exception exception)
{
Assert.fail(String.format("Unexpected exception: class: %s, message: \"%s\"",
resourceClass.getSimpleName(), exception.getMessage()));
}
} |
@Override
public Collection<DatabasePacket> execute() throws SQLException {
new BackendTransactionManager(connectionSession.getDatabaseConnectionManager()).rollback();
connectionSession.setAutoCommit(true);
connectionSession.setDefaultIsolationLevel(null);
connectionSession.setIsolationLevel(null);
connectionSession.getServerPreparedStatementRegistry().clear();
return Collections.singleton(new MySQLOKPacket(ServerStatusFlagCalculator.calculateFor(connectionSession)));
} | @Test
void assertExecute() throws SQLException {
ConnectionSession connectionSession = mock(ConnectionSession.class);
ProxyDatabaseConnectionManager databaseConnectionManager = mock(ProxyDatabaseConnectionManager.class);
when(connectionSession.getDatabaseConnectionManager()).thenReturn(databaseConnectionManager);
when(connectionSession.getTransactionStatus()).thenReturn(new TransactionStatus());
when(connectionSession.getServerPreparedStatementRegistry()).thenReturn(new ServerPreparedStatementRegistry());
int statementId = 1;
connectionSession.getServerPreparedStatementRegistry().addPreparedStatement(statementId, new MySQLServerPreparedStatement("", null, new HintValueContext(), Collections.emptyList()));
Collection<DatabasePacket> actual = new MySQLComResetConnectionExecutor(connectionSession).execute();
assertThat(actual.size(), is(1));
assertThat(actual.iterator().next(), instanceOf(MySQLOKPacket.class));
verify(connectionSession).setAutoCommit(true);
verify(connectionSession).setDefaultIsolationLevel(null);
verify(connectionSession).setIsolationLevel(null);
assertNull(connectionSession.getServerPreparedStatementRegistry().getPreparedStatement(statementId));
} |
public void onLeadershipChange(Set<Partition> partitionsBecomeLeader,
Set<Partition> partitionsBecomeFollower,
Map<String, Uuid> topicIds) {
LOGGER.debug("Received leadership changes for leaders: {} and followers: {}", partitionsBecomeLeader, partitionsBecomeFollower);
if (rlmConfig.isRemoteStorageSystemEnabled() && !isRemoteLogManagerConfigured()) {
throw new KafkaException("RemoteLogManager is not configured when remote storage system is enabled");
}
Map<TopicIdPartition, Boolean> leaderPartitions = filterPartitions(partitionsBecomeLeader)
.collect(Collectors.toMap(p -> new TopicIdPartition(topicIds.get(p.topic()), p.topicPartition()),
p -> p.log().exists(log -> log.config().remoteLogCopyDisable())));
Map<TopicIdPartition, Boolean> followerPartitions = filterPartitions(partitionsBecomeFollower)
.collect(Collectors.toMap(p -> new TopicIdPartition(topicIds.get(p.topic()), p.topicPartition()),
p -> p.log().exists(log -> log.config().remoteLogCopyDisable())));
if (!leaderPartitions.isEmpty() || !followerPartitions.isEmpty()) {
LOGGER.debug("Effective topic partitions after filtering compact and internal topics, leaders: {} and followers: {}",
leaderPartitions, followerPartitions);
leaderPartitions.forEach((tp, __) -> cacheTopicPartitionIds(tp));
followerPartitions.forEach((tp, __) -> cacheTopicPartitionIds(tp));
remoteLogMetadataManager.onPartitionLeadershipChanges(leaderPartitions.keySet(), followerPartitions.keySet());
followerPartitions.forEach((tp, __) -> doHandleFollowerPartition(tp));
// If this node was the previous leader for the partition, then the RLMTask might be running in the
// background thread and might emit metrics. So, removing the metrics after marking this node as follower.
followerPartitions.forEach((tp, __) -> removeRemoteTopicPartitionMetrics(tp));
leaderPartitions.forEach(this::doHandleLeaderPartition);
}
} | @Test
void testLeadershipChangesWithoutRemoteLogManagerConfiguring() {
assertThrows(KafkaException.class, () -> {
remoteLogManager.onLeadershipChange(
Collections.singleton(mockPartition(leaderTopicIdPartition)), Collections.singleton(mockPartition(followerTopicIdPartition)), topicIds);
}, "RemoteLogManager is not configured when remote storage system is enabled");
} |
@PostMapping(
path = "/api/-/namespace/create",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
@Operation(summary = "Create a namespace")
@ApiResponses({
@ApiResponse(
responseCode = "201",
description = "Successfully created the namespace",
content = @Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
examples = @ExampleObject(value = "{ \"success\": \"Created namespace foobar\" }")
),
headers = @Header(
name = "Location",
description = "The URL of the namespace metadata",
schema = @Schema(type = "string")
)
),
@ApiResponse(
responseCode = "400",
description = "The namespace could not be created",
content = @Content(
mediaType = MediaType.APPLICATION_JSON_VALUE,
examples = @ExampleObject(value = "{ \"error\": \"Invalid access token.\" }")
)
),
@ApiResponse(
responseCode = "429",
description = "A client has sent too many requests in a given amount of time",
content = @Content(),
headers = {
@Header(
name = "X-Rate-Limit-Retry-After-Seconds",
description = "Number of seconds to wait after receiving a 429 response",
schema = @Schema(type = "integer", format = "int32")
),
@Header(
name = "X-Rate-Limit-Remaining",
description = "Remaining number of requests left",
schema = @Schema(type = "integer", format = "int32")
)
}
)
})
public ResponseEntity<ResultJson> createNamespace(
@RequestBody @Parameter(description = "Describes the namespace to create")
NamespaceJson namespace,
@RequestParam @Parameter(description = "A personal access token")
String token
) {
if (namespace == null) {
return ResponseEntity.ok(ResultJson.error("No JSON input."));
}
if (StringUtils.isEmpty(namespace.name)) {
return ResponseEntity.ok(ResultJson.error("Missing required property 'name'."));
}
try {
var json = local.createNamespace(namespace, token);
var serverUrl = UrlUtil.getBaseUrl();
var url = UrlUtil.createApiUrl(serverUrl, "api", namespace.name);
return ResponseEntity.status(HttpStatus.CREATED)
.location(URI.create(url))
.body(json);
} catch (ErrorResultException exc) {
return exc.toResponseEntity();
}
} | @Test
public void testCreateNamespace() throws Exception {
mockAccessToken();
mockMvc.perform(post("/api/-/namespace/create?token={token}", "my_token")
.contentType(MediaType.APPLICATION_JSON)
.content(namespaceJson(n -> { n.name = "foobar"; })))
.andExpect(status().isCreated())
.andExpect(redirectedUrl("http://localhost/api/foobar"))
.andExpect(content().json(successJson("Created namespace foobar")));
} |
@InvokeOnHeader(Web3jConstants.SHH_NEW_FILTER)
void shhNewFilter(Message message) throws IOException {
String data = message.getHeader(Web3jConstants.DATA, configuration::getData, String.class);
List<String> topics = message.getHeader(Web3jConstants.TOPICS, configuration::getTopics, List.class);
org.web3j.protocol.core.methods.request.ShhFilter shhFilter = Web3jEndpoint.buildShhFilter(data, topics);
Request<?, ShhNewFilter> request = web3j.shhNewFilter(shhFilter);
setRequestId(message, request);
ShhNewFilter response = request.send();
boolean hasError = checkForError(message, response);
if (!hasError) {
message.setBody(response.getFilterId());
}
} | @Test
public void shhNewFilterTest() throws Exception {
ShhNewFilter response = Mockito.mock(ShhNewFilter.class);
Mockito.when(mockWeb3j.shhNewFilter(any())).thenReturn(request);
Mockito.when(request.send()).thenReturn(response);
Mockito.when(response.getFilterId()).thenReturn(BigInteger.ONE);
Exchange exchange = createExchangeWithBodyAndHeader(null, OPERATION, Web3jConstants.SHH_NEW_FILTER);
template.send(exchange);
BigInteger body = exchange.getIn().getBody(BigInteger.class);
assertEquals(BigInteger.ONE, body);
} |
public static void updateLong(Checksum checksum, long input) {
checksum.update((byte) (input >> 56));
checksum.update((byte) (input >> 48));
checksum.update((byte) (input >> 40));
checksum.update((byte) (input >> 32));
checksum.update((byte) (input >> 24));
checksum.update((byte) (input >> 16));
checksum.update((byte) (input >> 8));
checksum.update((byte) input /* >> 0 */);
} | @Test
public void testUpdateLong() {
final long value = Integer.MAX_VALUE + 1;
final ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(value);
Checksum crc1 = Crc32C.create();
Checksum crc2 = Crc32C.create();
Checksums.updateLong(crc1, value);
crc2.update(buffer.array(), buffer.arrayOffset(), 8);
assertEquals(crc1.getValue(), crc2.getValue(), "Crc values should be the same");
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStartBounds,
final Range<Instant> windowEndBounds,
final Optional<Position> position
) {
try {
final Instant lower = calculateLowerBound(windowStartBounds, windowEndBounds);
final Instant upper = calculateUpperBound(windowStartBounds, windowEndBounds);
final WindowKeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query =
WindowKeyQuery.withKeyAndWindowStartRange(key, lower, upper);
StateQueryRequest<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> request =
inStore(stateStore.getStateStoreName()).withQuery(query);
if (position.isPresent()) {
request = request.withPositionBound(PositionBound.at(position.get()));
}
final KafkaStreams streams = stateStore.getKafkaStreams();
final StateQueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> result =
streams.query(request);
final QueryResult<WindowStoreIterator<ValueAndTimestamp<GenericRow>>> queryResult =
result.getPartitionResults().get(partition);
if (queryResult.isFailure()) {
throw failedQueryException(queryResult);
}
if (queryResult.getResult() == null) {
return KsMaterializedQueryResult.rowIteratorWithPosition(
Collections.emptyIterator(), queryResult.getPosition());
}
try (WindowStoreIterator<ValueAndTimestamp<GenericRow>> it
= queryResult.getResult()) {
final Builder<WindowedRow> builder = ImmutableList.builder();
while (it.hasNext()) {
final KeyValue<Long, ValueAndTimestamp<GenericRow>> next = it.next();
final Instant windowStart = Instant.ofEpochMilli(next.key);
if (!windowStartBounds.contains(windowStart)) {
continue;
}
final Instant windowEnd = windowStart.plus(windowSize);
if (!windowEndBounds.contains(windowEnd)) {
continue;
}
final TimeWindow window =
new TimeWindow(windowStart.toEpochMilli(), windowEnd.toEpochMilli());
final WindowedRow row = WindowedRow.of(
stateStore.schema(),
new Windowed<>(key, window),
next.value.value(),
next.value.timestamp()
);
builder.add(row);
}
return KsMaterializedQueryResult.rowIteratorWithPosition(
builder.build().iterator(), queryResult.getPosition());
}
} catch (final NotUpToBoundException | MaterializationException e) {
throw e;
} catch (final Exception e) {
throw new MaterializationException("Failed to get value from materialized table", e);
}
} | @Test
@SuppressWarnings("unchecked")
public void shouldThrowIfQueryFails() {
// Given:
final StateQueryResult<?> partitionResult = new StateQueryResult<>();
partitionResult.addResult(PARTITION, QueryResult.forFailure(FailureReason.STORE_EXCEPTION, "Boom"));
when(kafkaStreams.query(any(StateQueryRequest.class))).thenReturn(partitionResult);
// When:
final Exception e = assertThrows(
MaterializationException.class,
() -> table.get(A_KEY, PARTITION, WINDOW_START_BOUNDS, WINDOW_END_BOUNDS)
);
// Then:
assertThat(e.getMessage(), containsString(
"Failed to get value from materialized table"));
assertThat(e, (instanceOf(MaterializationException.class)));
} |
@Override
protected TableRecords getUndoRows() {
return sqlUndoLog.getBeforeImage();
} | @Test
public void getUndoRows() {
Assertions.assertEquals(executor.getUndoRows(), executor.getSqlUndoLog().getBeforeImage());
} |
public DataMap toDataMap()
{
DataMap dataMap = new DataMap(_keys.size());
for (Map.Entry<String, ValueAndTypeInfoPair> keyParts : _keys.entrySet())
{
String key = keyParts.getKey();
ValueAndTypeInfoPair valueAndTypeInfoPair = keyParts.getValue();
Object value = valueAndTypeInfoPair.getValue();
TypeInfo typeInfo = valueAndTypeInfoPair.getTypeInfo();
DataSchema schema = typeInfo.getDeclared().getSchema();
Object coercedInput = coerceValueForDataMap(value, schema);
dataMap.put(key, coercedInput);
}
return dataMap;
} | @Test
public void testToDataMap()
{
CompoundKey compoundKey = new CompoundKey();
compoundKey.append("foo", "foo-value");
compoundKey.append("bar", 1);
compoundKey.append("baz", 7L);
DataMap dataMap = compoundKey.toDataMap();
Assert.assertEquals(dataMap.get("foo"), compoundKey.getPart("foo"));
Assert.assertEquals(dataMap.get("bar"), compoundKey.getPart("bar"));
Assert.assertEquals(dataMap.get("baz"), compoundKey.getPart("baz"));
} |
@Override
public boolean test(Pickle pickle) {
URI picklePath = pickle.getUri();
if (!lineFilters.containsKey(picklePath)) {
return true;
}
for (Integer line : lineFilters.get(picklePath)) {
if (Objects.equals(line, pickle.getLocation().getLine())
|| Objects.equals(line, pickle.getScenarioLocation().getLine())
|| pickle.getExamplesLocation().map(Location::getLine).map(line::equals).orElse(false)
|| pickle.getRuleLocation().map(Location::getLine).map(line::equals).orElse(false)
|| pickle.getFeatureLocation().map(Location::getLine).map(line::equals).orElse(false)) {
return true;
}
}
return false;
} | @Test
void matches_at_least_one_line() {
LinePredicate predicate = new LinePredicate(singletonMap(
featurePath,
asList(3, 4)));
assertTrue(predicate.test(firstPickle));
assertTrue(predicate.test(secondPickle));
assertTrue(predicate.test(thirdPickle));
assertTrue(predicate.test(fourthPickle));
} |
public static Optional<Object> doLogin(final String username, final String password, final String url) throws IOException {
Map<String, Object> loginMap = new HashMap<>(2);
loginMap.put(Constants.LOGIN_NAME, username);
loginMap.put(Constants.PASS_WORD, password);
String result = OkHttpTools.getInstance().get(url, loginMap);
Map<String, Object> resultMap = GsonUtils.getInstance().convertToMap(result);
if (!String.valueOf(CommonErrorCode.SUCCESSFUL).equals(String.valueOf(resultMap.get(Constants.ADMIN_RESULT_CODE)))) {
return Optional.empty();
}
String tokenJson = GsonUtils.getInstance().toJson(resultMap.get(Constants.ADMIN_RESULT_DATA));
LOGGER.info("login success: {} ", tokenJson);
Map<String, Object> tokenMap = GsonUtils.getInstance().convertToMap(tokenJson);
return Optional.ofNullable(tokenMap.get(Constants.ADMIN_RESULT_TOKEN));
} | @Test
public void testDoLoginError() throws IOException {
final String userName = "userName";
final String password = "password";
Map<String, Object> loginMap = new HashMap<>(2);
loginMap.put(Constants.LOGIN_NAME, userName);
loginMap.put(Constants.PASS_WORD, password);
when(okHttpTools.get(url, loginMap)).thenReturn("{\"code\":300}");
try (MockedStatic<OkHttpTools> okHttpToolsMockedStatic = mockStatic(OkHttpTools.class)) {
okHttpToolsMockedStatic.when(OkHttpTools::getInstance).thenReturn(okHttpTools);
Optional<Object> objectOptional = RegisterUtils.doLogin(userName, password, url);
Assertions.assertFalse(objectOptional.isPresent());
}
} |
@Override
public List<DataLayoutStrategy> generate() {
return Collections.singletonList(generateCompactionStrategy());
} | @Test
void testStrategySanityCheck() throws Exception {
final String testTable = "db.test_table_sanity_check";
try (SparkSession spark = getSparkSession()) {
spark.sql("USE openhouse");
spark.sql(
String.format(
"create table %s (id int, data string, ts timestamp) partitioned by (days(ts))",
testTable));
// produce 2 partitions
for (int i = 0; i < 3; ++i) {
spark.sql(
String.format(
"insert into %s values (0, 'data', cast('2024-07-15 00:1%d:34' as timestamp))",
testTable, i));
}
for (int i = 0; i < 3; ++i) {
spark.sql(
String.format(
"insert into %s values (0, 'data', cast('2024-07-16 00:1%d:34' as timestamp))",
testTable, i));
}
TableFileStats tableFileStats =
TableFileStats.builder().tableName(testTable).spark(spark).build();
TablePartitionStats tablePartitionStats =
TablePartitionStats.builder().tableName(testTable).spark(spark).build();
OpenHouseDataLayoutStrategyGenerator strategyGenerator =
OpenHouseDataLayoutStrategyGenerator.builder()
.tableFileStats(tableFileStats)
.tablePartitionStats(tablePartitionStats)
.build();
List<DataLayoutStrategy> strategies = strategyGenerator.generate();
Assertions.assertEquals(1, strategies.size());
DataLayoutStrategy strategy = strategies.get(0);
// few groups, expect 1 commit
Assertions.assertEquals(1, strategy.getConfig().getPartialProgressMaxCommits());
Assertions.assertTrue(strategy.getConfig().isPartialProgressEnabled());
Assertions.assertTrue(
strategy.getGain() == 5, "Gain for 6 files compaction in 2 partitions should be 5");
Assertions.assertTrue(
strategy.getCost() < 1.0, "Cost for 6 files compaction should be negligible");
Assertions.assertTrue(
strategy.getScore() < 10.0, "Score for 6 files compaction should be negligible");
}
} |
@Override
public <T> void storeObject(
String accountName,
ObjectType objectType,
String objectKey,
T obj,
String filename,
boolean isAnUpdate) {
if (objectType.equals(ObjectType.CANARY_RESULT_ARCHIVE)) {
var draftRecord = new SqlCanaryArchive();
draftRecord.setId(objectKey);
draftRecord.setContent(mapToJson(obj, objectType));
draftRecord.setCreatedAt(Instant.now());
draftRecord.setUpdatedAt(Instant.now());
sqlCanaryArchiveRepo.save(draftRecord);
return;
}
if (objectType.equals(ObjectType.CANARY_CONFIG)) {
var draftRecord = new SqlCanaryConfig();
draftRecord.setId(objectKey);
draftRecord.setContent(mapToJson(obj, objectType));
draftRecord.setCreatedAt(Instant.now());
draftRecord.setUpdatedAt(Instant.now());
sqlCanaryConfigRepo.save(draftRecord);
return;
}
if (objectType.equals(ObjectType.METRIC_SET_PAIR_LIST)) {
var draftRecord = new SqlMetricSetPairs();
draftRecord.setId(objectKey);
draftRecord.setContent(mapToJson(obj, objectType));
draftRecord.setCreatedAt(Instant.now());
draftRecord.setUpdatedAt(Instant.now());
sqlMetricSetPairsRepo.save(draftRecord);
return;
}
if (objectType.equals(ObjectType.METRIC_SET_LIST)) {
var draftRecord = new SqlMetricSets();
draftRecord.setId(objectKey);
draftRecord.setContent(mapToJson(obj, objectType));
draftRecord.setCreatedAt(Instant.now());
draftRecord.setUpdatedAt(Instant.now());
sqlMetricSetsRepo.save(draftRecord);
return;
}
throw new IllegalArgumentException("Unsupported object type: " + objectType);
} | @Test
public void testStoreObjectWhenCanaryArchive() {
var testAccountName = UUID.randomUUID().toString();
var testObjectType = ObjectType.CANARY_RESULT_ARCHIVE;
var testObjectKey = UUID.randomUUID().toString();
var testCanaryExecutionStatusResponse = createTestCanaryExecutionStatusResponse();
sqlStorageService.storeObject(
testAccountName, testObjectType, testObjectKey, testCanaryExecutionStatusResponse);
verify(sqlCanaryArchiveRepo).save(any(SqlCanaryArchive.class));
} |
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void invokeAny_withTimeout() throws Exception {
newManagedExecutorService().invokeAny(Collections.singleton(() -> null), 1, TimeUnit.SECONDS);
} |
public static SecretKey generateKey(String algorithm) {
return generateKey(algorithm, -1);
} | @Test
public void generateSm4KeyTest(){
// https://github.com/dromara/hutool/issues/2150
assertEquals(16, KeyUtil.generateKey("sm4").getEncoded().length);
assertEquals(32, KeyUtil.generateKey("sm4", 256).getEncoded().length);
} |
public static boolean shouldLoadInIsolation(String name) {
return !(EXCLUDE.matcher(name).matches() && !INCLUDE.matcher(name).matches());
} | @Test
public void testClientConfigProvider() {
assertFalse(PluginUtils.shouldLoadInIsolation(
"org.apache.kafka.common.config.provider.ConfigProvider")
);
assertTrue(PluginUtils.shouldLoadInIsolation(
"org.apache.kafka.common.config.provider.FileConfigProvider")
);
assertTrue(PluginUtils.shouldLoadInIsolation(
"org.apache.kafka.common.config.provider.FutureConfigProvider")
);
} |
@Override
public void doAdmissionChecks(Function.FunctionDetails functionDetails){
final String overriddenJobName = getOverriddenName(functionDetails);
KubernetesRuntime.doChecks(functionDetails, overriddenJobName);
validateMinResourcesRequired(functionDetails);
validateMaxResourcesRequired(functionDetails);
validateResourcesGranularityAndProportion(functionDetails);
secretsProviderConfigurator.doAdmissionChecks(appsClient, coreClient,
getOverriddenNamespace(functionDetails), overriddenJobName, functionDetails);
} | @Test
public void testAdmissionChecks() throws Exception {
factory = createKubernetesRuntimeFactory(null, null, null, null, false);
FunctionDetails functionDetails = createFunctionDetails();
factory.doAdmissionChecks(functionDetails);
} |
public void processOnce() throws IOException {
// set status of query to OK.
ctx.getState().reset();
executor = null;
// reset sequence id of MySQL protocol
final MysqlChannel channel = ctx.getMysqlChannel();
channel.setSequenceId(0);
// read packet from channel
try {
packetBuf = channel.fetchOnePacket();
if (packetBuf == null) {
throw new RpcException(ctx.getRemoteIP(), "Error happened when receiving packet.");
}
} catch (AsynchronousCloseException e) {
// when this happened, timeout checker close this channel
// killed flag in ctx has been already set, just return
return;
}
// dispatch
dispatch();
// finalize
finalizeCommand();
ctx.setCommand(MysqlCommand.COM_SLEEP);
} | @Test
public void testQueryFail(@Mocked StmtExecutor executor) throws Exception {
ConnectContext ctx = initMockContext(mockChannel(queryPacket), GlobalStateMgr.getCurrentState());
ConnectProcessor processor = new ConnectProcessor(ctx);
// Mock statement executor
new Expectations() {
{
executor.execute();
minTimes = 0;
result = new IOException("Fail");
executor.getQueryStatisticsForAuditLog();
minTimes = 0;
result = statistics;
}
};
processor.processOnce();
Assert.assertEquals(MysqlCommand.COM_QUERY, myContext.getCommand());
} |
public MapWithProtoValuesFluentAssertion<M> ignoringRepeatedFieldOrderForValues() {
return usingConfig(config.ignoringRepeatedFieldOrder());
} | @Test
public void testCompareMultipleMessageTypes() {
// Don't run this test twice.
if (!testIsRunOnce()) {
return;
}
expectThat(
ImmutableMap.of(
2,
TestMessage2.newBuilder().addRString("foo").addRString("bar").build(),
3,
TestMessage3.newBuilder().addRString("baz").addRString("qux").build()))
.ignoringRepeatedFieldOrderForValues()
.containsExactly(
3, TestMessage3.newBuilder().addRString("qux").addRString("baz").build(),
2, TestMessage2.newBuilder().addRString("bar").addRString("foo").build());
} |
@Override
public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) {
Set<RuleDescriptionSectionDto> advancedSections = rule.ruleDescriptionSections().stream()
.map(this::toRuleDescriptionSectionDto)
.collect(Collectors.toSet());
return addLegacySectionToAdvancedSections(advancedSections, rule);
} | @Test
public void generateSections_whenContextSpecificSectionsAndNonContextSpecificSection_createsTwoSectionsAndDefault() {
when(rule.ruleDescriptionSections()).thenReturn(List.of(SECTION_1, SECTION_3_WITH_CTX_2));
Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = generator.generateSections(rule);
assertThat(ruleDescriptionSectionDtos)
.usingRecursiveFieldByFieldElementComparator()
.containsExactlyInAnyOrder(EXPECTED_SECTION_1, EXPECTED_SECTION_3_WITH_CTX_2, LEGACY_SECTION);
} |
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
RequestDispatcher requestDispatcher = req.getRequestDispatcher(destination);
ClientPropertiesBean reqParams = new ClientPropertiesBean(req);
req.setAttribute("properties", reqParams);
requestDispatcher.forward(req, resp);
} catch (Exception e) {
LOGGER.error("Exception occurred GET request processing ", e);
}
} | @Test
void testDoGet() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
RequestDispatcher mockDispatcher = Mockito.mock(RequestDispatcher.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mockResp.getWriter()).thenReturn(printWriter);
when(mockReq.getRequestDispatcher(destination)).thenReturn(mockDispatcher);
AppServlet curServlet = new AppServlet();
curServlet.doGet(mockReq, mockResp);
verify(mockReq, times(1)).getRequestDispatcher(destination);
verify(mockDispatcher).forward(mockReq, mockResp);
} |
public static Versions parse(String input, Versions defaultVersions) {
if (input == null) {
return defaultVersions;
}
String trimmedInput = input.trim();
if (trimmedInput.isEmpty()) {
return defaultVersions;
}
if (trimmedInput.equals(NONE_STRING)) {
return NONE;
}
if (trimmedInput.endsWith("+")) {
return new Versions(Short.parseShort(
trimmedInput.substring(0, trimmedInput.length() - 1)),
Short.MAX_VALUE);
} else {
int dashIndex = trimmedInput.indexOf("-");
if (dashIndex < 0) {
short version = Short.parseShort(trimmedInput);
return new Versions(version, version);
}
return new Versions(
Short.parseShort(trimmedInput.substring(0, dashIndex)),
Short.parseShort(trimmedInput.substring(dashIndex + 1)));
}
} | @Test
public void testVersionsParse() {
assertEquals(Versions.NONE, Versions.parse(null, Versions.NONE));
assertEquals(Versions.ALL, Versions.parse(" ", Versions.ALL));
assertEquals(Versions.ALL, Versions.parse("", Versions.ALL));
assertEquals(newVersions(4, 5), Versions.parse(" 4-5 ", null));
} |
static void configureEncryption(
S3FileIOProperties s3FileIOProperties, PutObjectRequest.Builder requestBuilder) {
configureEncryption(
s3FileIOProperties,
requestBuilder::serverSideEncryption,
requestBuilder::ssekmsKeyId,
requestBuilder::sseCustomerAlgorithm,
requestBuilder::sseCustomerKey,
requestBuilder::sseCustomerKeyMD5);
} | @Test
public void testConfigureServerSideKmsEncryption() {
S3FileIOProperties s3FileIOProperties = new S3FileIOProperties();
s3FileIOProperties.setSseType(S3FileIOProperties.SSE_TYPE_KMS);
s3FileIOProperties.setSseKey("key");
S3RequestUtil.configureEncryption(
s3FileIOProperties,
this::setServerSideEncryption,
this::setKmsKeyId,
this::setCustomAlgorithm,
this::setCustomKey,
this::setCustomMd5);
assertThat(serverSideEncryption).isEqualTo(ServerSideEncryption.AWS_KMS);
assertThat(kmsKeyId).isEqualTo("key");
assertThat(customAlgorithm).isNull();
assertThat(customKey).isNull();
assertThat(customMd5).isNull();
} |
@Override
public void onTaskFinished(TaskAttachment attachment) {
if (attachment instanceof BrokerPendingTaskAttachment) {
onPendingTaskFinished((BrokerPendingTaskAttachment) attachment);
} else if (attachment instanceof BrokerLoadingTaskAttachment) {
onLoadingTaskFinished((BrokerLoadingTaskAttachment) attachment);
}
} | @Test
public void testCommitRateExceeded(@Injectable BrokerLoadingTaskAttachment attachment1,
@Injectable LoadTask loadTask1,
@Mocked GlobalStateMgr globalStateMgr,
@Injectable Database database,
@Mocked GlobalTransactionMgr transactionMgr) throws UserException {
BrokerLoadJob brokerLoadJob = new BrokerLoadJob();
Deencapsulation.setField(brokerLoadJob, "state", JobState.LOADING);
Map<Long, LoadTask> idToTasks = Maps.newHashMap();
idToTasks.put(1L, loadTask1);
Deencapsulation.setField(brokerLoadJob, "idToTasks", idToTasks);
new Expectations() {
{
attachment1.getCounter(BrokerLoadJob.DPP_NORMAL_ALL);
minTimes = 0;
result = 10;
attachment1.getCounter(BrokerLoadJob.DPP_ABNORMAL_ALL);
minTimes = 0;
result = 0;
attachment1.getTaskId();
minTimes = 0;
result = 1L;
globalStateMgr.getDb(anyLong);
minTimes = 0;
result = database;
globalStateMgr.getCurrentState().getGlobalTransactionMgr();
result = transactionMgr;
transactionMgr.commitTransaction(anyLong, anyLong, (List<TabletCommitInfo>) any,
(List<TabletFailInfo>) any, (TxnCommitAttachment) any);
result = new CommitRateExceededException(100, System.currentTimeMillis() + 10);
result = null;
}
};
brokerLoadJob.onTaskFinished(attachment1);
Set<Long> finishedTaskIds = Deencapsulation.getField(brokerLoadJob, "finishedTaskIds");
Assert.assertEquals(1, finishedTaskIds.size());
EtlStatus loadingStatus = Deencapsulation.getField(brokerLoadJob, "loadingStatus");
Assert.assertEquals("10", loadingStatus.getCounters().get(BrokerLoadJob.DPP_NORMAL_ALL));
Assert.assertEquals("0", loadingStatus.getCounters().get(BrokerLoadJob.DPP_ABNORMAL_ALL));
int progress = Deencapsulation.getField(brokerLoadJob, "progress");
Assert.assertEquals(99, progress);
} |
public static String getUserRole(String token) {
return (String) getTokenBody(token).get(ROLE_CLAIMS);
} | @Test
public void getUserRole() {
String userRole = JwtTokenUtil.getUserRole(token);
Assert.isTrue(role.equals(userRole));
} |
@Override
public boolean addWord(String word, int frequency) {
synchronized (mResourceMonitor) {
if (isClosed()) {
Logger.d(
TAG,
"Dictionary (type "
+ this.getClass().getName()
+ ") "
+ this.getDictionaryName()
+ " is closed! Can not add word.");
return false;
}
// Safeguard against adding long words. Can cause stack overflow.
if (word.length() >= getMaxWordLength()) return false;
Logger.i(
TAG,
"Adding word '"
+ word
+ "' to dictionary (in "
+ getClass().getSimpleName()
+ ") with frequency "
+ frequency);
// first deleting the word, so it wont conflict in the adding (_ID is unique).
deleteWord(word);
// add word to in-memory structure
addWordRec(mRoots, word, 0, frequency);
// add word to storage
addWordToStorage(word, frequency);
}
return true;
} | @Test
public void testAddWord() throws Exception {
mDictionaryUnderTest.loadDictionary();
assertTrue(mDictionaryUnderTest.addWord("new", 23));
Assert.assertEquals("new", mDictionaryUnderTest.wordRequestedToAddedToStorage);
Assert.assertEquals(23, mDictionaryUnderTest.wordFrequencyRequestedToAddedToStorage);
assertTrue(mDictionaryUnderTest.isValidWord("new"));
Assert.assertEquals(mDictionaryUnderTest.getWordFrequency("new"), 23);
// checking validity of the internal structure
assetNodeArrayIsValid(mDictionaryUnderTest.getRoot());
assertTrue(mDictionaryUnderTest.addWord("new", 34));
Assert.assertEquals("new", mDictionaryUnderTest.wordRequestedToAddedToStorage);
Assert.assertEquals(34, mDictionaryUnderTest.wordFrequencyRequestedToAddedToStorage);
assertTrue(mDictionaryUnderTest.isValidWord("new"));
Assert.assertEquals(34, mDictionaryUnderTest.getWordFrequency("new"));
// checking validity of the internal structure
assetNodeArrayIsValid(mDictionaryUnderTest.getRoot());
assertTrue(mDictionaryUnderTest.addWord("newa", 45));
assertTrue(mDictionaryUnderTest.isValidWord("newa"));
Assert.assertEquals(34, mDictionaryUnderTest.getWordFrequency("new"));
Assert.assertEquals(45, mDictionaryUnderTest.getWordFrequency("newa"));
// checking validity of the internal structure
assetNodeArrayIsValid(mDictionaryUnderTest.getRoot());
assertTrue(mDictionaryUnderTest.addWord("nea", 47));
Assert.assertEquals("nea", mDictionaryUnderTest.wordRequestedToAddedToStorage);
Assert.assertEquals(47, mDictionaryUnderTest.wordFrequencyRequestedToAddedToStorage);
assertTrue(mDictionaryUnderTest.isValidWord("nea"));
Assert.assertEquals(34, mDictionaryUnderTest.getWordFrequency("new"));
Assert.assertEquals(45, mDictionaryUnderTest.getWordFrequency("newa"));
Assert.assertEquals(47, mDictionaryUnderTest.getWordFrequency("nea"));
// checking validity of the internal structure
assetNodeArrayIsValid(mDictionaryUnderTest.getRoot());
assertTrue(mDictionaryUnderTest.addWord("neabb", 50));
Assert.assertEquals("neabb", mDictionaryUnderTest.wordRequestedToAddedToStorage);
Assert.assertEquals(50, mDictionaryUnderTest.wordFrequencyRequestedToAddedToStorage);
assertTrue(mDictionaryUnderTest.isValidWord("neabb"));
Assert.assertFalse(mDictionaryUnderTest.isValidWord("neab"));
Assert.assertEquals(34, mDictionaryUnderTest.getWordFrequency("new"));
Assert.assertEquals(45, mDictionaryUnderTest.getWordFrequency("newa"));
Assert.assertEquals(47, mDictionaryUnderTest.getWordFrequency("nea"));
Assert.assertEquals(50, mDictionaryUnderTest.getWordFrequency("neabb"));
Assert.assertEquals(0, mDictionaryUnderTest.getWordFrequency("neab"));
// checking validity of the internal structure
assetNodeArrayIsValid(mDictionaryUnderTest.getRoot());
} |
public static String encodingParams(Map<String, String> params, String encoding)
throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
if (null == params || params.isEmpty()) {
return null;
}
for (Map.Entry<String, String> entry : params.entrySet()) {
if (StringUtils.isEmpty(entry.getValue())) {
continue;
}
sb.append(entry.getKey()).append('=');
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append('&');
}
return sb.toString();
} | @Test
void testEncodingParamsMap() throws UnsupportedEncodingException {
Map<String, String> params = new LinkedHashMap<>();
params.put("a", "");
params.put("b", "x");
params.put("uriChar", "=");
params.put("chinese", "测试");
assertEquals("b=x&uriChar=%3D&chinese=%E6%B5%8B%E8%AF%95&", HttpUtils.encodingParams(params, "UTF-8"));
} |
public static ClusterMembership from(String stringValue, Version vespaVersion, Optional<DockerImage> dockerImageRepo) {
return from(stringValue, vespaVersion, dockerImageRepo, ZoneEndpoint.defaultEndpoint);
} | @Test
void testServiceInstanceWithGroupAndRetireFromString() {
assertContentServiceWithGroupAndRetire(ClusterMembership.from("content/id1/4/37/retired/stateful", Vtag.currentVersion, Optional.empty()));
} |
@VisibleForTesting
public static Domain getDomain(Type type, long rowCount, ColumnStatistics columnStatistics)
{
if (rowCount == 0) {
return Domain.none(type);
}
if (columnStatistics == null) {
return Domain.all(type);
}
if (columnStatistics.hasNumberOfValues() && columnStatistics.getNumberOfValues() == 0) {
return Domain.onlyNull(type);
}
boolean hasNullValue = columnStatistics.getNumberOfValues() != rowCount;
if (type.getJavaType() == boolean.class && columnStatistics.getBooleanStatistics() != null) {
BooleanStatistics booleanStatistics = columnStatistics.getBooleanStatistics();
boolean hasTrueValues = (booleanStatistics.getTrueValueCount() != 0);
boolean hasFalseValues = (columnStatistics.getNumberOfValues() != booleanStatistics.getTrueValueCount());
if (hasTrueValues && hasFalseValues) {
return Domain.all(BOOLEAN);
}
if (hasTrueValues) {
return Domain.create(ValueSet.of(BOOLEAN, true), hasNullValue);
}
if (hasFalseValues) {
return Domain.create(ValueSet.of(BOOLEAN, false), hasNullValue);
}
}
else if (isShortDecimal(type) && columnStatistics.getDecimalStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getDecimalStatistics(), value -> rescale(value, (DecimalType) type).unscaledValue().longValue());
}
else if (isLongDecimal(type) && columnStatistics.getDecimalStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getDecimalStatistics(), value -> encodeUnscaledValue(rescale(value, (DecimalType) type).unscaledValue()));
}
else if (isCharType(type) && columnStatistics.getStringStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getStringStatistics(), value -> truncateToLengthAndTrimSpaces(value, type));
}
else if (isVarcharType(type) && columnStatistics.getStringStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getStringStatistics());
}
else if (type.getTypeSignature().getBase().equals(StandardTypes.DATE) && columnStatistics.getDateStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getDateStatistics(), value -> (long) value);
}
else if (type.getJavaType() == long.class && columnStatistics.getIntegerStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getIntegerStatistics());
}
else if (type.getJavaType() == double.class && columnStatistics.getDoubleStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getDoubleStatistics());
}
else if (REAL.equals(type) && columnStatistics.getDoubleStatistics() != null) {
return createDomain(type, hasNullValue, columnStatistics.getDoubleStatistics(), value -> (long) floatToRawIntBits(value.floatValue()));
}
return Domain.create(ValueSet.all(type), hasNullValue);
} | @Test
public void testBoolean()
{
assertEquals(getDomain(BOOLEAN, 0, null), Domain.none(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 10, null), Domain.all(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(null, null)), Domain.none(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(0L, null)), Domain.none(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(0L, 0L)), Domain.none(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(0L, 0L)), onlyNull(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(10L, null)), notNull(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(10L, 10L)), singleValue(BOOLEAN, true));
assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(10L, 0L)), singleValue(BOOLEAN, false));
assertEquals(getDomain(BOOLEAN, 20, booleanColumnStats(10L, 5L)), Domain.all(BOOLEAN));
assertEquals(getDomain(BOOLEAN, 20, booleanColumnStats(10L, 10L)), create(ValueSet.ofRanges(Range.equal(BOOLEAN, true)), true));
assertEquals(getDomain(BOOLEAN, 20, booleanColumnStats(10L, 0L)), create(ValueSet.ofRanges(Range.equal(BOOLEAN, false)), true));
} |
@SuppressWarnings("FutureReturnValueIgnored")
public void start() {
running.set(true);
configFetcher.start();
memoryMonitor.start();
streamingWorkerHarness.start();
sampler.start();
workerStatusReporter.start();
activeWorkRefresher.start();
} | @Test
public void testOutputKeyTooLargeException() throws Exception {
KvCoder<String, String> kvCoder = KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of());
List<ParallelInstruction> instructions =
Arrays.asList(
makeSourceInstruction(kvCoder),
makeDoFnInstruction(new ExceptionCatchingFn(), 0, kvCoder),
makeSinkInstruction(kvCoder, 1));
server.setExpectedExceptionCount(1);
StreamingDataflowWorker worker =
makeWorker(
defaultWorkerParams()
.setInstructions(instructions)
.setOperationalLimits(
OperationalLimits.builder()
.setMaxOutputKeyBytes(15)
.setThrowExceptionOnLargeOutput(true)
.build())
.build());
worker.start();
// This large key will cause the ExceptionCatchingFn to throw an exception, which will then
// cause it to output a smaller key.
String bigKey = "some_much_too_large_output_key";
server.whenGetWorkCalled().thenReturn(makeInput(1, 0, bigKey, DEFAULT_SHARDING_KEY));
server.waitForEmptyWorkQueue();
Map<Long, Windmill.WorkItemCommitRequest> result = server.waitForAndGetCommits(1);
assertEquals(1, result.size());
assertEquals(
makeExpectedOutput(1, 0, bigKey, DEFAULT_SHARDING_KEY, "smaller_key").build(),
removeDynamicFields(result.get(1L)));
} |
@Deprecated
public List<IndexSegment> prune(List<IndexSegment> segments, QueryContext query) {
return prune(segments, query, new SegmentPrunerStatistics());
} | @Test
public void emptySegmentsAreNotInvalid() {
SegmentPrunerService service = new SegmentPrunerService(_emptyPrunerConf);
IndexSegment indexSegment = mockIndexSegment(0, "col1", "col2");
SegmentPrunerStatistics stats = new SegmentPrunerStatistics();
List<IndexSegment> indexes = new ArrayList<>();
indexes.add(indexSegment);
String query = "select col1 from t1";
QueryContext queryContext = QueryContextConverterUtils.getQueryContext(query);
List<IndexSegment> actual = service.prune(indexes, queryContext, stats);
Assert.assertEquals(actual, Collections.emptyList());
Assert.assertEquals(stats.getInvalidSegments(), 0);
} |
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) getBeanFactory().getBean(name);
} | @Test
public void getBeanTest(){
final Demo2 testDemo = SpringUtil.getBean("testDemo");
assertEquals(12345, testDemo.getId());
assertEquals("test", testDemo.getName());
} |
public void isNotEmpty() {
if (actual == null) {
failWithActual(simpleFact("expected a non-empty string"));
} else if (actual.isEmpty()) {
failWithoutActual(simpleFact("expected not to be empty"));
}
} | @Test
public void stringIsNotEmpty() {
assertThat("abc").isNotEmpty();
} |
public Map<String, String> match(String text) {
final HashMap<String, String> result = MapUtil.newHashMap(true);
int from = 0;
String key = null;
int to;
for (String part : patterns) {
if (StrUtil.isWrap(part, "${", "}")) {
// 变量
key = StrUtil.sub(part, 2, part.length() - 1);
} else {
to = text.indexOf(part, from);
if (to < 0) {
//普通字符串未匹配到,说明整个模式不能匹配,返回空
return MapUtil.empty();
}
if (null != key && to > from) {
// 变量对应部分有内容
result.put(key, text.substring(from, to));
}
// 下一个起始点是普通字符串的末尾
from = to + part.length();
key = null;
}
}
if (null != key && from < text.length()) {
// 变量对应部分有内容
result.put(key, text.substring(from));
}
return result;
} | @Test
public void matcherTest2(){
// 当有无匹配项的时候,按照全不匹配对待
final StrMatcher strMatcher = new StrMatcher("${name}-${age}-${gender}-${country}-${province}-${city}-${status}");
final Map<String, String> match = strMatcher.match("小明-19-男-中国-河南-郑州");
assertEquals(0, match.size());
} |
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("version", version)
.add("type", type)
.add("length", length)
.toString();
} | @Test
public void testToStringBmp() throws Exception {
Bmp bmp = deserializer.deserialize(headerBytes, 0, headerBytes.length);
String str = bmp.toString();
assertTrue(StringUtils.contains(str, "version=" + version));
assertTrue(StringUtils.contains(str, "type=" + type));
assertTrue(StringUtils.contains(str, "length=" + length));
} |
public String getBaseUrl() {
String url = config.get(SERVER_BASE_URL).orElse("");
if (isEmpty(url)) {
url = computeBaseUrl();
}
// Remove trailing slashes
return StringUtils.removeEnd(url, "/");
} | @Test
public void base_url_is_http_localhost_specified_port_when_port_is_set() {
settings.setProperty(PORT_PORPERTY, 951);
assertThat(underTest().getBaseUrl()).isEqualTo("http://localhost:951");
} |
public static List<Criterion> parse(String filter) {
return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false)
.map(FilterParser::parseCriterion)
.toList();
} | @Test
public void metric_key_with_and_string() {
List<Criterion> criterion = FilterParser.parse("ncloc > 10 and operand = 5");
assertThat(criterion).hasSize(2).extracting(Criterion::getKey, Criterion::getValue).containsExactly(tuple("ncloc", "10"), tuple("operand", "5"));
} |
@Override
public T remove(Object key) {
if (key instanceof StructLike || key == null) {
StructLikeWrapper wrapper = wrappers.get();
T value = wrapperMap.remove(wrapper.set((StructLike) key));
wrapper.set(null); // don't hold a reference to the key.
return value;
}
return null;
} | @Test
public void testRemove() {
Record gRecord = GenericRecord.create(STRUCT_TYPE);
Record record = gRecord.copy(ImmutableMap.of("id", 1, "data", "aaa"));
Map<StructLike, String> map = StructLikeMap.create(STRUCT_TYPE);
map.put(record, "1-aaa");
assertThat(map).hasSize(1).containsEntry(record, "1-aaa");
assertThat(map.remove(record)).isEqualTo("1-aaa");
assertThat(map).isEmpty();
map.put(record, "1-aaa");
assertThat(map).containsEntry(record, "1-aaa");
} |
@Override
public int deleteTopics(final Set<String> deleteTopics) {
if (deleteTopics == null || deleteTopics.isEmpty()) {
return 0;
}
int deleteCount = 0;
for (String topic : deleteTopics) {
ConcurrentMap<Integer, ConsumeQueueInterface> queueTable = this.consumeQueueStore.findConsumeQueueMap(topic);
if (queueTable == null || queueTable.isEmpty()) {
continue;
}
for (ConsumeQueueInterface cq : queueTable.values()) {
try {
this.consumeQueueStore.destroy(cq);
} catch (RocksDBException e) {
LOGGER.error("DeleteTopic: ConsumeQueue cleans error!, topic={}, queueId={}", cq.getTopic(), cq.getQueueId(), e);
}
LOGGER.info("DeleteTopic: ConsumeQueue has been cleaned, topic={}, queueId={}", cq.getTopic(), cq.getQueueId());
this.consumeQueueStore.removeTopicQueueTable(cq.getTopic(), cq.getQueueId());
}
// remove topic from cq table
this.consumeQueueStore.getConsumeQueueTable().remove(topic);
if (this.brokerConfig.isAutoDeleteUnusedStats()) {
this.brokerStatsManager.onTopicDeleted(topic);
}
// destroy consume queue dir
String consumeQueueDir = StorePathConfigHelper.getStorePathConsumeQueue(
this.messageStoreConfig.getStorePathRootDir()) + File.separator + topic;
String consumeQueueExtDir = StorePathConfigHelper.getStorePathConsumeQueueExt(
this.messageStoreConfig.getStorePathRootDir()) + File.separator + topic;
String batchConsumeQueueDir = StorePathConfigHelper.getStorePathBatchConsumeQueue(
this.messageStoreConfig.getStorePathRootDir()) + File.separator + topic;
UtilAll.deleteEmptyDirectory(new File(consumeQueueDir));
UtilAll.deleteEmptyDirectory(new File(consumeQueueExtDir));
UtilAll.deleteEmptyDirectory(new File(batchConsumeQueueDir));
LOGGER.info("DeleteTopic: Topic has been destroyed, topic={}", topic);
deleteCount++;
}
return deleteCount;
} | @Test
public void testDeleteTopics() {
MessageStoreConfig messageStoreConfig = messageStore.getMessageStoreConfig();
ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueueInterface>> consumeQueueTable =
((DefaultMessageStore) messageStore).getConsumeQueueTable();
for (int i = 0; i < 10; i++) {
ConcurrentMap<Integer, ConsumeQueueInterface> cqTable = new ConcurrentHashMap<>();
String topicName = "topic-" + i;
for (int j = 0; j < 4; j++) {
ConsumeQueue consumeQueue = new ConsumeQueue(topicName, j, messageStoreConfig.getStorePathRootDir(),
messageStoreConfig.getMappedFileSizeConsumeQueue(), messageStore);
cqTable.put(j, consumeQueue);
}
consumeQueueTable.put(topicName, cqTable);
}
Assert.assertEquals(consumeQueueTable.size(), 10);
HashSet<String> resultSet = Sets.newHashSet("topic-3", "topic-5");
messageStore.deleteTopics(Sets.difference(consumeQueueTable.keySet(), resultSet));
Assert.assertEquals(consumeQueueTable.size(), 2);
Assert.assertEquals(resultSet, consumeQueueTable.keySet());
} |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingConfig.getNamespace().equals(newConfig.getNamespace())) {
throw new IllegalArgumentException("Namespaces differ");
}
if (!existingConfig.getName().equals(newConfig.getName())) {
throw new IllegalArgumentException("Sink Names differ");
}
if (!StringUtils.isEmpty(newConfig.getClassName())) {
mergedConfig.setClassName(newConfig.getClassName());
}
if (!StringUtils.isEmpty(newConfig.getSourceSubscriptionName()) && !newConfig.getSourceSubscriptionName()
.equals(existingConfig.getSourceSubscriptionName())) {
throw new IllegalArgumentException("Subscription Name cannot be altered");
}
if (newConfig.getInputSpecs() == null) {
newConfig.setInputSpecs(new HashMap<>());
}
if (mergedConfig.getInputSpecs() == null) {
mergedConfig.setInputSpecs(new HashMap<>());
}
if (!StringUtils.isEmpty(newConfig.getLogTopic())) {
mergedConfig.setLogTopic(newConfig.getLogTopic());
}
if (newConfig.getInputs() != null) {
newConfig.getInputs().forEach((topicName -> {
newConfig.getInputSpecs().putIfAbsent(topicName,
ConsumerConfig.builder().isRegexPattern(false).build());
}));
}
if (newConfig.getTopicsPattern() != null && !newConfig.getTopicsPattern().isEmpty()) {
newConfig.getInputSpecs().put(newConfig.getTopicsPattern(),
ConsumerConfig.builder()
.isRegexPattern(true)
.build());
}
if (newConfig.getTopicToSerdeClassName() != null) {
newConfig.getTopicToSerdeClassName().forEach((topicName, serdeClassName) -> {
newConfig.getInputSpecs().put(topicName,
ConsumerConfig.builder()
.serdeClassName(serdeClassName)
.isRegexPattern(false)
.build());
});
}
if (newConfig.getTopicToSchemaType() != null) {
newConfig.getTopicToSchemaType().forEach((topicName, schemaClassname) -> {
newConfig.getInputSpecs().put(topicName,
ConsumerConfig.builder()
.schemaType(schemaClassname)
.isRegexPattern(false)
.build());
});
}
if (!newConfig.getInputSpecs().isEmpty()) {
SinkConfig finalMergedConfig = mergedConfig;
newConfig.getInputSpecs().forEach((topicName, consumerConfig) -> {
if (!existingConfig.getInputSpecs().containsKey(topicName)) {
throw new IllegalArgumentException("Input Topics cannot be altered");
}
if (consumerConfig.isRegexPattern() != existingConfig.getInputSpecs().get(topicName).isRegexPattern()) {
throw new IllegalArgumentException(
"isRegexPattern for input topic " + topicName + " cannot be altered");
}
finalMergedConfig.getInputSpecs().put(topicName, consumerConfig);
});
}
if (newConfig.getProcessingGuarantees() != null && !newConfig.getProcessingGuarantees()
.equals(existingConfig.getProcessingGuarantees())) {
throw new IllegalArgumentException("Processing Guarantees cannot be altered");
}
if (newConfig.getConfigs() != null) {
mergedConfig.setConfigs(newConfig.getConfigs());
}
if (newConfig.getSecrets() != null) {
mergedConfig.setSecrets(newConfig.getSecrets());
}
if (newConfig.getParallelism() != null) {
mergedConfig.setParallelism(newConfig.getParallelism());
}
if (newConfig.getRetainOrdering() != null && !newConfig.getRetainOrdering()
.equals(existingConfig.getRetainOrdering())) {
throw new IllegalArgumentException("Retain Ordering cannot be altered");
}
if (newConfig.getRetainKeyOrdering() != null && !newConfig.getRetainKeyOrdering()
.equals(existingConfig.getRetainKeyOrdering())) {
throw new IllegalArgumentException("Retain Key Ordering cannot be altered");
}
if (newConfig.getAutoAck() != null && !newConfig.getAutoAck().equals(existingConfig.getAutoAck())) {
throw new IllegalArgumentException("AutoAck cannot be altered");
}
if (newConfig.getResources() != null) {
mergedConfig
.setResources(ResourceConfigUtils.merge(existingConfig.getResources(), newConfig.getResources()));
}
if (newConfig.getTimeoutMs() != null) {
mergedConfig.setTimeoutMs(newConfig.getTimeoutMs());
}
if (newConfig.getCleanupSubscription() != null) {
mergedConfig.setCleanupSubscription(newConfig.getCleanupSubscription());
}
if (!StringUtils.isEmpty(newConfig.getArchive())) {
mergedConfig.setArchive(newConfig.getArchive());
}
if (!StringUtils.isEmpty(newConfig.getRuntimeFlags())) {
mergedConfig.setRuntimeFlags(newConfig.getRuntimeFlags());
}
if (!StringUtils.isEmpty(newConfig.getCustomRuntimeOptions())) {
mergedConfig.setCustomRuntimeOptions(newConfig.getCustomRuntimeOptions());
}
if (newConfig.getTransformFunction() != null) {
mergedConfig.setTransformFunction(newConfig.getTransformFunction());
}
if (newConfig.getTransformFunctionClassName() != null) {
mergedConfig.setTransformFunctionClassName(newConfig.getTransformFunctionClassName());
}
if (newConfig.getTransformFunctionConfig() != null) {
mergedConfig.setTransformFunctionConfig(newConfig.getTransformFunctionConfig());
}
return mergedConfig;
} | @Test
public void testMergeDifferentLogTopic() {
SinkConfig sinkConfig = createSinkConfig();
SinkConfig newSinkConfig = createUpdatedSinkConfig("logTopic", "Different");
SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig);
assertEquals(
mergedConfig.getLogTopic(),
"Different"
);
mergedConfig.setLogTopic(sinkConfig.getLogTopic());
assertEquals(
new Gson().toJson(sinkConfig),
new Gson().toJson(mergedConfig)
);
} |
@Override
public boolean next() throws SQLException {
if (skipAll) {
return false;
}
if (!paginationContext.getActualRowCount().isPresent()) {
return getMergedResult().next();
}
return ++rowNumber <= paginationContext.getActualRowCount().get() && getMergedResult().next();
} | @Test
void assertNextWithoutRowCount() throws SQLException {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
MySQLSelectStatement selectStatement = new MySQLSelectStatement();
selectStatement.setProjections(new ProjectionsSegment(0, 0));
selectStatement.setLimit(new LimitSegment(0, 0, new NumberLiteralLimitValueSegment(0, 0, 2L), null));
SelectStatementContext selectStatementContext =
new SelectStatementContext(createShardingSphereMetaData(database), Collections.emptyList(), selectStatement, DefaultDatabase.LOGIC_NAME, Collections.emptyList());
when(database.getName()).thenReturn(DefaultDatabase.LOGIC_NAME);
ShardingDQLResultMerger resultMerger = new ShardingDQLResultMerger(TypedSPILoader.getService(DatabaseType.class, "MySQL"));
MergedResult actual = resultMerger.merge(Arrays.asList(mockQueryResult(), mockQueryResult(), mockQueryResult(), mockQueryResult()), selectStatementContext, database,
mock(ConnectionContext.class));
for (int i = 0; i < 6; i++) {
assertTrue(actual.next());
}
assertFalse(actual.next());
} |
public MessageReceiptHandle removeOne(String msgID) {
Map<HandleKey, HandleData> handleMap = this.receiptHandleMap.get(msgID);
if (handleMap == null) {
return null;
}
Set<HandleKey> keys = handleMap.keySet();
for (HandleKey key : keys) {
MessageReceiptHandle res = this.remove(msgID, key.originalHandle);
if (res != null) {
return res;
}
}
return null;
} | @Test
public void testRemoveOne() {
String handle1 = createHandle();
AtomicReference<MessageReceiptHandle> removeHandleRef = new AtomicReference<>();
AtomicInteger count = new AtomicInteger();
receiptHandleGroup.put(msgID, createMessageReceiptHandle(handle1, msgID));
int threadNum = Math.max(Runtime.getRuntime().availableProcessors(), 3);
CountDownLatch latch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
Thread thread = new Thread(() -> {
try {
latch.countDown();
latch.await();
MessageReceiptHandle handle = receiptHandleGroup.removeOne(msgID);
if (handle != null) {
removeHandleRef.set(handle);
count.incrementAndGet();
}
} catch (Exception ignored) {
}
});
thread.start();
}
await().atMost(Duration.ofSeconds(1)).untilAsserted(() -> assertEquals(1, count.get()));
assertEquals(handle1, removeHandleRef.get().getReceiptHandleStr());
assertTrue(receiptHandleGroup.isEmpty());
} |
public AbilityStatus getConnectionAbility(AbilityKey abilityKey) {
if (currentConnection != null) {
return currentConnection.getConnectionAbility(abilityKey);
}
// return null if connection is not ready
return null;
} | @Test
void testGetConnectionAbilityWithReadyConnection() {
when(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)).thenReturn(AbilityStatus.SUPPORTED);
rpcClient.currentConnection = connection;
AbilityStatus abilityStatus = rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1);
assertNotNull(abilityStatus);
assertEquals(AbilityStatus.SUPPORTED, abilityStatus);
} |
public String getStoreMode() {
return storeMode;
} | @Test
public void testGetStoreMode() {
Assertions.assertEquals("file", parameterParser.getStoreMode());
} |
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCodegen(Long tableId) {
// 校验是否已经存在
if (codegenTableMapper.selectById(tableId) == null) {
throw exception(CODEGEN_TABLE_NOT_EXISTS);
}
// 删除 table 表定义
codegenTableMapper.deleteById(tableId);
// 删除 column 字段定义
codegenColumnMapper.deleteListByTableId(tableId);
} | @Test
public void testDeleteCodegen_success() {
// mock 数据
CodegenTableDO table = randomPojo(CodegenTableDO.class,
o -> o.setScene(CodegenSceneEnum.ADMIN.getScene()));
codegenTableMapper.insert(table);
CodegenColumnDO column = randomPojo(CodegenColumnDO.class, o -> o.setTableId(table.getId()));
codegenColumnMapper.insert(column);
// 准备参数
Long tableId = table.getId();
// 调用
codegenService.deleteCodegen(tableId);
// 断言
assertNull(codegenTableMapper.selectById(tableId));
assertEquals(0, codegenColumnMapper.selectList().size());
} |
public static boolean isCompositeURI(URI uri) {
String ssp = stripPrefix(uri.getRawSchemeSpecificPart().trim(), "//").trim();
if (ssp.indexOf('(') == 0 && checkParenthesis(ssp)) {
return true;
}
return false;
} | @Test
public void testIsCompositeURIWithQueryAndSlashes() throws URISyntaxException {
URI[] compositeURIs = new URI[] { new URI("test://(part1://host?part1=true)?outside=true"), new URI("broker://(tcp://localhost:61616)?name=foo") };
for (URI uri : compositeURIs) {
assertTrue(uri + " must be detected as composite URI", URISupport.isCompositeURI(uri));
}
} |
public static List<UpdateRequirement> forUpdateTable(
TableMetadata base, List<MetadataUpdate> metadataUpdates) {
Preconditions.checkArgument(null != base, "Invalid table metadata: null");
Preconditions.checkArgument(null != metadataUpdates, "Invalid metadata updates: null");
Builder builder = new Builder(base, false);
builder.require(new UpdateRequirement.AssertTableUUID(base.uuid()));
metadataUpdates.forEach(builder::update);
return builder.build();
} | @Test
public void setDefaultPartitionSpec() {
int specId = 3;
when(metadata.defaultSpecId()).thenReturn(specId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetDefaultPartitionSpec(specId),
new MetadataUpdate.SetDefaultPartitionSpec(specId + 1),
new MetadataUpdate.SetDefaultPartitionSpec(specId + 2)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class, UpdateRequirement.AssertDefaultSpecID.class);
assertTableUUID(requirements);
assertThat(requirements)
.element(1)
.asInstanceOf(InstanceOfAssertFactories.type(UpdateRequirement.AssertDefaultSpecID.class))
.extracting(UpdateRequirement.AssertDefaultSpecID::specId)
.isEqualTo(specId);
} |
public static void smooth(PointList geometry, double maxWindowSize) {
if (geometry.size() <= 2) {
// geometry consists only of tower nodes, there are no pillar nodes to be smoothed in between
return;
}
// calculate the distance between all points once here to avoid repeated calculation.
// for n nodes there are always n-1 edges
double[] distances = new double[geometry.size() - 1];
for (int i = 0; i <= geometry.size() - 2; i++) {
distances[i] = DistancePlaneProjection.DIST_PLANE.calcDist(
geometry.getLat(i), geometry.getLon(i),
geometry.getLat(i + 1), geometry.getLon(i + 1)
);
}
// map that will collect all smoothed elevation values, size is less by 2
// because elevation of start and end point (tower nodes) won't be touched
IntDoubleHashMap averagedElevations = new IntDoubleHashMap((geometry.size() - 1) * 4 / 3);
// iterate over every pillar node to smooth its elevation
// first and last points are left out as they are tower nodes
for (int i = 1; i <= geometry.size() - 2; i++) {
// first, determine the average window which could be smaller when close to pillar nodes
double searchDistance = maxWindowSize / 2.0;
double searchDistanceBack = 0.0;
for (int j = i - 1; j >= 0; j--) {
searchDistanceBack += distances[j];
if (searchDistanceBack > searchDistance) {
break;
}
}
// update search distance if pillar node is close to START tower node
searchDistance = Math.min(searchDistance, searchDistanceBack);
double searchDistanceForward = 0.0;
for (int j = i; j < geometry.size() - 1; j++) {
searchDistanceForward += distances[j];
if (searchDistanceForward > searchDistance) {
break;
}
}
// update search distance if pillar node is close to END tower node
searchDistance = Math.min(searchDistance, searchDistanceForward);
if (searchDistance <= 0.0) {
// there is nothing to smooth. this is an edge case where pillar nodes share exactly the same location
// as a tower node.
// by doing so we avoid (at least theoretically) a division by zero later in the function call
continue;
}
// area under elevation curve
double elevationArea = 0.0;
// first going again backwards
double distanceBack = 0.0;
for (int j = i - 1; j >= 0; j--) {
double dist = distances[j];
double searchDistLeft = searchDistance - distanceBack;
distanceBack += dist;
if (searchDistLeft < dist) {
// node lies outside averaging window
double elevationDelta = geometry.getEle(j) - geometry.getEle(j + 1);
double elevationAtSearchDistance = geometry.getEle(j + 1) + searchDistLeft / dist * elevationDelta;
elevationArea += searchDistLeft * (geometry.getEle(j + 1) + elevationAtSearchDistance) / 2.0;
break;
} else {
elevationArea += dist * (geometry.getEle(j + 1) + geometry.getEle(j)) / 2.0;
}
}
// now going forward
double distanceForward = 0.0;
for (int j = i; j < geometry.size() - 1; j++) {
double dist = distances[j];
double searchDistLeft = searchDistance - distanceForward;
distanceForward += dist;
if (searchDistLeft < dist) {
double elevationDelta = geometry.getEle(j + 1) - geometry.getEle(j);
double elevationAtSearchDistance = geometry.getEle(j) + searchDistLeft / dist * elevationDelta;
elevationArea += searchDistLeft * (geometry.getEle(j) + elevationAtSearchDistance) / 2.0;
break;
} else {
elevationArea += dist * (geometry.getEle(j + 1) + geometry.getEle(j)) / 2.0;
}
}
double elevationAverage = elevationArea / (searchDistance * 2);
averagedElevations.put(i, elevationAverage);
}
// after all pillar nodes got an averaged elevation, elevations are overwritten
averagedElevations.forEach((Consumer<IntDoubleCursor>) c -> geometry.setElevation(c.key, c.value));
} | @Test
public void testManyPoints() {
/**
* used to cross validate this implementation as it was ported from an internal kotlin prototype
*/
PointList pl = new PointList(27, true);
pl.add(10.153564, 47.324976, 1209.5);
pl.add(10.15365, 47.32499, 1209.3);
pl.add(10.153465, 47.325058, 1213.6);
pl.add(10.153382, 47.325062, 1213.5);
pl.add(10.153283, 47.325048, 1213.5);
pl.add(10.153049, 47.324956, 1213.5);
pl.add(10.152899, 47.324949, 1213.6);
pl.add(10.152795, 47.324968, 1213.7);
pl.add(10.152706, 47.325044, 1213.7);
pl.add(10.152466, 47.325041, 1215.2);
pl.add(10.152283, 47.32508, 1215.4);
pl.add(10.152216, 47.325074, 1215.5);
pl.add(10.151649, 47.324849, 1216);
pl.add(10.151502, 47.324824, 1216.9);
pl.add(10.151212, 47.324708, 1218.1);
pl.add(10.150862, 47.324493, 1219.7);
pl.add(10.150729, 47.324491, 1220.4);
pl.add(10.150714, 47.324514, 1220.6);
pl.add(10.150767, 47.324605, 1226.5);
pl.add(10.150989, 47.324943, 1236.4);
pl.add(10.150996, 47.32502, 1236.3);
pl.add(10.150964, 47.325038, 1236.3);
pl.add(10.150528, 47.324928, 1237.2);
pl.add(10.149945, 47.324733, 1239.3);
pl.add(10.14989, 47.324736, 1249.9);
pl.add(10.149504, 47.324455, 1248.6);
pl.add(10.149392, 47.324333, 1248);
EdgeElevationSmoothingMovingAverage.smooth(pl, 150.0);
double[] expectedElevations = {
1209.5, 1209.8259124400417, 1212.16778770315, 1212.4695940128302,
1212.7073845131501, 1213.3531253136111, 1213.933051594191,
1214.1484378838704, 1214.3274054744827, 1214.72713517562,
1215.0590153809194, 1215.1879106460751, 1216.6557611915186,
1217.0679077126047, 1218.343674121969, 1223.000531752824,
1224.8734639760428, 1225.2508699507118, 1226.687883355977,
1232.0752337564345, 1233.0834528364871, 1233.565160290987,
1237.6276352913503, 1243.4122145535805, 1243.92486025017,
1248.5623859735897, 1248.0
};
for (int i = 0; i < pl.size(); i++) {
assertEquals(expectedElevations[i], pl.getEle(i), 0.0000001);
}
} |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
return parser.parse(false);
} | @Test
public void shouldNotParseUnquotedArrayElementsAsStrings() {
SchemaAndValue schemaAndValue = Values.parseString("[foo]");
assertEquals(Type.STRING, schemaAndValue.schema().type());
assertEquals("[foo]", schemaAndValue.value());
} |
public static RepositoryMetadataStore getInstance() {
return repositoryMetadataStore;
} | @Test
public void shouldAnswerIfKeyHasGivenOption() throws Exception {
PackageConfigurations repositoryConfigurationPut = new PackageConfigurations();
repositoryConfigurationPut.add(new PackageConfiguration("key-one").with(PackageConfiguration.SECURE, true).with(PackageConfiguration.REQUIRED, true));
repositoryConfigurationPut.add(new PackageConfiguration("key-two"));
RepositoryMetadataStore metadataStore = RepositoryMetadataStore.getInstance();
metadataStore.addMetadataFor("plugin-id", repositoryConfigurationPut);
assertThat(metadataStore.hasOption("plugin-id", "key-one", PackageConfiguration.SECURE),is(true));
assertThat(metadataStore.hasOption("plugin-id", "key-one", PackageConfiguration.REQUIRED),is(true));
assertThat(metadataStore.hasOption("plugin-id", "key-one", PackageConfiguration.PART_OF_IDENTITY),is(true));
assertThat(metadataStore.hasOption("plugin-id", "key-two", PackageConfiguration.SECURE),is(false));
assertThat(metadataStore.hasOption("plugin-id", "key-two", PackageConfiguration.REQUIRED),is(true));
assertThat(metadataStore.hasOption("plugin-id", "key-two", PackageConfiguration.PART_OF_IDENTITY),is(true));
} |
@Override
public Connector build(Server server, MetricRegistry metrics, String name, @Nullable ThreadPool threadPool) {
final HttpConfiguration httpConfig = buildHttpConfiguration();
final HttpConnectionFactory httpConnectionFactory = buildHttpConnectionFactory(httpConfig);
final SslContextFactory.Server sslContextFactory = configureSslContextFactory(new SslContextFactory.Server());
sslContextFactory.addEventListener(logSslParameters(sslContextFactory));
server.addBean(sslContextFactory);
server.addBean(new SslReload(sslContextFactory, this::configureSslContextFactory));
final SslConnectionFactory sslConnectionFactory =
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString());
final Scheduler scheduler = new ScheduledExecutorScheduler();
final ByteBufferPool bufferPool = buildBufferPool();
return buildConnector(server, scheduler, bufferPool, name, threadPool,
new InstrumentedConnectionFactory(
sslConnectionFactory,
metrics.timer(httpConnections())),
httpConnectionFactory);
} | @Test
void testBuild() throws Exception {
final HttpsConnectorFactory https = new HttpsConnectorFactory();
https.setBindHost("127.0.0.1");
https.setPort(8443);
https.setKeyStorePath("/etc/app/server.ks");
https.setKeyStoreType("JKS");
https.setKeyStorePassword("correct_horse");
https.setKeyStoreProvider("BC");
https.setTrustStorePath("/etc/app/server.ts");
https.setTrustStoreType("JKS");
https.setTrustStorePassword("battery_staple");
https.setTrustStoreProvider("BC");
https.setKeyManagerPassword("new_overlords");
https.setNeedClientAuth(true);
https.setWantClientAuth(true);
https.setCertAlias("alt_server");
https.setCrlPath(new File("/etc/ctr_list.txt"));
https.setEnableCRLDP(true);
https.setEnableOCSP(true);
https.setMaxCertPathLength(4);
https.setOcspResponderUrl(new URI("http://windc1/ocsp"));
https.setJceProvider("BC");
https.setAllowRenegotiation(false);
https.setEndpointIdentificationAlgorithm("HTTPS");
https.setValidateCerts(true);
https.setValidatePeers(true);
https.setSupportedProtocols(Arrays.asList("TLSv1.1", "TLSv1.2"));
https.setSupportedCipherSuites(Arrays.asList("TLS_DHE_RSA.*", "TLS_ECDHE.*"));
final Server server = new Server();
final MetricRegistry metrics = new MetricRegistry();
final ThreadPool threadPool = new QueuedThreadPool();
try (final ServerConnector serverConnector = (ServerConnector) https.build(server, metrics, "test-https-connector", threadPool)) {
assertThat(serverConnector.getPort()).isEqualTo(8443);
assertThat(serverConnector.getHost()).isEqualTo("127.0.0.1");
assertThat(serverConnector.getName()).isEqualTo("test-https-connector");
assertThat(serverConnector.getServer()).isSameAs(server);
assertThat(serverConnector.getScheduler()).isInstanceOf(ScheduledExecutorScheduler.class);
assertThat(serverConnector.getExecutor()).isSameAs(threadPool);
final InstrumentedConnectionFactory sslConnectionFactory =
(InstrumentedConnectionFactory) serverConnector.getConnectionFactory("ssl");
assertThat(sslConnectionFactory).isInstanceOf(InstrumentedConnectionFactory.class);
assertThat(sslConnectionFactory)
.extracting("connectionFactory")
.asInstanceOf(InstanceOfAssertFactories.type(SslConnectionFactory.class))
.extracting(SslConnectionFactory::getSslContextFactory)
.satisfies(sslContextFactory -> {
assertThat(sslContextFactory.getKeyStoreResource())
.isEqualTo(newResource("/etc/app/server.ks"));
assertThat(sslContextFactory.getKeyStoreType()).isEqualTo("JKS");
assertThat(sslContextFactory).extracting("_keyStorePassword")
.isEqualTo("correct_horse");
assertThat(sslContextFactory.getKeyStoreProvider()).isEqualTo("BC");
assertThat(sslContextFactory.getTrustStoreResource())
.isEqualTo(newResource("/etc/app/server.ts"));
assertThat(sslContextFactory.getKeyStoreType()).isEqualTo("JKS");
assertThat(sslContextFactory).extracting("_trustStorePassword")
.isEqualTo("battery_staple");
assertThat(sslContextFactory.getKeyStoreProvider()).isEqualTo("BC");
assertThat(sslContextFactory).extracting("_keyManagerPassword")
.isEqualTo("new_overlords");
assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
assertThat(sslContextFactory.getWantClientAuth()).isTrue();
assertThat(sslContextFactory.getCertAlias()).isEqualTo("alt_server");
assertThat(sslContextFactory.getCrlPath()).isEqualTo(new File("/etc/ctr_list.txt").getAbsolutePath());
assertThat(sslContextFactory.isEnableCRLDP()).isTrue();
assertThat(sslContextFactory.isEnableOCSP()).isTrue();
assertThat(sslContextFactory.getMaxCertPathLength()).isEqualTo(4);
assertThat(sslContextFactory.getOcspResponderURL()).isEqualTo("http://windc1/ocsp");
assertThat(sslContextFactory.getProvider()).isEqualTo("BC");
assertThat(sslContextFactory.isRenegotiationAllowed()).isFalse();
assertThat(sslContextFactory.getEndpointIdentificationAlgorithm()).isEqualTo("HTTPS");
assertThat(sslContextFactory.isValidateCerts()).isTrue();
assertThat(sslContextFactory.isValidatePeerCerts()).isTrue();
assertThat(sslContextFactory.getIncludeProtocols()).containsOnly("TLSv1.1", "TLSv1.2");
assertThat(sslContextFactory.getIncludeCipherSuites()).containsOnly("TLS_DHE_RSA.*", "TLS_ECDHE.*");
});
final ConnectionFactory httpConnectionFactory = serverConnector.getConnectionFactory("http/1.1");
assertThat(httpConnectionFactory).isInstanceOf(HttpConnectionFactory.class);
final HttpConfiguration httpConfiguration = ((HttpConnectionFactory) httpConnectionFactory)
.getHttpConfiguration();
assertThat(httpConfiguration.getSecureScheme()).isEqualTo("https");
assertThat(httpConfiguration.getSecurePort()).isEqualTo(8443);
assertThat(httpConfiguration.getCustomizers()).hasAtLeastOneElementOfType(SecureRequestCustomizer.class);
} finally {
server.stop();
}
} |
void logRun(long runIndex, boolean runSucceeded, Duration pollInterval, Instant runStartTime, Instant runEndTime) {
if (runSucceeded && exceptionCounter > 0) {
--exceptionCounter;
}
Duration actualRunDuration = Duration.between(runStartTime, runEndTime);
if (actualRunDuration.compareTo(pollInterval) < 0) {
LOGGER.debug("JobZooKeeper run took {}", actualRunDuration);
runTookToLongCounter = 0;
} else {
LOGGER.debug("JobZooKeeper run took {} (while pollIntervalInSeconds is {})", actualRunDuration, pollInterval);
if (runTookToLongCounter < 2) {
runTookToLongCounter++;
} else {
dashboardNotificationManager.notify(new PollIntervalInSecondsTimeBoxIsTooSmallNotification(runIndex, (int) pollInterval.getSeconds(), runStartTime, (int) actualRunDuration.getSeconds()));
runTookToLongCounter = 0;
}
}
} | @Test
void ifThreeConsecutiveRunsTookTooLongANotificationIsShown() {
statistics.logRun(2, true, pollInterval, now().minusSeconds(45), now().minusSeconds(30));
statistics.logRun(3, true, pollInterval, now().minusSeconds(30), now().minusSeconds(15));
statistics.logRun(4, true, pollInterval, now().minusSeconds(15), now());
verify(dashboardNotificationManager).notify(any(PollIntervalInSecondsTimeBoxIsTooSmallNotification.class));
} |
@Override @Nonnull public ListIterator<T> listIterator(final int initialIndex) {
final Iterator<T> initialIterator;
try {
initialIterator = iterator(initialIndex);
} catch (NoSuchElementException ex) {
throw new IndexOutOfBoundsException();
}
return new AbstractListIterator<T>() {
private int index = initialIndex - 1;
@Nullable private Iterator<T> forwardIterator = initialIterator;
@Nonnull
private Iterator<T> getForwardIterator() {
if (forwardIterator == null) {
try {
forwardIterator = iterator(index+1);
} catch (IndexOutOfBoundsException ex) {
throw new NoSuchElementException();
}
}
return forwardIterator;
}
@Override public boolean hasNext() {
return getForwardIterator().hasNext();
}
@Override public boolean hasPrevious() {
return index >= 0;
}
@Override public T next() {
T ret = getForwardIterator().next();
index++;
return ret;
}
@Override public int nextIndex() {
return index+1;
}
@Override public T previous() {
forwardIterator = null;
try {
return iterator(index--).next();
} catch (IndexOutOfBoundsException ex) {
throw new NoSuchElementException();
}
}
@Override public int previousIndex() {
return index;
}
};
} | @Test
public void testForwardIterationException() {
// note: no "expected = NoSuchElementException", because we want to make sure the exception occurs only during
// the last call to next()
ListIterator<Integer> iter = list.listIterator(0);
for (int i=0; i<100; i++) {
iter.next();
}
try {
iter.next();
} catch (NoSuchElementException ex) {
return;
}
Assert.fail();
} |
@Override
public double quantile(double p) {
if (p < 0.0 || p > 1.0) {
throw new IllegalArgumentException("Invalid p: " + p);
}
if (p < Math.exp(-lambda)) {
return 0;
}
int n = (int) Math.max(Math.sqrt(lambda), 5.0);
int nl, nu, inc = 1;
if (p < cdf(n)) {
do {
n = Math.max(n - inc, 0);
inc *= 2;
} while (p < cdf(n) && n > 0);
nl = n;
nu = n + inc / 2;
} else {
do {
n += inc;
inc *= 2;
} while (p > cdf(n));
nu = n;
nl = n - inc / 2;
}
return quantile(p, nl, nu);
} | @Test
public void testQuantile() {
System.out.println("quantile");
PoissonDistribution instance = new PoissonDistribution(3.5);
instance.rand();
assertEquals(0, instance.quantile(0.01), 1E-7);
assertEquals(1, instance.quantile(0.1), 1E-7);
assertEquals(2, instance.quantile(0.2), 1E-7);
assertEquals(2, instance.quantile(0.3), 1E-7);
assertEquals(3, instance.quantile(0.4), 1E-6);
assertEquals(3, instance.quantile(0.5), 1E-6);
assertEquals(6, instance.quantile(0.9), 1E-6);
assertEquals(8, instance.quantile(0.99), 1E-6);
} |
public boolean canSchedule(SchedulerGroupAccountant accountant) {
return accountant.totalReservedThreads() < getTableThreadsHardLimit();
} | @Test
public void testCanSchedule()
throws Exception {
ResourceManager rm = getResourceManager(2, 5, 1, 3);
SchedulerGroupAccountant accountant = mock(SchedulerGroupAccountant.class);
when(accountant.totalReservedThreads()).thenReturn(3);
assertFalse(rm.canSchedule(accountant));
when(accountant.totalReservedThreads()).thenReturn(2);
assertTrue(rm.canSchedule(accountant));
} |
@Subscribe
public void onScriptCallbackEvent(ScriptCallbackEvent event)
{
// ROE uncharge uses the same script as destroy
if (!"destroyOnOpKey".equals(event.getEventName()))
{
return;
}
final int yesOption = client.getIntStack()[client.getIntStackSize() - 1];
if (yesOption == 1)
{
checkDestroyWidget();
}
} | @Test
public void testUncharge()
{
when(client.getIntStack()).thenReturn(new int[]{1, RING_OF_ENDURANCE});
when(client.getIntStackSize()).thenReturn(1);
when(client.getTickCount()).thenReturn(1);
Widget enduranceWidget = mock(Widget.class);
when(client.getWidget(ComponentID.DESTROY_ITEM_NAME)).thenReturn(enduranceWidget);
when(enduranceWidget.getText()).thenReturn("Ring of endurance");
ScriptCallbackEvent scriptCallbackEvent = new ScriptCallbackEvent();
scriptCallbackEvent.setEventName("destroyOnOpKey");
runEnergyPlugin.onScriptCallbackEvent(scriptCallbackEvent);
verify(configManager).setRSProfileConfiguration(RunEnergyConfig.GROUP_NAME, "ringOfEnduranceCharges", 0);
} |
public static double conversion(String expression) {
return (new Calculator()).calculate(expression);
} | @Test
public void conversationTest6() {
final double conversion = Calculator.conversion("-((2.12-2) * 100)");
assertEquals(-1D * (2.12 - 2) * 100, conversion, 0.01);
} |
public void skipValue() throws IOException {
int count = 0;
do {
int p = peeked;
if (p == PEEKED_NONE) {
p = doPeek();
}
switch (p) {
case PEEKED_BEGIN_ARRAY:
push(JsonScope.EMPTY_ARRAY);
count++;
break;
case PEEKED_BEGIN_OBJECT:
push(JsonScope.EMPTY_OBJECT);
count++;
break;
case PEEKED_END_ARRAY:
stackSize--;
count--;
break;
case PEEKED_END_OBJECT:
// Only update when object end is explicitly skipped, otherwise stack is not updated
// anyways
if (count == 0) {
// Free the last path name so that it can be garbage collected
pathNames[stackSize - 1] = null;
}
stackSize--;
count--;
break;
case PEEKED_UNQUOTED:
skipUnquotedValue();
break;
case PEEKED_SINGLE_QUOTED:
skipQuotedValue('\'');
break;
case PEEKED_DOUBLE_QUOTED:
skipQuotedValue('"');
break;
case PEEKED_UNQUOTED_NAME:
skipUnquotedValue();
// Only update when name is explicitly skipped, otherwise stack is not updated anyways
if (count == 0) {
pathNames[stackSize - 1] = "<skipped>";
}
break;
case PEEKED_SINGLE_QUOTED_NAME:
skipQuotedValue('\'');
// Only update when name is explicitly skipped, otherwise stack is not updated anyways
if (count == 0) {
pathNames[stackSize - 1] = "<skipped>";
}
break;
case PEEKED_DOUBLE_QUOTED_NAME:
skipQuotedValue('"');
// Only update when name is explicitly skipped, otherwise stack is not updated anyways
if (count == 0) {
pathNames[stackSize - 1] = "<skipped>";
}
break;
case PEEKED_NUMBER:
pos += peekedNumberLength;
break;
case PEEKED_EOF:
// Do nothing
return;
default:
// For all other tokens there is nothing to do; token has already been consumed from
// underlying reader
}
peeked = PEEKED_NONE;
} while (count > 0);
pathIndices[stackSize - 1]++;
} | @Test
public void testStrictNonExecutePrefixWithSkipValue() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
var e = assertThrows(MalformedJsonException.class, () -> reader.skipValue());
assertStrictError(e, "line 1 column 1 path $");
} |
@Override
public boolean releaseTaskManager(ResourceID taskManagerId, Exception cause) {
assertHasBeenStarted();
if (registeredTaskManagers.remove(taskManagerId)) {
internalReleaseTaskManager(taskManagerId, cause);
return true;
}
return false;
} | @Test
void testReleaseTaskManager() throws Exception {
try (DeclarativeSlotPoolService declarativeSlotPoolService =
createDeclarativeSlotPoolService()) {
final ResourceID knownTaskManager = ResourceID.generate();
declarativeSlotPoolService.registerTaskManager(knownTaskManager);
declarativeSlotPoolService.releaseTaskManager(
knownTaskManager, new FlinkException("Test cause"));
assertThat(
declarativeSlotPoolService.isTaskManagerRegistered(
knownTaskManager.getResourceID()))
.isFalse();
}
} |
@Override
public Database getDb(String name) {
ConnectorMetadata metadata = metadataOfDb(name);
return metadata.getDb(name);
} | @Test
void testGetDb(@Mocked ConnectorMetadata connectorMetadata) {
new Expectations() {
{
connectorMetadata.getDb("test_db");
result = null;
times = 1;
}
};
CatalogConnectorMetadata catalogConnectorMetadata = new CatalogConnectorMetadata(
connectorMetadata,
informationSchemaMetadata,
metaMetadata
);
Database db = catalogConnectorMetadata.getDb("test_db");
assertNull(db);
assertNotNull(catalogConnectorMetadata.getDb(InfoSchemaDb.DATABASE_NAME));
} |
public static long producerRecordSizeInBytes(final ProducerRecord<byte[], byte[]> record) {
return recordSizeInBytes(
record.key() == null ? 0 : record.key().length,
record.value() == null ? 0 : record.value().length,
record.topic(),
record.headers()
);
} | @Test
public void shouldComputeSizeInBytesForProducerRecordWithNullValue() {
final ProducerRecord<byte[], byte[]> record = new ProducerRecord<>(
TOPIC,
1,
0L,
KEY,
null,
HEADERS
);
assertThat(producerRecordSizeInBytes(record), equalTo(TOMBSTONE_SIZE_IN_BYTES));
} |
public static long checkPositive(long n, String name)
{
if (n <= 0)
{
throw new IllegalArgumentException(name + ": " + n + " (expected: > 0)");
}
return n;
} | @Test(expected = IllegalArgumentException.class)
public void checkPositiveMustFailIfArgumentIsZero()
{
RangeUtil.checkPositive(0, "var");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.