focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public void updateConfig(ConfigSaveReqVO updateReqVO) {
// 校验自己存在
validateConfigExists(updateReqVO.getId());
// 校验参数配置 key 的唯一性
validateConfigKeyUnique(updateReqVO.getId(), updateReqVO.getKey());
// 更新参数配置
ConfigDO updateObj = ConfigConvert.INSTANCE.convert(updateReqVO);
configMapper.updateById(updateObj);
} | @Test
public void testUpdateConfig_success() {
// mock 数据
ConfigDO dbConfig = randomConfigDO();
configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据
// 准备参数
ConfigSaveReqVO reqVO = randomPojo(ConfigSaveReqVO.class, o -> {
o.setId(dbConfig.getId()); // 设置更新的 ID
});
// 调用
configService.updateConfig(reqVO);
// 校验是否更新正确
ConfigDO config = configMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, config);
} |
@Deprecated
public String createToken(Authentication authentication) {
return createToken(authentication.getName());
} | @Test
void testInvalidSecretKey() {
assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE"));
} |
public long stamp() {
long s = stamp;
if (s == 0) {
s = calculateStamp(partitions);
stamp = s;
}
return s;
} | @Test
public void test_getStamp() throws Exception {
InternalPartition[] partitions = createRandomPartitions();
PartitionTableView table = new PartitionTableView(partitions);
assertEquals(calculateStamp(partitions), table.stamp());
} |
public void updateConfig(DynamicConfigEvent event) {
if (!isTargetConfig(event)) {
return;
}
if (updateWithDefaultMode(event)) {
afterUpdateConfig();
}
} | @Test
public void testRegistrySwitchConfig() {
RegistryConfigResolver configResolver = new OriginRegistrySwitchConfigResolver();
final DynamicConfigEvent event = Mockito.mock(DynamicConfigEvent.class);
Mockito.when(event.getContent()).thenReturn("origin.__registry__.needClose: true");
Mockito.when(event.getKey()).thenReturn("sermant.agent.registry");
configResolver.updateConfig(event);
final RegisterDynamicConfig config = config(configResolver, RegisterDynamicConfig.class);
Assert.assertTrue(config.isNeedCloseOriginRegisterCenter());
} |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
@Override
public ClusterInfo get() {
return getClusterInfo();
} | @Test
public void testInfoSlash() throws JSONException, Exception {
// test with trailing "/" to make sure acts same as without slash
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("info/").accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
response.getType().toString());
JSONObject json = response.getEntity(JSONObject.class);
verifyClusterInfo(json);
} |
public static void verifyKafkaBrokers(Properties props) {
//ensure bootstrap.servers is assigned
String brokerList = getString(BOOTSTRAP_SERVERS_CONFIG, props); //usually = "bootstrap.servers"
String[] brokers = brokerList.split(",");
for (String broker : brokers) {
checkArgument(
broker.contains(":"),
"Proper broker formatting requires a \":\" between the host and the port (input=" + broker + ")"
);
String host = broker.substring(0, broker.indexOf(":")); //we could validate the host is we wanted to
String port = broker.substring(broker.indexOf(":") + 1);
parseInt(port);//every port should be an integer
}
} | @Test
public void verifyKafkaBrokers_noPort() {
Properties props = new Properties();
props.setProperty("bootstrap.servers", "localhost");
assertThrows(
IllegalArgumentException.class,
() -> verifyKafkaBrokers(props)
);
} |
@Override
public SmsTemplateDO getSmsTemplate(Long id) {
return smsTemplateMapper.selectById(id);
} | @Test
public void testGetSmsTemplate() {
// mock 数据
SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO();
smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbSmsTemplate.getId();
// 调用
SmsTemplateDO smsTemplate = smsTemplateService.getSmsTemplate(id);
// 校验
assertPojoEquals(dbSmsTemplate, smsTemplate);
} |
Image getIcon(String pluginId) {
return getVersionedElasticAgentExtension(pluginId).getIcon(pluginId);
} | @Test
public void shouldCallTheVersionedExtensionBasedOnResolvedVersion() {
when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ELASTIC_AGENT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success("{\"content_type\":\"image/png\",\"data\":\"Zm9vYmEK\"}"));
extension.getIcon(PLUGIN_ID);
assertExtensionRequest("4.0", REQUEST_GET_PLUGIN_SETTINGS_ICON, null);
} |
public Optional<String> evaluate(Number toEvaluate) {
return interval.isIn(toEvaluate) ? Optional.of(binValue) : Optional.empty();
} | @Test
void evaluateClosedClosed() {
KiePMMLDiscretizeBin kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(null, 20,
CLOSURE.CLOSED_CLOSED));
Optional<String> retrieved = kiePMMLDiscretizeBin.evaluate(10);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(20);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(30);
assertThat(retrieved).isNotPresent();
kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(20, null, CLOSURE.CLOSED_CLOSED));
retrieved = kiePMMLDiscretizeBin.evaluate(30);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(20);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(10);
assertThat(retrieved).isNotPresent();
kiePMMLDiscretizeBin = getKiePMMLDiscretizeBin(new KiePMMLInterval(20, 40, CLOSURE.CLOSED_CLOSED));
retrieved = kiePMMLDiscretizeBin.evaluate(30);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(10);
assertThat(retrieved).isNotPresent();
retrieved = kiePMMLDiscretizeBin.evaluate(20);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(40);
assertThat(retrieved).isPresent();
assertThat(retrieved.get()).isEqualTo(BINVALUE);
retrieved = kiePMMLDiscretizeBin.evaluate(50);
assertThat(retrieved).isNotPresent();
} |
public void checkExistsName(final String name) {
if (baseballTeamRepository.existsByNameIn(List.of(name))) {
throw new DuplicateTeamNameException();
}
} | @Test
void 이미_존재하는_이름의_구단을_중복_저장할_수_없다() {
// given
String duplicateName = "두산 베어스";
// when
// then
assertThatThrownBy(() -> createBaseballTeamService.checkExistsName(duplicateName))
.isInstanceOf(DuplicateTeamNameException.class);
} |
public static <R> R callStaticMethod(
ClassLoader classLoader,
String fullyQualifiedClassName,
String methodName,
ClassParameter<?>... classParameters) {
Class<?> clazz = loadClass(classLoader, fullyQualifiedClassName);
return callStaticMethod(clazz, methodName, classParameters);
} | @Test
public void callStaticMethodReflectively_wrapsCheckedException() {
try {
ReflectionHelpers.callStaticMethod(ExampleDescendant.class, "staticThrowCheckedException");
fail("Expected exception not thrown");
} catch (RuntimeException e) {
assertThat(e.getCause()).isInstanceOf(TestException.class);
}
} |
@Override
public Optional<IndexSetConfig> findOne(DBQuery.Query query) {
return Optional.ofNullable(collection.findOne(query));
} | @Test
@MongoDBFixtures("MongoIndexSetServiceTest.json")
public void findOne() throws Exception {
final Optional<IndexSetConfig> config3 = indexSetService.findOne(DBQuery.is("title", "Test 2"));
assertThat(config3).isPresent();
assertThat(config3.get().id()).isEqualTo("57f3d721a43c2d59cb750002");
final Optional<IndexSetConfig> config4 = indexSetService.findOne(DBQuery.is("title", "__yolo"));
assertThat(config4).isNotPresent();
} |
public static long getLastModified(URL resourceURL) {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final JarEntry entry = jarConnection.getJarEntry();
return entry.getTime();
} catch (IOException ignored) {
}
return 0;
case "file":
URLConnection connection = null;
try {
connection = resourceURL.openConnection();
return connection.getLastModified();
} catch (IOException ignored) {
} finally {
if (connection != null) {
try {
connection.getInputStream().close();
} catch (IOException ignored) {
}
}
}
return 0;
default:
throw new IllegalArgumentException("Unsupported protocol " + protocol + " for resource " + resourceURL);
}
} | @Test
void getLastModifiedReturnsTheLastModifiedTimeOfAFile(@TempDir Path tempDir) throws Exception {
final URL url = tempDir.toUri().toURL();
final long lastModified = ResourceURL.getLastModified(url);
assertThat(lastModified)
.isPositive()
.isEqualTo(tempDir.toFile().lastModified());
} |
public NugetPackage parse(InputStream stream) throws NuspecParseException {
try {
final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder();
final Document d = db.parse(stream);
final XPath xpath = XPathFactory.newInstance().newXPath();
final NugetPackage nuspec = new NugetPackage();
if (xpath.evaluate("/package/metadata/id", d, XPathConstants.NODE) == null
|| xpath.evaluate("/package/metadata/version", d, XPathConstants.NODE) == null
|| xpath.evaluate("/package/metadata/authors", d, XPathConstants.NODE) == null
|| xpath.evaluate("/package/metadata/description", d, XPathConstants.NODE) == null) {
throw new NuspecParseException("Invalid Nuspec format");
}
nuspec.setId(xpath.evaluate("/package/metadata/id", d));
nuspec.setVersion(xpath.evaluate("/package/metadata/version", d));
nuspec.setAuthors(xpath.evaluate("/package/metadata/authors", d));
nuspec.setOwners(getOrNull((Node) xpath.evaluate("/package/metadata/owners", d, XPathConstants.NODE)));
nuspec.setLicenseUrl(getOrNull((Node) xpath.evaluate("/package/metadata/licenseUrl", d, XPathConstants.NODE)));
nuspec.setTitle(getOrNull((Node) xpath.evaluate("/package/metadata/title", d, XPathConstants.NODE)));
nuspec.setDescription(xpath.evaluate("/package/metadata/description", d));
return nuspec;
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | NuspecParseException e) {
throw new NuspecParseException("Unable to parse nuspec", e);
}
} | @Test(expected = NuspecParseException.class)
public void testMissingDocument() throws Exception {
XPathNuspecParser parser = new XPathNuspecParser();
//InputStream is = XPathNuspecParserTest.class.getClassLoader().getResourceAsStream("dependencycheck.properties");
InputStream is = BaseTest.getResourceAsStream(this, "dependencycheck.properties");
//hide the fatal message from the core parser
final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
System.setErr(new PrintStream(myOut));
parser.parse(is);
} |
public final void isAtLeast(int other) {
asDouble.isAtLeast(other);
} | @Test
public void isAtLeast_int() {
expectFailureWhenTestingThat(2.0f).isAtLeast(3);
assertThat(2.0f).isAtLeast(2);
assertThat(2.0f).isAtLeast(1);
} |
public void createDir(File dir) {
Path dirPath = requireNonNull(dir, "dir can not be null").toPath();
if (dirPath.toFile().exists()) {
checkState(dirPath.toFile().isDirectory(), "%s is not a directory", dirPath);
} else {
try {
createDirectories(dirPath);
} catch (IOException e) {
throw new IllegalStateException(format("Failed to create directory %s", dirPath), e);
}
}
} | @Test
public void createDir_creates_specified_directory() throws IOException {
File dir = new File(temp.newFolder(), "someDir");
assertThat(dir).doesNotExist();
underTest.createDir(dir);
assertThat(dir).exists();
} |
public static <T, R> R unaryCall(Invoker<?> invoker, MethodDescriptor methodDescriptor, T request) {
return (R) call(invoker, methodDescriptor, new Object[] {request});
} | @Test
void testUnaryCall() throws Throwable {
when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> result);
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<Object> atomicReference = new AtomicReference<>();
StreamObserver<Object> responseObserver = new StreamObserver<Object>() {
@Override
public void onNext(Object data) {
atomicReference.set(data);
}
@Override
public void onError(Throwable throwable) {}
@Override
public void onCompleted() {
latch.countDown();
}
};
StubInvocationUtil.unaryCall(invoker, method, request, responseObserver);
latch.await(1, TimeUnit.SECONDS);
Assertions.assertEquals(response, atomicReference.get());
} |
@Udf
public List<String> keys(@UdfParameter final String jsonObj) {
if (jsonObj == null) {
return null;
}
final JsonNode node = UdfJsonMapper.parseJson(jsonObj);
if (node.isMissingNode() || !node.isObject()) {
return null;
}
final List<String> ret = new ArrayList<>();
node.fieldNames().forEachRemaining(ret::add);
return ret;
} | @Test
public void shouldReturnKeysForEmptyObject() {
// When:
final List<String> result = udf.keys("{}");
// Then:
assertEquals(Collections.emptyList(), result);
} |
public long getMsgOutCounter() {
return msgOutFromRemovedConsumer.longValue() + sumConsumers(Consumer::getMsgOutCounter);
} | @Test
public void testGetMsgOutCounter() {
subscription.msgOutFromRemovedConsumer.add(1L);
when(consumer.getMsgOutCounter()).thenReturn(2L);
assertEquals(subscription.getMsgOutCounter(), 3L);
} |
@Override
protected <R> EurekaHttpResponse<R> execute(RequestExecutor<R> requestExecutor) {
List<EurekaEndpoint> candidateHosts = null;
int endpointIdx = 0;
for (int retry = 0; retry < numberOfRetries; retry++) {
EurekaHttpClient currentHttpClient = delegate.get();
EurekaEndpoint currentEndpoint = null;
if (currentHttpClient == null) {
if (candidateHosts == null) {
candidateHosts = getHostCandidates();
if (candidateHosts.isEmpty()) {
throw new TransportException("There is no known eureka server; cluster server list is empty");
}
}
if (endpointIdx >= candidateHosts.size()) {
throw new TransportException("Cannot execute request on any known server");
}
currentEndpoint = candidateHosts.get(endpointIdx++);
currentHttpClient = clientFactory.newClient(currentEndpoint);
}
try {
EurekaHttpResponse<R> response = requestExecutor.execute(currentHttpClient);
if (serverStatusEvaluator.accept(response.getStatusCode(), requestExecutor.getRequestType())) {
delegate.set(currentHttpClient);
if (retry > 0) {
logger.info("Request execution succeeded on retry #{}", retry);
}
return response;
}
logger.warn("Request execution failure with status code {}; retrying on another server if available", response.getStatusCode());
} catch (Exception e) {
logger.warn("Request execution failed with message: {}", e.getMessage()); // just log message as the underlying client should log the stacktrace
}
// Connection error or 5xx from the server that must be retried on another server
delegate.compareAndSet(currentHttpClient, null);
if (currentEndpoint != null) {
quarantineSet.add(currentEndpoint);
}
}
throw new TransportException("Retry limit reached; giving up on completing the request");
} | @Test(expected = TransportException.class)
public void testErrorResponseIsReturnedIfRetryLimitIsReached() throws Exception {
simulateTransportError(0, NUMBER_OF_RETRIES + 1);
retryableClient.execute(requestExecutor);
} |
public ProjectStatusResponse.ProjectStatus format() {
if (!optionalMeasureData.isPresent()) {
return newResponseWithoutQualityGateDetails();
}
JsonObject json = JsonParser.parseString(optionalMeasureData.get()).getAsJsonObject();
ProjectStatusResponse.Status qualityGateStatus = measureLevelToQualityGateStatus(json.get("level").getAsString());
projectStatusBuilder.setStatus(qualityGateStatus);
projectStatusBuilder.setCaycStatus(caycStatus.toString());
formatIgnoredConditions(json);
formatConditions(json.getAsJsonArray("conditions"));
formatPeriods();
return projectStatusBuilder.build();
} | @Test
public void ignore_period_not_set_on_leak_period() throws IOException {
String measureData = IOUtils.toString(getClass().getResource("QualityGateDetailsFormatterTest/non_leak_period.json"));
SnapshotDto snapshot = new SnapshotDto()
.setPeriodMode("last_version")
.setPeriodParam("2015-12-07")
.setPeriodDate(1449404331764L);
underTest = newQualityGateDetailsFormatter(measureData, snapshot);
ProjectStatus result = underTest.format();
// check conditions
assertThat(result.getConditionsCount()).isOne();
List<ProjectStatusResponse.Condition> conditions = result.getConditionsList();
assertThat(conditions).extracting("status").containsExactly(ProjectStatusResponse.Status.ERROR);
assertThat(conditions).extracting("metricKey").containsExactly("new_coverage");
assertThat(conditions).extracting("comparator").containsExactly(ProjectStatusResponse.Comparator.LT);
assertThat(conditions).extracting("errorThreshold").containsOnly("85");
assertThat(conditions).extracting("actualValue").containsExactly("82.2985024398452");
} |
public boolean includes(String ipAddress) {
if (all) {
return true;
}
if (ipAddress == null) {
throw new IllegalArgumentException("ipAddress is null.");
}
try {
return includes(addressFactory.getByName(ipAddress));
} catch (UnknownHostException e) {
return false;
}
} | @Test
public void testIPList() {
//create MachineList with a list of of IPs
MachineList ml = new MachineList(IP_LIST, new TestAddressFactory());
//test for inclusion with an known IP
assertTrue(ml.includes("10.119.103.112"));
//test for exclusion with an unknown IP
assertFalse(ml.includes("10.119.103.111"));
} |
public static String[] getAllValueMetaNames() {
List<String> strings = new ArrayList<String>();
List<PluginInterface> plugins = pluginRegistry.getPlugins( ValueMetaPluginType.class );
for ( PluginInterface plugin : plugins ) {
String id = plugin.getIds()[0];
if ( !( "0".equals( id ) ) ) {
strings.add( plugin.getName() );
}
}
return strings.toArray( new String[strings.size()] );
} | @Test
public void testGetAllValueMetaNames() {
List<String> dataTypes = Arrays.<String>asList( ValueMetaFactory.getAllValueMetaNames() );
assertTrue( dataTypes.contains( "Number" ) );
assertTrue( dataTypes.contains( "String" ) );
assertTrue( dataTypes.contains( "Date" ) );
assertTrue( dataTypes.contains( "Boolean" ) );
assertTrue( dataTypes.contains( "Integer" ) );
assertTrue( dataTypes.contains( "BigNumber" ) );
assertTrue( dataTypes.contains( "Serializable" ) );
assertTrue( dataTypes.contains( "Binary" ) );
assertTrue( dataTypes.contains( "Timestamp" ) );
assertTrue( dataTypes.contains( "Internet Address" ) );
} |
@Override
public void close() throws IOException {
throw new UnsupportedOperationException(
"Caller does not own the underlying output stream " + " and should not call close().");
} | @Test
public void testClosingThrows() throws Exception {
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Caller does not own the underlying");
os.close();
} |
@Override
public void shutdown() {
delegate.shutdown();
} | @Test
public void shutdown() {
underTest.shutdown();
verify(executorService).shutdown();
} |
public void skipReserved(final int length) {
byteBuf.skipBytes(length);
} | @Test
void assertSkipReserved() {
new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).skipReserved(10);
verify(byteBuf).skipBytes(10);
} |
public static boolean equals(String left, String right) {
Slime leftSlime = SlimeUtils.jsonToSlimeOrThrow(left);
Slime rightSlime = SlimeUtils.jsonToSlimeOrThrow(right);
return leftSlime.equalTo(rightSlime);
} | @Test
public void implementationSpecificEqualsBehavior() {
// Exception thrown if outside a long
assertTrue( JSON.equals("{\"a\": 9223372036854775807}", "{\"a\": 9223372036854775807}"));
assertRuntimeException(() -> JSON.equals("{\"a\": 9223372036854775808}", "{\"a\": 9223372036854775808}"));
// Infinity if floating point number outside of double, and hence equal
assertTrue(JSON.equals("{\"a\": 2.7976931348623158e+308}", "{\"a\": 2.7976931348623158e+308}"));
// Ignores extraneous precision
assertTrue(JSON.equals( "{\"e\": 2.7182818284590452354}",
"{\"e\": 2.7182818284590452354}"));
assertTrue(JSON.equals( "{\"e\": 2.7182818284590452354}",
"{\"e\": 2.7182818284590452355}"));
assertFalse(JSON.equals("{\"e\": 2.7182818284590452354}",
"{\"e\": 2.71828182845904}"));
// Comparing equal but syntactically different numbers
assertFalse(JSON.equals("{\"a\": 1.0}", "{\"a\":1}"));
assertTrue(JSON.equals("{\"a\": 1.0}", "{\"a\":1.00}"));
assertTrue(JSON.equals("{\"a\": 1.0}", "{\"a\":1.0000000000000000000000000000}"));
assertTrue(JSON.equals("{\"a\": 10.0}", "{\"a\":1e1}"));
assertTrue(JSON.equals("{\"a\": 1.2}", "{\"a\":12e-1}"));
} |
@Override
public Optional<ScmInfo> getScmInfo(Component component) {
requireNonNull(component, "Component cannot be null");
if (component.getType() != Component.Type.FILE) {
return Optional.empty();
}
return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent);
} | @Test
public void read_from_DB_if_no_report_and_file_unchanged() {
createDbScmInfoWithOneLine();
when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true);
// should clear revision and author
ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get();
assertThat(scmInfo.getAllChangesets()).hasSize(1);
assertChangeset(scmInfo.getChangesetForLine(1), null, null, 10L);
verify(fileStatuses).isUnchanged(FILE_SAME);
verify(dbLoader).getScmInfo(FILE_SAME);
verifyNoMoreInteractions(dbLoader);
verifyNoMoreInteractions(fileStatuses);
verifyNoInteractions(diff);
} |
@Override
public RefreshSuperUserGroupsConfigurationResponse refreshSuperUserGroupsConfiguration(
RefreshSuperUserGroupsConfigurationRequest request)
throws StandbyException, YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrRefreshSuperUserGroupsConfigurationFailedRetrieved();
RouterServerUtil.logAndThrowException("Missing RefreshSuperUserGroupsConfiguration request.",
null);
}
// call refreshSuperUserGroupsConfiguration of activeSubClusters.
try {
long startTime = clock.getTime();
RMAdminProtocolMethod remoteMethod = new RMAdminProtocolMethod(
new Class[] {RefreshSuperUserGroupsConfigurationRequest.class}, new Object[] {request});
String subClusterId = request.getSubClusterId();
Collection<RefreshSuperUserGroupsConfigurationResponse> refreshSuperUserGroupsConfResps =
remoteMethod.invokeConcurrent(this, RefreshSuperUserGroupsConfigurationResponse.class,
subClusterId);
if (CollectionUtils.isNotEmpty(refreshSuperUserGroupsConfResps)) {
long stopTime = clock.getTime();
routerMetrics.succeededRefreshSuperUserGroupsConfRetrieved(stopTime - startTime);
return RefreshSuperUserGroupsConfigurationResponse.newInstance();
}
} catch (YarnException e) {
routerMetrics.incrRefreshSuperUserGroupsConfigurationFailedRetrieved();
RouterServerUtil.logAndThrowException(e,
"Unable to refreshSuperUserGroupsConfiguration due to exception. " + e.getMessage());
}
routerMetrics.incrRefreshSuperUserGroupsConfigurationFailedRetrieved();
throw new YarnException("Unable to refreshSuperUserGroupsConfiguration.");
} | @Test
public void testRefreshSuperUserGroupsConfiguration() throws Exception {
// null request.
LambdaTestUtils.intercept(YarnException.class,
"Missing RefreshSuperUserGroupsConfiguration request.",
() -> interceptor.refreshSuperUserGroupsConfiguration(null));
// normal request.
// There is no return information defined in RefreshSuperUserGroupsConfigurationResponse,
// as long as it is not empty, it means that the command is successfully executed.
RefreshSuperUserGroupsConfigurationRequest request =
RefreshSuperUserGroupsConfigurationRequest.newInstance();
RefreshSuperUserGroupsConfigurationResponse response =
interceptor.refreshSuperUserGroupsConfiguration(request);
assertNotNull(response);
} |
@Override
protected CouchbaseEndpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
CouchbaseEndpoint endpoint = new CouchbaseEndpoint(uri, remaining, this);
setProperties(endpoint, parameters);
return endpoint;
} | @Test
public void testEndpointCreated() throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("bucket", "bucket");
String uri = "couchbase:http://localhost:9191?bucket=bucket";
String remaining = "http://localhost:9191";
CouchbaseEndpoint endpoint = component.createEndpoint(uri, remaining, params);
assertNotNull(endpoint);
} |
public List<LineageRel> analyzeLineage(String statement) {
// 1. Generate original relNode tree
Tuple2<String, RelNode> parsed = parseStatement(statement);
String sinkTable = parsed.getField(0);
RelNode oriRelNode = parsed.getField(1);
// 2. Build lineage based from RelMetadataQuery
return buildFiledLineageResult(sinkTable, oriRelNode);
} | @Test
public void testAnalyzeLineage() {
String sql = "INSERT INTO TT SELECT a||c A ,b||c B FROM ST";
String[][] expectedArray = {
{"ST", "a", "TT", "A", "||(a, c)"},
{"ST", "c", "TT", "A", "||(a, c)"},
{"ST", "b", "TT", "B", "||(b, c)"},
{"ST", "c", "TT", "B", "||(b, c)"}
};
analyzeLineage(sql, expectedArray);
} |
@VisibleForTesting
static String getActualColumnName(String rawTableName, String columnName, @Nullable Map<String, String> columnNameMap,
boolean ignoreCase) {
if ("*".equals(columnName)) {
return columnName;
}
String columnNameToCheck = trimTableName(rawTableName, columnName, ignoreCase);
if (ignoreCase) {
columnNameToCheck = columnNameToCheck.toLowerCase();
}
if (columnNameMap != null) {
String actualColumnName = columnNameMap.get(columnNameToCheck);
if (actualColumnName != null) {
return actualColumnName;
}
}
if (columnName.charAt(0) == '$') {
return columnName;
}
throw new BadQueryRequestException("Unknown columnName '" + columnName + "' found in the query");
} | @Test
public void testGetActualColumnNameCaseInSensitive() {
Map<String, String> columnNameMap = new HashMap<>();
columnNameMap.put("student_name", "student_name");
String actualColumnName =
BaseSingleStageBrokerRequestHandler.getActualColumnName("mytable", "MYTABLE.student_name", columnNameMap, true);
Assert.assertEquals(actualColumnName, "student_name");
Assert.assertEquals(
BaseSingleStageBrokerRequestHandler.getActualColumnName("db1.MYTABLE", "DB1.mytable.student_name",
columnNameMap, true), "student_name");
Assert.assertEquals(
BaseSingleStageBrokerRequestHandler.getActualColumnName("db1.mytable", "MYTABLE.student_name", columnNameMap,
true), "student_name");
boolean exceptionThrown = false;
try {
BaseSingleStageBrokerRequestHandler.getActualColumnName("student", "MYTABLE2.student_name", columnNameMap, true);
Assert.fail("should throw exception if column is not known");
} catch (BadQueryRequestException ex) {
exceptionThrown = true;
}
Assert.assertTrue(exceptionThrown, "should throw exception if column is not known");
columnNameMap.put("mytable_student_name", "mytable_student_name");
String wrongColumnName2 =
BaseSingleStageBrokerRequestHandler.getActualColumnName("mytable", "MYTABLE_student_name", columnNameMap, true);
Assert.assertEquals(wrongColumnName2, "mytable_student_name");
columnNameMap.put("mytable", "mytable");
String wrongColumnName3 =
BaseSingleStageBrokerRequestHandler.getActualColumnName("MYTABLE", "mytable", columnNameMap, true);
Assert.assertEquals(wrongColumnName3, "mytable");
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefine.getDefaultValue())
.comment(typeDefine.getComment());
String sqlServerType = typeDefine.getDataType().toUpperCase();
switch (sqlServerType) {
case SQLSERVER_BIT:
builder.sourceType(SQLSERVER_BIT);
builder.dataType(BasicType.BOOLEAN_TYPE);
break;
case SQLSERVER_TINYINT:
case SQLSERVER_TINYINT_IDENTITY:
builder.sourceType(SQLSERVER_TINYINT);
builder.dataType(BasicType.SHORT_TYPE);
break;
case SQLSERVER_SMALLINT:
case SQLSERVER_SMALLINT_IDENTITY:
builder.sourceType(SQLSERVER_SMALLINT);
builder.dataType(BasicType.SHORT_TYPE);
break;
case SQLSERVER_INTEGER:
case SQLSERVER_INTEGER_IDENTITY:
case SQLSERVER_INT:
case SQLSERVER_INT_IDENTITY:
builder.sourceType(SQLSERVER_INT);
builder.dataType(BasicType.INT_TYPE);
break;
case SQLSERVER_BIGINT:
case SQLSERVER_BIGINT_IDENTITY:
builder.sourceType(SQLSERVER_BIGINT);
builder.dataType(BasicType.LONG_TYPE);
break;
case SQLSERVER_REAL:
builder.sourceType(SQLSERVER_REAL);
builder.dataType(BasicType.FLOAT_TYPE);
break;
case SQLSERVER_FLOAT:
if (typeDefine.getPrecision() != null && typeDefine.getPrecision() <= 24) {
builder.sourceType(SQLSERVER_REAL);
builder.dataType(BasicType.FLOAT_TYPE);
} else {
builder.sourceType(SQLSERVER_FLOAT);
builder.dataType(BasicType.DOUBLE_TYPE);
}
break;
case SQLSERVER_DECIMAL:
case SQLSERVER_NUMERIC:
builder.sourceType(
String.format(
"%s(%s,%s)",
SQLSERVER_DECIMAL,
typeDefine.getPrecision(),
typeDefine.getScale()));
builder.dataType(
new DecimalType(
typeDefine.getPrecision().intValue(), typeDefine.getScale()));
builder.columnLength(typeDefine.getPrecision());
builder.scale(typeDefine.getScale());
break;
case SQLSERVER_MONEY:
builder.sourceType(SQLSERVER_MONEY);
builder.dataType(
new DecimalType(
typeDefine.getPrecision().intValue(), typeDefine.getScale()));
builder.columnLength(typeDefine.getPrecision());
builder.scale(typeDefine.getScale());
break;
case SQLSERVER_SMALLMONEY:
builder.sourceType(SQLSERVER_SMALLMONEY);
builder.dataType(
new DecimalType(
typeDefine.getPrecision().intValue(), typeDefine.getScale()));
builder.columnLength(typeDefine.getPrecision());
builder.scale(typeDefine.getScale());
break;
case SQLSERVER_CHAR:
builder.sourceType(String.format("%s(%s)", SQLSERVER_CHAR, typeDefine.getLength()));
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(
TypeDefineUtils.doubleByteTo4ByteLength(typeDefine.getLength()));
break;
case SQLSERVER_NCHAR:
builder.sourceType(
String.format("%s(%s)", SQLSERVER_NCHAR, typeDefine.getLength()));
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(
TypeDefineUtils.doubleByteTo4ByteLength(typeDefine.getLength()));
break;
case SQLSERVER_VARCHAR:
if (typeDefine.getLength() == -1) {
builder.sourceType(MAX_VARCHAR);
builder.columnLength(TypeDefineUtils.doubleByteTo4ByteLength(POWER_2_31 - 1));
} else {
builder.sourceType(
String.format("%s(%s)", SQLSERVER_VARCHAR, typeDefine.getLength()));
builder.columnLength(
TypeDefineUtils.doubleByteTo4ByteLength(typeDefine.getLength()));
}
builder.dataType(BasicType.STRING_TYPE);
break;
case SQLSERVER_NVARCHAR:
if (typeDefine.getLength() == -1) {
builder.sourceType(MAX_NVARCHAR);
builder.columnLength(TypeDefineUtils.doubleByteTo4ByteLength(POWER_2_31 - 1));
} else {
builder.sourceType(
String.format("%s(%s)", SQLSERVER_NVARCHAR, typeDefine.getLength()));
builder.columnLength(
TypeDefineUtils.doubleByteTo4ByteLength(typeDefine.getLength()));
}
builder.dataType(BasicType.STRING_TYPE);
break;
case SQLSERVER_TEXT:
builder.sourceType(SQLSERVER_TEXT);
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(POWER_2_31 - 1);
break;
case SQLSERVER_NTEXT:
builder.sourceType(SQLSERVER_NTEXT);
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(POWER_2_30 - 1);
break;
case SQLSERVER_XML:
builder.sourceType(SQLSERVER_XML);
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(POWER_2_31 - 1);
break;
case SQLSERVER_UNIQUEIDENTIFIER:
builder.sourceType(SQLSERVER_UNIQUEIDENTIFIER);
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(TypeDefineUtils.charTo4ByteLength(typeDefine.getLength()));
break;
case SQLSERVER_SQLVARIANT:
builder.sourceType(SQLSERVER_SQLVARIANT);
builder.dataType(BasicType.STRING_TYPE);
builder.columnLength(typeDefine.getLength());
break;
case SQLSERVER_BINARY:
builder.sourceType(
String.format("%s(%s)", SQLSERVER_BINARY, typeDefine.getLength()));
builder.dataType(PrimitiveByteArrayType.INSTANCE);
builder.columnLength(typeDefine.getLength());
break;
case SQLSERVER_VARBINARY:
if (typeDefine.getLength() == -1) {
builder.sourceType(MAX_VARBINARY);
builder.columnLength(POWER_2_31 - 1);
} else {
builder.sourceType(
String.format("%s(%s)", SQLSERVER_VARBINARY, typeDefine.getLength()));
builder.columnLength(typeDefine.getLength());
}
builder.dataType(PrimitiveByteArrayType.INSTANCE);
break;
case SQLSERVER_IMAGE:
builder.sourceType(SQLSERVER_IMAGE);
builder.dataType(PrimitiveByteArrayType.INSTANCE);
builder.columnLength(POWER_2_31 - 1);
break;
case SQLSERVER_TIMESTAMP:
builder.sourceType(SQLSERVER_TIMESTAMP);
builder.dataType(PrimitiveByteArrayType.INSTANCE);
builder.columnLength(8L);
break;
case SQLSERVER_DATE:
builder.sourceType(SQLSERVER_DATE);
builder.dataType(LocalTimeType.LOCAL_DATE_TYPE);
break;
case SQLSERVER_TIME:
builder.sourceType(String.format("%s(%s)", SQLSERVER_TIME, typeDefine.getScale()));
builder.dataType(LocalTimeType.LOCAL_TIME_TYPE);
builder.scale(typeDefine.getScale());
break;
case SQLSERVER_DATETIME:
builder.sourceType(SQLSERVER_DATETIME);
builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE);
builder.scale(3);
break;
case SQLSERVER_DATETIME2:
builder.sourceType(
String.format("%s(%s)", SQLSERVER_DATETIME2, typeDefine.getScale()));
builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE);
builder.scale(typeDefine.getScale());
break;
case SQLSERVER_DATETIMEOFFSET:
builder.sourceType(
String.format("%s(%s)", SQLSERVER_DATETIMEOFFSET, typeDefine.getScale()));
builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE);
builder.scale(typeDefine.getScale());
break;
case SQLSERVER_SMALLDATETIME:
builder.sourceType(SQLSERVER_SMALLDATETIME);
builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE);
break;
default:
throw CommonError.convertToSeaTunnelTypeError(
DatabaseIdentifier.SQLSERVER, sqlServerType, typeDefine.getName());
}
return builder.build();
} | @Test
public void testConvertBigint() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder()
.name("test")
.columnType("bigint")
.dataType("bigint")
.build();
Column column = SqlServerTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), column.getName());
Assertions.assertEquals(BasicType.LONG_TYPE, column.getDataType());
Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType().toLowerCase());
} |
@Deprecated
public static Connection getConnection( LogChannelInterface log, DatabaseMeta dbMeta, String partitionId )
throws Exception {
DataSource ds = getDataSource( log, dbMeta, partitionId );
return ds.getConnection();
} | @Test
public void testGetConnection() throws Exception {
when( dbMeta.getName() ).thenReturn( "CP1" );
when( dbMeta.getPassword() ).thenReturn( PASSWORD );
when( dbMeta.getInitialPoolSize() ).thenReturn( 1 );
when( dbMeta.getMaximumPoolSize() ).thenReturn( 2 );
DataSource conn = ConnectionPoolUtil.getDataSource( logChannelInterface, dbMeta, "" );
assertNotNull( conn );
} |
@Override public Throwable error() {
return error;
} | @Test void error() {
assertThat(response.error()).isSameAs(error);
} |
@Override
public JobStatus getJobStatus() {
return JobStatus.RUNNING;
} | @Test
void testStateDoesNotExposeGloballyTerminalExecutionGraph() throws Exception {
try (MockExecutingContext ctx = new MockExecutingContext()) {
final FinishingMockExecutionGraph finishingMockExecutionGraph =
new FinishingMockExecutionGraph();
Executing executing =
new ExecutingStateBuilder()
.setExecutionGraph(finishingMockExecutionGraph)
.build(ctx);
// ideally we'd delay the async call to #onGloballyTerminalState instead, but the
// context does not support that
ctx.setExpectFinished(eg -> {});
finishingMockExecutionGraph.completeTerminationFuture(JobStatus.FINISHED);
// this is just a sanity check for the test
assertThat(executing.getExecutionGraph().getState()).isEqualTo(JobStatus.FINISHED);
assertThat(executing.getJobStatus()).isEqualTo(JobStatus.RUNNING);
assertThat(executing.getJob().getState()).isEqualTo(JobStatus.RUNNING);
assertThat(executing.getJob().getStatusTimestamp(JobStatus.FINISHED)).isZero();
}
} |
public <T extends ConnectionProvider<?>> List<String> getNamesByType( Class<T> providerClass ) {
List<String> detailNames = new ArrayList<>();
for ( ConnectionProvider<? extends ConnectionDetails> provider : getProvidersByType( providerClass ) ) {
List<String> names = getNames( provider );
if ( names != null) {
detailNames.addAll( names );
}
}
return detailNames;
} | @Test
public void testGetNamesByType() {
addOne();
List<String> names = connectionManager.getNamesByType( TestConnectionWithBucketsProvider.class );
assertEquals( 1, names.size() );
assertEquals( CONNECTION_NAME, names.get( 0 ) );
} |
@Override
public Collection<SQLToken> generateSQLTokens(final AlterTableStatementContext sqlStatementContext) {
String tableName = sqlStatementContext.getSqlStatement().getTable().getTableName().getIdentifier().getValue();
EncryptTable encryptTable = encryptRule.getEncryptTable(tableName);
Collection<SQLToken> result = new LinkedList<>(getAddColumnTokens(encryptTable, sqlStatementContext.getSqlStatement().getAddColumnDefinitions()));
result.addAll(getModifyColumnTokens(encryptTable, sqlStatementContext.getSqlStatement().getModifyColumnDefinitions()));
result.addAll(getChangeColumnTokens(encryptTable, sqlStatementContext.getSqlStatement().getChangeColumnDefinitions()));
List<SQLToken> dropColumnTokens = getDropColumnTokens(encryptTable, sqlStatementContext.getSqlStatement().getDropColumnDefinitions());
String databaseName = sqlStatementContext.getDatabaseType().getType();
if ("SQLServer".equals(databaseName)) {
result.addAll(mergeDropColumnStatement(dropColumnTokens, "", ""));
} else if ("Oracle".equals(databaseName)) {
result.addAll(mergeDropColumnStatement(dropColumnTokens, "(", ")"));
} else {
result.addAll(dropColumnTokens);
}
return result;
} | @Test
void assertAddColumnGenerateSQLTokens() {
Collection<SQLToken> actual = generator.generateSQLTokens(mockAddColumnStatementContext());
assertThat(actual.size(), is(4));
Iterator<SQLToken> actualIterator = actual.iterator();
assertThat(actualIterator.next(), instanceOf(RemoveToken.class));
EncryptColumnToken cipherToken = (EncryptColumnToken) actualIterator.next();
assertThat(cipherToken.toString(), is("cipher_certificate_number VARCHAR(4000)"));
assertThat(cipherToken.getStartIndex(), is(68));
assertThat(cipherToken.getStopIndex(), is(67));
EncryptColumnToken assistedToken = (EncryptColumnToken) actualIterator.next();
assertThat(assistedToken.toString(), is(", ADD COLUMN assisted_certificate_number VARCHAR(4000)"));
assertThat(assistedToken.getStartIndex(), is(68));
assertThat(assistedToken.getStopIndex(), is(67));
EncryptColumnToken likeToken = (EncryptColumnToken) actualIterator.next();
assertThat(likeToken.toString(), is(", ADD COLUMN like_certificate_number VARCHAR(4000)"));
assertThat(likeToken.getStartIndex(), is(68));
assertThat(likeToken.getStopIndex(), is(67));
} |
public static DynamicProtoCoder of(Descriptors.Descriptor protoMessageDescriptor) {
return new DynamicProtoCoder(
ProtoDomain.buildFrom(protoMessageDescriptor),
protoMessageDescriptor.getFullName(),
ImmutableSet.of());
} | @Test
public void testDynamicMessage() throws Exception {
DynamicMessage message =
DynamicMessage.newBuilder(MessageA.getDescriptor())
.setField(
MessageA.getDescriptor().findFieldByNumber(MessageA.FIELD1_FIELD_NUMBER), "foo")
.build();
Coder<DynamicMessage> coder = DynamicProtoCoder.of(message.getDescriptorForType());
// Special code to check the DynamicMessage equality (@see IsDynamicMessageEqual)
for (Coder.Context context : ALL_CONTEXTS) {
CoderProperties.coderDecodeEncodeInContext(
coder, context, message, IsDynamicMessageEqual.equalTo(message));
}
} |
CompletableFuture<Void> beginExecute(
@Nonnull List<? extends Tasklet> tasklets,
@Nonnull CompletableFuture<Void> cancellationFuture,
@Nonnull ClassLoader jobClassLoader
) {
final ExecutionTracker executionTracker = new ExecutionTracker(tasklets.size(), cancellationFuture);
try {
final Map<Boolean, List<Tasklet>> byCooperation =
tasklets.stream().collect(partitioningBy(
tasklet -> doWithClassLoader(jobClassLoader, tasklet::isCooperative)
));
submitCooperativeTasklets(executionTracker, jobClassLoader, byCooperation.get(true));
submitBlockingTasklets(executionTracker, jobClassLoader, byCooperation.get(false));
} catch (Throwable t) {
executionTracker.future.internalCompleteExceptionally(t);
}
return executionTracker.future;
} | @Test
public void when_blockingTaskletIsCancelled_then_completeEarly() {
// Given
final List<MockTasklet> tasklets =
Stream.generate(() -> new MockTasklet().blocking().callsBeforeDone(Integer.MAX_VALUE))
.limit(100).collect(toList());
// When
CompletableFuture<Void> f = tes.beginExecute(tasklets, cancellationFuture, classLoader);
cancellationFuture.cancel(true);
// Then
tasklets.forEach(MockTasklet::assertNotDone);
assertThrows(CancellationException.class, f::get);
} |
@VisibleForTesting
public static <ConfigT> ConfigT payloadToConfig(
ExternalConfigurationPayload payload, Class<ConfigT> configurationClass) {
try {
return payloadToConfigSchema(payload, configurationClass);
} catch (NoSuchSchemaException schemaException) {
LOG.warn(
"Configuration class '{}' has no schema registered. Attempting to construct with setter"
+ " approach.",
configurationClass.getName());
try {
return payloadToConfigSetters(payload, configurationClass);
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(
String.format(
"Failed to construct instance of configuration class '%s'",
configurationClass.getName()),
e);
}
}
} | @Test
public void testCompoundCodersForExternalConfiguration_schemas() throws Exception {
ExternalTransforms.ExternalConfigurationPayload externalConfig =
encodeRowIntoExternalConfigurationPayload(
Row.withSchema(
Schema.of(
Field.nullable("configKey1", FieldType.INT64),
Field.nullable("configKey2", FieldType.iterable(FieldType.BYTES)),
Field.of("configKey3", FieldType.map(FieldType.STRING, FieldType.INT64)),
Field.of(
"configKey4",
FieldType.map(FieldType.STRING, FieldType.array(FieldType.INT64)))))
.withFieldValue("configKey1", 1L)
.withFieldValue("configKey2", BYTE_LIST)
.withFieldValue("configKey3", BYTE_KV_LIST)
.withFieldValue("configKey4", BYTE_KV_LIST_WITH_LIST_VALUE)
.build());
TestConfigSchema config =
ExpansionService.payloadToConfig(externalConfig, TestConfigSchema.class);
assertThat(config.getConfigKey1(), Matchers.is(1L));
assertThat(config.getConfigKey2(), contains(BYTE_LIST.toArray()));
Map<String, Long> configKey3 = config.getConfigKey3();
assertThat(configKey3, is(notNullValue()));
// no-op for checker framework
if (configKey3 != null) {
assertThat(
configKey3.entrySet(),
containsInAnyOrder(
BYTE_KV_LIST.entrySet().stream()
.map(
(entry) ->
allOf(
hasProperty("key", equalTo(entry.getKey())),
hasProperty("value", equalTo(entry.getValue()))))
.collect(Collectors.toList())));
}
Map<String, List<Long>> configKey4 = config.getConfigKey4();
assertThat(configKey4, is(notNullValue()));
// no-op for checker framework
if (configKey4 != null) {
assertThat(
configKey4.entrySet(),
containsInAnyOrder(
BYTE_KV_LIST_WITH_LIST_VALUE.entrySet().stream()
.map(
(entry) ->
allOf(
hasProperty("key", equalTo(entry.getKey())),
hasProperty("value", equalTo(entry.getValue()))))
.collect(Collectors.toList())));
}
} |
public void init(ScannerReportWriter writer) {
File analysisLog = writer.getFileStructure().analysisLog();
try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) {
writePlugins(fileWriter);
writeBundledAnalyzers(fileWriter);
writeGlobalSettings(fileWriter);
writeProjectSettings(fileWriter);
writeModulesSettings(fileWriter);
} catch (IOException e) {
throw new IllegalStateException("Unable to write analysis log", e);
}
} | @Test
public void shouldNotDumpSensitiveGlobalProperties() throws Exception {
when(globalServerSettings.properties()).thenReturn(ImmutableMap.of("sonar.login", "my_token", "sonar.password", "azerty", "sonar.cpp.license.secured", "AZERTY"));
DefaultInputModule rootModule = new DefaultInputModule(ProjectDefinition.create()
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder())
.setProperty("sonar.projectKey", "foo"));
when(store.allModules()).thenReturn(singletonList(rootModule));
when(hierarchy.root()).thenReturn(rootModule);
publisher.init(writer);
assertThat(FileUtils.readFileToString(writer.getFileStructure().analysisLog(), StandardCharsets.UTF_8)).containsSubsequence(
"sonar.cpp.license.secured=******",
"sonar.login=******",
"sonar.password=******");
} |
public static synchronized void wtf(final String tag, String text, Object... args) {
if (msLogger.supportsWTF()) {
String msg = getFormattedString(text, args);
addLog(LVL_WTF, tag, msg);
msLogger.wtf(tag, msg);
}
} | @Test
public void testWtf() throws Exception {
Logger.wtf("mTag", "Text with %d digits", 0);
Mockito.verify(mMockLog).wtf("mTag", "Text with 0 digits");
Logger.wtf("mTag", "Text with no digits");
Mockito.verify(mMockLog).wtf("mTag", "Text with no digits");
} |
@Override
public void populateContainer(MigrationContainer container) {
container.add(executorType);
populateFromMigrationSteps(container);
} | @Test
public void populateContainer_adds_MigrationStepsExecutorImpl() {
when(migrationSteps.readAll()).thenReturn(emptyList());
// add MigrationStepsExecutorImpl's dependencies
migrationContainer.add(mock(MigrationHistory.class));
migrationContainer.add(mock(MutableDatabaseMigrationState.class));
migrationContainer.add(mock(TelemetryDbMigrationStepsProvider.class));
migrationContainer.add(mock(TelemetryDbMigrationTotalTimeProvider.class));
migrationContainer.add(mock(TelemetryDbMigrationSuccessProvider.class));
migrationContainer.startComponents();
underTest.populateContainer(migrationContainer);
assertThat(migrationContainer.getComponentByType(MigrationStepsExecutorImpl.class)).isNotNull();
} |
public Future<KafkaVersionChange> reconcile() {
return getVersionFromController()
.compose(i -> getPods())
.compose(this::detectToAndFromVersions)
.compose(i -> prepareVersionChange());
} | @Test
public void testNewClusterWithoutVersion(VertxTestContext context) {
VersionChangeCreator vcc = mockVersionChangeCreator(
mockKafka(null, null, null),
mockNewCluster(null, null, List.of())
);
Checkpoint async = context.checkpoint();
vcc.reconcile().onComplete(context.succeeding(c -> context.verify(() -> {
assertThat(c.from(), is(VERSIONS.defaultVersion()));
assertThat(c.to(), is(VERSIONS.defaultVersion()));
assertThat(c.interBrokerProtocolVersion(), is(VERSIONS.defaultVersion().protocolVersion()));
assertThat(c.logMessageFormatVersion(), is(VERSIONS.defaultVersion().messageVersion()));
assertThat(c.metadataVersion(), is(VERSIONS.defaultVersion().metadataVersion()));
async.flag();
})));
} |
@Override
public void start() throws Exception {
LOG.debug("Start leadership runner for job {}.", getJobID());
leaderElection.startLeaderElection(this);
} | @Test
void testJobMasterServiceLeadershipRunnerCloseWhenElectionServiceGrantLeaderShip()
throws Exception {
final AtomicReference<LeaderInformationRegister> storedLeaderInformation =
new AtomicReference<>(LeaderInformationRegister.empty());
final AtomicBoolean haBackendLeadershipFlag = new AtomicBoolean();
final TestingLeaderElectionDriver.Factory driverFactory =
new TestingLeaderElectionDriver.Factory(
TestingLeaderElectionDriver.newBuilder(
haBackendLeadershipFlag,
storedLeaderInformation,
new AtomicBoolean()));
// we need to use DefaultLeaderElectionService here because JobMasterServiceLeadershipRunner
// in connection with the DefaultLeaderElectionService generates the nested locking
final DefaultLeaderElectionService defaultLeaderElectionService =
new DefaultLeaderElectionService(driverFactory, fatalErrorHandler);
// latch to detect when we reached the first synchronized section having a lock on the
// JobMasterServiceProcess#stop side
final OneShotLatch closeAsyncCalledTrigger = new OneShotLatch();
// latch to halt the JobMasterServiceProcess#stop before calling stop on the
// DefaultLeaderElectionService instance (and entering the LeaderElectionService's
// synchronized block)
final OneShotLatch triggerClassLoaderLeaseRelease = new OneShotLatch();
final JobMasterServiceProcess jobMasterServiceProcess =
TestingJobMasterServiceProcess.newBuilder()
.setGetJobMasterGatewayFutureSupplier(CompletableFuture::new)
.setGetResultFutureSupplier(CompletableFuture::new)
.setGetLeaderAddressFutureSupplier(
() -> CompletableFuture.completedFuture("unused address"))
.setCloseAsyncSupplier(
() -> {
closeAsyncCalledTrigger.trigger();
// we have to return a completed future because we need the
// follow-up task to run in the calling thread to make the
// follow-up code block being executed in the synchronized block
return CompletableFuture.completedFuture(null);
})
.build();
final String componentId = "random-component-id";
final LeaderElection leaderElection =
defaultLeaderElectionService.createLeaderElection(componentId);
try (final JobMasterServiceLeadershipRunner jobManagerRunner =
newJobMasterServiceLeadershipRunnerBuilder()
.setClassLoaderLease(
TestingClassLoaderLease.newBuilder()
.setCloseRunnable(
() -> {
try {
// we want to wait with releasing to halt
// before calling stop on the
// DefaultLeaderElectionService
triggerClassLoaderLeaseRelease.await();
// In order to reproduce the deadlock, we
// need to ensure that
// leaderContender#grantLeadership can be
// called after
// JobMasterServiceLeadershipRunner obtains
// its own lock. Unfortunately, This will
// change the running status of
// DefaultLeaderElectionService
// to false, which will cause the
// notification of leadership to be
// ignored. The issue is that we
// don't have any means of verify that we're
// in the synchronized block of
// DefaultLeaderElectionService#lock in
// DefaultLeaderElectionService#onGrantLeadership,
// but we trigger this implicitly through
// TestingLeaderElectionDriver#grantLeadership(UUID).
// Adding a short sleep can ensure that
// another thread successfully receives the
// leadership notification, so that the
// deadlock problem can recur.
Thread.sleep(5);
} catch (InterruptedException e) {
ExceptionUtils.checkInterrupted(e);
}
})
.build())
.setJobMasterServiceProcessFactory(
TestingJobMasterServiceProcessFactory.newBuilder()
.setJobMasterServiceProcessFunction(
ignoredSessionId -> jobMasterServiceProcess)
.build())
.setLeaderElection(leaderElection)
.build()) {
jobManagerRunner.start();
// grant leadership to create jobMasterServiceProcess
haBackendLeadershipFlag.set(true);
final UUID leaderSessionID = UUID.randomUUID();
defaultLeaderElectionService.onGrantLeadership(leaderSessionID);
final SupplierWithException<Boolean, Exception> confirmationForSessionIdReceived =
() ->
storedLeaderInformation
.get()
.forComponentId(componentId)
.map(LeaderInformation::getLeaderSessionID)
.map(sessionId -> sessionId.equals(leaderSessionID))
.orElse(false);
CommonTestUtils.waitUntilCondition(confirmationForSessionIdReceived);
final CheckedThread contenderCloseThread = createCheckedThread(jobManagerRunner::close);
contenderCloseThread.start();
// waiting for the contender reaching the synchronized section of the stop call
closeAsyncCalledTrigger.await();
final CheckedThread grantLeadershipThread =
createCheckedThread(
() -> {
// DefaultLeaderElectionService enforces a proper event handling
// order (i.e. no two grant or revoke events should appear after
// each other). This requires the leadership to be revoked before
// regaining leadership in this test.
defaultLeaderElectionService.onRevokeLeadership();
defaultLeaderElectionService.onGrantLeadership(UUID.randomUUID());
});
grantLeadershipThread.start();
// finalize ClassloaderLease release to trigger DefaultLeaderElectionService#stop
triggerClassLoaderLeaseRelease.trigger();
contenderCloseThread.sync();
grantLeadershipThread.sync();
}
} |
@Override
public Column convert(BasicTypeDefine typeDefine) {
PhysicalColumn.PhysicalColumnBuilder builder =
PhysicalColumn.builder()
.name(typeDefine.getName())
.sourceType(typeDefine.getColumnType())
.nullable(typeDefine.isNullable())
.defaultValue(typeDefine.getDefaultValue())
.comment(typeDefine.getComment());
String pgDataType = typeDefine.getDataType().toLowerCase();
switch (pgDataType) {
case PG_BOOLEAN:
builder.dataType(BasicType.BOOLEAN_TYPE);
break;
case PG_BOOLEAN_ARRAY:
builder.dataType(ArrayType.BOOLEAN_ARRAY_TYPE);
break;
case PG_SMALLSERIAL:
case PG_SMALLINT:
builder.dataType(BasicType.SHORT_TYPE);
break;
case PG_SMALLINT_ARRAY:
builder.dataType(ArrayType.SHORT_ARRAY_TYPE);
break;
case PG_INTEGER:
case PG_SERIAL:
builder.dataType(BasicType.INT_TYPE);
break;
case PG_INTEGER_ARRAY:
builder.dataType(ArrayType.INT_ARRAY_TYPE);
break;
case PG_BIGINT:
case PG_BIGSERIAL:
builder.dataType(BasicType.LONG_TYPE);
break;
case PG_BIGINT_ARRAY:
builder.dataType(ArrayType.LONG_ARRAY_TYPE);
break;
case PG_REAL:
builder.dataType(BasicType.FLOAT_TYPE);
break;
case PG_REAL_ARRAY:
builder.dataType(ArrayType.FLOAT_ARRAY_TYPE);
break;
case PG_DOUBLE_PRECISION:
builder.dataType(BasicType.DOUBLE_TYPE);
break;
case PG_DOUBLE_PRECISION_ARRAY:
builder.dataType(ArrayType.DOUBLE_ARRAY_TYPE);
break;
case PG_NUMERIC:
DecimalType decimalType;
if (typeDefine.getPrecision() != null && typeDefine.getPrecision() > 0) {
decimalType =
new DecimalType(
typeDefine.getPrecision().intValue(), typeDefine.getScale());
} else {
decimalType = new DecimalType(DEFAULT_PRECISION, DEFAULT_SCALE);
}
builder.dataType(decimalType);
break;
case PG_MONEY:
// -92233720368547758.08 to +92233720368547758.07, With the sign bit it's 20, we use
// 30 precision to save it
DecimalType moneyDecimalType;
moneyDecimalType = new DecimalType(30, 2);
builder.dataType(moneyDecimalType);
builder.columnLength(30L);
builder.scale(2);
break;
case PG_CHAR:
case PG_CHARACTER:
builder.dataType(BasicType.STRING_TYPE);
if (typeDefine.getLength() == null || typeDefine.getLength() <= 0) {
builder.columnLength(TypeDefineUtils.charTo4ByteLength(1L));
builder.sourceType(pgDataType);
} else {
builder.columnLength(TypeDefineUtils.charTo4ByteLength(typeDefine.getLength()));
builder.sourceType(String.format("%s(%s)", pgDataType, typeDefine.getLength()));
}
break;
case PG_VARCHAR:
case PG_CHARACTER_VARYING:
builder.dataType(BasicType.STRING_TYPE);
if (typeDefine.getLength() == null || typeDefine.getLength() <= 0) {
builder.sourceType(pgDataType);
} else {
builder.sourceType(String.format("%s(%s)", pgDataType, typeDefine.getLength()));
builder.columnLength(TypeDefineUtils.charTo4ByteLength(typeDefine.getLength()));
}
break;
case PG_TEXT:
builder.dataType(BasicType.STRING_TYPE);
break;
case PG_UUID:
builder.dataType(BasicType.STRING_TYPE);
builder.sourceType(pgDataType);
builder.columnLength(128L);
break;
case PG_JSON:
case PG_JSONB:
case PG_XML:
case PG_GEOMETRY:
case PG_GEOGRAPHY:
builder.dataType(BasicType.STRING_TYPE);
break;
case PG_CHAR_ARRAY:
case PG_VARCHAR_ARRAY:
case PG_TEXT_ARRAY:
builder.dataType(ArrayType.STRING_ARRAY_TYPE);
break;
case PG_BYTEA:
builder.dataType(PrimitiveByteArrayType.INSTANCE);
break;
case PG_DATE:
builder.dataType(LocalTimeType.LOCAL_DATE_TYPE);
break;
case PG_TIME:
case PG_TIME_TZ:
builder.dataType(LocalTimeType.LOCAL_TIME_TYPE);
if (typeDefine.getScale() != null && typeDefine.getScale() > MAX_TIME_SCALE) {
builder.scale(MAX_TIME_SCALE);
log.warn(
"The scale of time type is larger than {}, it will be truncated to {}",
MAX_TIME_SCALE,
MAX_TIME_SCALE);
} else {
builder.scale(typeDefine.getScale());
}
break;
case PG_TIMESTAMP:
case PG_TIMESTAMP_TZ:
builder.dataType(LocalTimeType.LOCAL_DATE_TIME_TYPE);
if (typeDefine.getScale() != null && typeDefine.getScale() > MAX_TIMESTAMP_SCALE) {
builder.scale(MAX_TIMESTAMP_SCALE);
log.warn(
"The scale of timestamp type is larger than {}, it will be truncated to {}",
MAX_TIMESTAMP_SCALE,
MAX_TIMESTAMP_SCALE);
} else {
builder.scale(typeDefine.getScale());
}
break;
default:
throw CommonError.convertToSeaTunnelTypeError(
identifier(), typeDefine.getDataType(), typeDefine.getName());
}
return builder.build();
} | @Test
public void testConvertBigint() {
BasicTypeDefine<Object> typeDefine =
BasicTypeDefine.builder().name("test").columnType("int8").dataType("int8").build();
Column column = PostgresTypeConverter.INSTANCE.convert(typeDefine);
Assertions.assertEquals(typeDefine.getName(), column.getName());
Assertions.assertEquals(BasicType.LONG_TYPE, column.getDataType());
Assertions.assertEquals(typeDefine.getColumnType(), column.getSourceType().toLowerCase());
} |
public void go(PrintStream out) {
KieServices ks = KieServices.Factory.get();
// Install example1 in the local maven repo before to do this
KieContainer kContainer = ks.newKieContainer(ks.newReleaseId("org.drools", "named-kiesession", Drools.getFullVersion()));
KieSession kSession = kContainer.newKieSession("ksession1");
kSession.setGlobal("out", out);
Object msg1 = createMessage(kContainer, "Dave", "Hello, HAL. Do you read me, HAL?");
kSession.insert(msg1);
kSession.fireAllRules();
} | @Test
public void testGo() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
new KieContainerFromKieRepoExample().go(ps);
ps.close();
String actual = baos.toString();
String expected = "" +
"Dave: Hello, HAL. Do you read me, HAL?" + NL +
"HAL: Dave. I read you." + NL;
assertEquals(expected, actual);
} |
@Override
public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) {
File[] allFiles = getFiles(configRepoCheckoutDirectory, context);
// if context had changed files list then we could parse only new content
PartialConfig[] allFragments = parseFiles(allFiles);
PartialConfig partialConfig = new PartialConfig();
collectFragments(allFragments, partialConfig);
return partialConfig;
} | @Test
public void shouldFailToLoadDirectoryWithNonXmlFormat() throws Exception {
String content = """
<?xml version="1.0" encoding="utf-8"?>
<cruise xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="cruise-config.xsd" schemaVersion="38">
/cruise>""";// missing '<'
helper.writeFileWithContent("bad.gocd.xml",content);
try {
PartialConfig part = xmlPartialProvider.load(tmpFolder, mock(PartialConfigLoadContext.class));
} catch (RuntimeException ex) {
return;
}
fail("should have thrown");
} |
public <T> void resolve(T resolvable) {
ParamResolver resolver = this;
if (ParamScope.class.isAssignableFrom(resolvable.getClass())) {
ParamScope newScope = (ParamScope) resolvable;
resolver = newScope.applyOver(resolver);
}
resolveStringLeaves(resolvable, resolver);
resolveNonStringLeaves(resolvable, resolver);
resolveNodes(resolvable, resolver);
} | @Test
public void shouldEscapeEscapedPatternStartSequences() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("cruise", "dev", "ant");
pipelineConfig.setLabelTemplate("2.1-${COUNT}-#######{foo}-bar-####{bar}");
new ParamResolver(new ParamSubstitutionHandlerFactory(params(param("foo", "pavan"), param("bar", "jj"))), fieldCache).resolve(pipelineConfig);
assertThat(pipelineConfig.getLabelTemplate(), is("2.1-${COUNT}-###pavan-bar-##{bar}"));
} |
public static boolean isValidIpv4Address(String ip) {
boolean matches = IPV4_ADDRESS.matcher(ip).matches();
if (matches) {
String[] split = ip.split("\\.");
for (String num : split) {
int i = Integer.parseInt(num);
if (i > 255) {
return false;
}
}
}
return matches;
} | @Test
public void testIPv4() {
assertThat(IpAndDnsValidation.isValidIpv4Address("127.0.0.1"), is(true));
assertThat(IpAndDnsValidation.isValidIpv4Address("123.123.123.123"), is(true));
assertThat(IpAndDnsValidation.isValidIpv4Address("127.0.0.0.1"), is(false));
assertThat(IpAndDnsValidation.isValidIpv4Address("127.0.1"), is(false));
assertThat(IpAndDnsValidation.isValidIpv4Address("321.321.321.321"), is(false));
assertThat(IpAndDnsValidation.isValidIpv4Address("some.domain.name"), is(false));
} |
public static Logger getLogger(Class<?> key) {
return ConcurrentHashMapUtils.computeIfAbsent(
LOGGERS, key.getName(), name -> new FailsafeLogger(loggerAdapter.getLogger(name)));
} | @Test
void shouldReturnSameLogger() {
Logger logger1 = LoggerFactory.getLogger(this.getClass().getName());
Logger logger2 = LoggerFactory.getLogger(this.getClass().getName());
assertThat(logger1, is(logger2));
} |
public WriteResult<T, K> update(Bson filter, T object, boolean upsert, boolean multi) {
return update(filter, object, upsert, multi, delegate.getWriteConcern());
} | @Test
void updateWithObjectVariants() {
final var collection = spy(jacksonCollection("simple", Simple.class));
final var foo = new Simple("000000000000000000000001", "foo");
final DBQuery.Query query = DBQuery.empty();
collection.update(query, foo);
verify(collection).update(eq(query), eq(foo), eq(false), eq(false));
verify(collection).update(eq(query), eq(foo), eq(false), eq(false), eq(WriteConcern.ACKNOWLEDGED));
} |
public synchronized Value get(String key) throws IOException {
checkNotClosed();
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
for (File file : entry.cleanFiles) {
// A file must have been deleted manually!
if (!file.exists()) {
return null;
}
}
redundantOpCount++;
journalWriter.append(READ);
journalWriter.append(' ');
journalWriter.append(key);
journalWriter.append('\n');
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return new Value(key, entry.sequenceNumber, entry.cleanFiles, entry.lengths);
} | @Test public void readingTheSameFileMultipleTimes() throws Exception {
set("a", "a", "b");
DiskLruCache.Value value = cache.get("a");
assertThat(value.getFile(0)).isSameInstanceAs(value.getFile(0));
} |
public static boolean acceptEndpoint(String endpointUrl) {
return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING);
} | @Test
public void testAcceptEndpointFailures() {
assertFalse(WebSocketMessageConsumptionTask.acceptEndpoint("localhost:4000/websocket"));
assertFalse(WebSocketMessageConsumptionTask
.acceptEndpoint("microcks-ws.example.com/api/ws/Service/1.0.0/channel/sub/path"));
} |
public static Object parse(Payload payload) {
Class classType = PayloadRegistry.getClassByType(payload.getMetadata().getType());
if (classType != null) {
ByteString byteString = payload.getBody().getValue();
ByteBuffer byteBuffer = byteString.asReadOnlyByteBuffer();
Object obj = JacksonUtils.toObj(new ByteBufferBackedInputStream(byteBuffer), classType);
if (obj instanceof Request) {
((Request) obj).putAllHeader(payload.getMetadata().getHeadersMap());
}
return obj;
} else {
throw new RemoteException(NacosException.SERVER_ERROR,
"Unknown payload type:" + payload.getMetadata().getType());
}
} | @Test
void testParse() {
Payload requestPayload = GrpcUtils.convert(request);
ServiceQueryRequest request = (ServiceQueryRequest) GrpcUtils.parse(requestPayload);
assertEquals(this.request.getHeaders(), request.getHeaders());
assertEquals(this.request.getCluster(), request.getCluster());
assertEquals(this.request.isHealthyOnly(), request.isHealthyOnly());
assertEquals(this.request.getNamespace(), request.getNamespace());
Payload responsePayload = GrpcUtils.convert(response);
ClientConfigMetricResponse response = (ClientConfigMetricResponse) GrpcUtils.parse(responsePayload);
assertEquals(this.response.getMetrics(), response.getMetrics());
} |
public ApolloAuditTracer tracer() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
Object tracer = requestAttributes.getAttribute(ApolloAuditConstants.TRACER,
RequestAttributes.SCOPE_REQUEST);
if (tracer != null) {
return ((ApolloAuditTracer) tracer);
} else {
ApolloAuditTracer newTracer = new ApolloAuditTracer(new ApolloAuditScopeManager(), operatorSupplier);
setTracer(newTracer);
return newTracer;
}
}
return null;
} | @Test
public void testGetTracerInAnotherThreadButSameRequest() {
ApolloAuditTracer mockTracer = Mockito.mock(ApolloAuditTracer.class);
{
Mockito.when(traceContext.tracer()).thenReturn(mockTracer);
}
CountDownLatch latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().submit(() -> {
ApolloAuditTracer tracer = traceContext.tracer();
assertEquals(mockTracer, tracer);
latch.countDown();
});
} |
@Override
public void setValueForKey(int groupKey, double newValue) {
if (groupKey != GroupKeyGenerator.INVALID_ID) {
_resultArray[groupKey] = newValue;
}
} | @Test
void testSetValueForKey() {
GroupByResultHolder resultHolder = new DoubleGroupByResultHolder(INITIAL_CAPACITY, MAX_CAPACITY, DEFAULT_VALUE);
for (int i = 0; i < INITIAL_CAPACITY; i++) {
resultHolder.setValueForKey(i, _expected[i]);
}
testValues(resultHolder, _expected, 0, INITIAL_CAPACITY);
} |
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
AuthenticationToken token = null;
String tokenStr = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
tokenStr = cookie.getValue();
if (tokenStr.isEmpty()) {
throw new AuthenticationException("Unauthorized access");
}
try {
tokenStr = signer.verifyAndExtract(tokenStr);
} catch (SignerException ex) {
throw new AuthenticationException(ex);
}
break;
}
}
}
if (tokenStr != null) {
token = AuthenticationToken.parse(tokenStr);
boolean match = verifyTokenType(getAuthenticationHandler(), token);
if (!match) {
throw new AuthenticationException("Invalid AuthenticationToken type");
}
if (token.isExpired()) {
throw new AuthenticationException("AuthenticationToken expired");
}
}
return token;
} | @Test
public void testGetToken() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
SignerSecretProvider secretProvider =
getMockedServletContextWithStringSigner(config);
filter.init(config);
AuthenticationToken token = new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE);
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
AuthenticationToken newToken = filter.getToken(request);
Assert.assertEquals(token.toString(), newToken.toString());
} finally {
filter.destroy();
}
} |
public static <T> Iterator<T> skipFirst(Iterator<T> iterator, @Nonnull Predicate<? super T> predicate) {
checkNotNull(iterator, "iterator cannot be null.");
while (iterator.hasNext()) {
T object = iterator.next();
if (!predicate.test(object)) {
continue;
}
return prepend(object, iterator);
}
return iterator;
} | @Test
public void elementNotFound() {
var list = List.of(1, 2, 3, 4, 5, 6);
var actual = IterableUtil.skipFirst(list.iterator(), v -> v > 30);
assertThatThrownBy(actual::next).isInstanceOf(NoSuchElementException.class);
} |
public static String generateAsAsciiArt(String content) {
return generateAsAsciiArt(content, 0, 0, 1);
} | @Test
public void generateAsciiArtTest() {
final QrConfig qrConfig = QrConfig.create()
.setForeColor(Color.BLUE)
.setBackColor(Color.MAGENTA)
.setWidth(0)
.setHeight(0).setMargin(1);
final String asciiArt = QrCodeUtil.generateAsAsciiArt("https://hutool.cn/",qrConfig);
Assert.notNull(asciiArt);
//Console.log(asciiArt);
} |
void completeQuietly(final Utils.ThrowingRunnable function,
final String msg,
final AtomicReference<Throwable> firstException) {
try {
function.run();
} catch (TimeoutException e) {
log.debug("Timeout expired before the {} operation could complete.", msg);
} catch (Exception e) {
firstException.compareAndSet(null, e);
}
} | @Test
public void testCompleteQuietly() {
AtomicReference<Throwable> exception = new AtomicReference<>();
CompletableFuture<Object> future = CompletableFuture.completedFuture(null);
consumer = newConsumer();
assertDoesNotThrow(() -> consumer.completeQuietly(() ->
future.get(0, TimeUnit.MILLISECONDS), "test", exception));
assertNull(exception.get());
assertDoesNotThrow(() -> consumer.completeQuietly(() -> {
throw new KafkaException("Test exception");
}, "test", exception));
assertInstanceOf(KafkaException.class, exception.get());
} |
public static String unescape(String str) {
if (str == null) {
return null;
}
int len = str.length();
StringWriter writer = new StringWriter(len);
StringBuilder unicode = new StringBuilder(4);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (inUnicode) {
unicode.append(ch);
if (unicode.length() == 4) {
try {
int value = Integer.parseInt(unicode.toString(), 16);
writer.write((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
} catch (NumberFormatException nfe) {
throw new JsonPathException("Unable to parse unicode value: " + unicode, nfe);
}
}
continue;
}
if (hadSlash) {
hadSlash = false;
switch (ch) {
case '\\':
writer.write('\\');
break;
case '\'':
writer.write('\'');
break;
case '\"':
writer.write('"');
break;
case 'r':
writer.write('\r');
break;
case 'f':
writer.write('\f');
break;
case 't':
writer.write('\t');
break;
case 'n':
writer.write('\n');
break;
case 'b':
writer.write('\b');
break;
case 'u':
{
inUnicode = true;
break;
}
default :
writer.write(ch);
break;
}
continue;
} else if (ch == '\\') {
hadSlash = true;
continue;
}
writer.write(ch);
}
if (hadSlash) {
writer.write('\\');
}
return writer.toString();
} | @Test
public void testUnescape() {
Assertions.assertNull(Utils.unescape(null));
Assertions.assertEquals("foo", Utils.unescape("foo"));
Assertions.assertEquals("\\", Utils.unescape("\\"));
Assertions.assertEquals("\\", Utils.unescape("\\\\"));
Assertions.assertEquals("\'", Utils.unescape("\\\'"));
Assertions.assertEquals("\"", Utils.unescape("\\\""));
Assertions.assertEquals("\r", Utils.unescape("\\r"));
Assertions.assertEquals("\f", Utils.unescape("\\f"));
Assertions.assertEquals("\t", Utils.unescape("\\t"));
Assertions.assertEquals("\n", Utils.unescape("\\n"));
Assertions.assertEquals("\b", Utils.unescape("\\b"));
Assertions.assertEquals("a", Utils.unescape("\\a"));
Assertions.assertEquals("\uffff", Utils.unescape("\\uffff"));
} |
@NonNull public static GestureTypingPathDraw create(
@NonNull OnInvalidateCallback callback, @NonNull GestureTrailTheme theme) {
if (theme.maxTrailLength <= 0) return NO_OP;
return new GestureTypingPathDrawHelper(callback, theme);
} | @Test
public void testCreatesImpl() {
final AtomicInteger invalidates = new AtomicInteger();
GestureTypingPathDraw actual =
GestureTypingPathDrawHelper.create(
invalidates::incrementAndGet,
new GestureTrailTheme(
Color.argb(200, 60, 120, 240), Color.argb(100, 30, 240, 200), 100f, 20f, 10));
Assert.assertNotSame(GestureTypingPathDrawHelper.NO_OP, actual);
Assert.assertTrue(actual instanceof GestureTypingPathDrawHelper);
} |
public static Criterion matchEthType(int ethType) {
return new EthTypeCriterion(ethType);
} | @Test
public void testMatchEthTypeMethod() {
EthType ethType = new EthType(12);
Criterion matchEthType = Criteria.matchEthType(new EthType(12));
EthTypeCriterion ethTypeCriterion =
checkAndConvert(matchEthType,
Criterion.Type.ETH_TYPE,
EthTypeCriterion.class);
assertThat(ethTypeCriterion.ethType(), is(equalTo(ethType)));
} |
String name(String name) {
return sanitize(name, NAME_RESERVED);
} | @Test
public void truncatesNamesExceedingCustomMaxLength() throws Exception {
Sanitize customSanitize = new Sanitize(70);
String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789";
assertThat(customSanitize.name(longName)).isEqualTo(longName.substring(0, 70));
} |
@SuppressWarnings("unchecked")
public <T extends Expression> T rewrite(final T expression, final C context) {
return (T) rewriter.process(expression, context);
} | @Test
public void shouldRewriteCreateArrayExpression() {
// Given:
final CreateArrayExpression parsed = parseExpression("ARRAY['foo', col4[1]]");
final Expression firstVal = parsed.getValues().get(0);
final Expression secondVal = parsed.getValues().get(1);
when(processor.apply(firstVal, context)).thenReturn(expr1);
when(processor.apply(secondVal, context)).thenReturn(expr2);
// When:
final Expression rewritten = expressionRewriter.rewrite(parsed, context);
// Then:
assertThat(rewritten, equalTo(new CreateArrayExpression(ImmutableList.of(expr1, expr2))));
} |
@Override
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry());
} | @Test
public void injectsTheMetricRegistryIntoTheServletContext() {
final ServletContext context = mock(ServletContext.class);
final ServletContextEvent event = mock(ServletContextEvent.class);
when(event.getServletContext()).thenReturn(context);
listener.contextInitialized(event);
verify(context).setAttribute("com.codahale.metrics.servlet.InstrumentedFilter.registry", registry);
} |
@PostMapping("/get_logs")
@Operation(summary = "Get paginated account logs")
public DAccountLogsResult getAccountLogs(@RequestBody DAccountLogsRequest deprecatedRequest){
validatePageId(deprecatedRequest);
AppSession appSession = validate(deprecatedRequest);
var request = deprecatedRequest.getRequest();
var result = accountService.getAccountLogs(appSession.getAccountId(), appSession.getDeviceName(), appSession.getAppCode(), request);
return DAccountLogsResult.copyFrom(result);
} | @Test
public void testInvalidPageId() {
DAccountLogsRequest request = new DAccountLogsRequest();
request.setAppSessionId("id");
DAccountException exc = assertThrows(DAccountException.class, () -> {
accountLogsController.getAccountLogs(request);
});
assertEquals(HttpStatus.BAD_REQUEST, exc.getAccountErrorMessage().getHttpStatus());
assertEquals("Missing parameters.", exc.getAccountErrorMessage().getMessage());
} |
public static void waitForCommandSequenceNumber(
final CommandQueue commandQueue,
final KsqlRequest request,
final Duration timeout
) throws InterruptedException, TimeoutException {
final Optional<Long> commandSequenceNumber = request.getCommandSequenceNumber();
if (commandSequenceNumber.isPresent()) {
final long seqNum = commandSequenceNumber.get();
commandQueue.ensureConsumedPast(seqNum, timeout);
}
} | @Test
public void shouldNotWaitIfNoSequenceNumberSpecified() throws Exception {
// Given:
when(request.getCommandSequenceNumber()).thenReturn(Optional.empty());
// When:
CommandStoreUtil.waitForCommandSequenceNumber(commandQueue, request, TIMEOUT);
// Then:
verify(commandQueue, never()).ensureConsumedPast(anyLong(), any());
} |
public static boolean objectWithTheSameNameExists( SharedObjectInterface object,
Collection<? extends SharedObjectInterface> scope ) {
for ( SharedObjectInterface element : scope ) {
String elementName = element.getName();
if ( elementName != null && elementName.equalsIgnoreCase( object.getName() ) && object != element ) {
return true;
}
}
return false;
} | @Test
public void objectWithTheSameNameExists_false_if_not_exist() {
SharedObjectInterface sharedObject = mock( SharedObjectInterface.class );
when( sharedObject.getName() ).thenReturn( "NEW_TEST_OBJECT" );
assertFalse( objectWithTheSameNameExists( sharedObject, createTestScope( "TEST_OBJECT" ) ) );
} |
@Override
public Address getCaller() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testGetCaller() {
localCacheWideEventData.getCaller();
} |
@Override
public CRTask deserialize(JsonElement json,
Type type,
JsonDeserializationContext context) throws JsonParseException {
return determineJsonElementForDistinguishingImplementers(json, context, TYPE, ARTIFACT_ORIGIN);
} | @Test
public void shouldThrowExceptionForFetchIfOriginIsInvalid() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "fetch");
jsonObject.addProperty(TypeAdapter.ARTIFACT_ORIGIN, "fsg");
assertThatThrownBy(() -> taskTypeAdapter.deserialize(jsonObject, type, jsonDeserializationContext))
.isInstanceOf(JsonParseException.class)
.hasMessageContaining("Invalid artifact origin 'fsg' for fetch task.");
} |
@Override
public Serde<GenericRow> create(
final FormatInfo format,
final PersistenceSchema schema,
final KsqlConfig ksqlConfig,
final Supplier<SchemaRegistryClient> srClientFactory,
final String loggerNamePrefix,
final ProcessingLogContext processingLogContext,
final Optional<TrackedCallback> tracker
) {
final Serde<List<?>> formatSerde =
innerFactory.createFormatSerde("Value", format, schema, ksqlConfig, srClientFactory, false);
final Serde<GenericRow> genericRowSerde = toGenericRowSerde(formatSerde, schema);
final Serde<GenericRow> loggingSerde = innerFactory.wrapInLoggingSerde(
genericRowSerde,
loggerNamePrefix,
processingLogContext,
queryId);
final Serde<GenericRow> serde = tracker
.map(callback -> innerFactory.wrapInTrackingSerde(loggingSerde, callback))
.orElse(loggingSerde);
serde.configure(Collections.emptyMap(), false);
return serde;
} | @Test
public void shouldReturnLoggingSerde() {
// When:
final Serde<GenericRow> result = factory
.create(format, schema, config, srClientFactory, LOGGER_PREFIX, processingLogCxt,
Optional.empty());
// Then:
assertThat(result, is(sameInstance(loggingSerde)));
} |
@Override
public V chooseVolume(List<V> volumes, long replicaSize, String storageId)
throws IOException {
if (volumes.size() < 1) {
throw new DiskOutOfSpaceException("No more available volumes");
}
// As all the items in volumes are with the same storage type,
// so only need to get the storage type index of the first item in volumes
StorageType storageType = volumes.get(0).getStorageType();
int index = storageType != null ?
storageType.ordinal() : StorageType.DEFAULT.ordinal();
synchronized (syncLocks[index]) {
return doChooseVolume(volumes, replicaSize, storageId);
}
} | @Test(timeout=60000)
public void testAvailableSpaceChanges() throws Exception {
@SuppressWarnings("unchecked")
final AvailableSpaceVolumeChoosingPolicy<FsVolumeSpi> policy =
ReflectionUtils.newInstance(AvailableSpaceVolumeChoosingPolicy.class, null);
initPolicy(policy, BALANCED_SPACE_THRESHOLD, 1.0f);
List<FsVolumeSpi> volumes = new ArrayList<FsVolumeSpi>();
// First volume with 1MB free space
volumes.add(Mockito.mock(FsVolumeSpi.class));
Mockito.when(volumes.get(0).getAvailable()).thenReturn(1024L * 1024L);
// Second volume with 3MB free space, which is a difference of 2MB, more
// than the threshold of 1MB.
volumes.add(Mockito.mock(FsVolumeSpi.class));
Mockito.when(volumes.get(1).getAvailable())
.thenReturn(1024L * 1024L * 3)
.thenReturn(1024L * 1024L * 3)
.thenReturn(1024L * 1024L * 3)
.thenReturn(1024L * 1024L * 1); // After the third check, return 1MB.
// Should still be able to get a volume for the replica even though the
// available space on the second volume changed.
Assert.assertEquals(volumes.get(1), policy.chooseVolume(volumes,
100, null));
} |
public boolean isUnknownOrLessThan(Version version) {
return isUnknown() || compareTo(version) < 0;
} | @Test
public void isUnknownOrLessThan() {
assertFalse(V3_0.isUnknownOrLessThan(of(2, 0)));
assertFalse(V3_0.isUnknownOrLessThan(of(3, 0)));
assertTrue(V3_0.isUnknownOrLessThan(of(3, 1)));
assertTrue(V3_0.isUnknownOrLessThan(of(4, 0)));
assertTrue(V3_0.isUnknownOrLessThan(of(100, 0)));
assertTrue(UNKNOWN.isUnknownOrLessThan(of(100, 0)));
} |
public Flowable<EthBlock> replayPastBlocksFlowable(
DefaultBlockParameter startBlock,
boolean fullTransactionObjects,
Flowable<EthBlock> onCompleteFlowable) {
// We use a scheduler to ensure this Flowable runs asynchronously for users to be
// consistent with the other Flowables
return replayPastBlocksFlowableSync(startBlock, fullTransactionObjects, onCompleteFlowable)
.subscribeOn(scheduler);
} | @Test
public void testReplayBlocksDescendingFlowable() throws Exception {
List<EthBlock> ethBlocks = Arrays.asList(createBlock(2), createBlock(1), createBlock(0));
OngoingStubbing<EthBlock> stubbing =
when(web3jService.send(any(Request.class), eq(EthBlock.class)));
for (EthBlock ethBlock : ethBlocks) {
stubbing = stubbing.thenReturn(ethBlock);
}
Flowable<EthBlock> flowable =
web3j.replayPastBlocksFlowable(
new DefaultBlockParameterNumber(BigInteger.ZERO),
new DefaultBlockParameterNumber(BigInteger.valueOf(2)),
false,
false);
CountDownLatch transactionLatch = new CountDownLatch(ethBlocks.size());
CountDownLatch completedLatch = new CountDownLatch(1);
List<EthBlock> results = new ArrayList<>(ethBlocks.size());
Disposable subscription =
flowable.subscribe(
result -> {
results.add(result);
transactionLatch.countDown();
},
throwable -> fail(throwable.getMessage()),
() -> completedLatch.countDown());
transactionLatch.await(1, TimeUnit.SECONDS);
assertEquals(results, (ethBlocks));
subscription.dispose();
completedLatch.await(1, TimeUnit.SECONDS);
assertTrue(subscription.isDisposed());
} |
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
public static RestartConfig.RestartNode getCurrentNode(RestartConfig config) {
Checks.checkTrue(
config != null && !ObjectHelper.isCollectionEmptyOrNull(config.getRestartPath()),
"Cannot get restart info in empty restart configuration");
return config.getRestartPath().get(config.getRestartPath().size() - 1);
} | @Test
public void testExtractCurrentNodeFromRestartConfig() {
AssertHelper.assertThrows(
"Invalid get",
IllegalArgumentException.class,
"Cannot get restart info in empty restart configuration",
() -> RunRequest.getCurrentNode(RestartConfig.builder().build()));
RestartConfig config = RestartConfig.builder().addRestartNode("foo", 1, "bar").build();
Assert.assertEquals(
new RestartConfig.RestartNode("foo", 1, "bar"), RunRequest.getCurrentNode(config));
} |
public static Type[] getExactParameterTypes(Executable m, Type declaringType) {
return stream(
GenericTypeReflector.getExactParameterTypes(
m, GenericTypeReflector.annotate(declaringType)))
.map(annType -> uncapture(annType.getType()))
.toArray(Type[]::new);
} | @Test
public void getExactParameterTypes() {
var type = Types.parameterizedType(Container.class, Person.class);
var ctor = Container.class.getDeclaredConstructors()[0];
assertThat(Reflection.getExactParameterTypes(ctor, type)).isEqualTo(new Type[] {Person.class});
var method = Container.class.getDeclaredMethods()[0];
assertThat(Reflection.getExactParameterTypes(method, type))
.isEqualTo(new Type[] {Person.class});
} |
@Override
public ListTopicsResult listTopics(final ListTopicsOptions options) {
final KafkaFutureImpl<Map<String, TopicListing>> topicListingFuture = new KafkaFutureImpl<>();
final long now = time.milliseconds();
runnable.call(new Call("listTopics", calcDeadlineMs(now, options.timeoutMs()),
new LeastLoadedNodeProvider()) {
@Override
MetadataRequest.Builder createRequest(int timeoutMs) {
return MetadataRequest.Builder.allTopics();
}
@Override
void handleResponse(AbstractResponse abstractResponse) {
MetadataResponse response = (MetadataResponse) abstractResponse;
Map<String, TopicListing> topicListing = new HashMap<>();
for (MetadataResponse.TopicMetadata topicMetadata : response.topicMetadata()) {
String topicName = topicMetadata.topic();
boolean isInternal = topicMetadata.isInternal();
if (!topicMetadata.isInternal() || options.shouldListInternal())
topicListing.put(topicName, new TopicListing(topicName, topicMetadata.topicId(), isInternal));
}
topicListingFuture.complete(topicListing);
}
@Override
void handleFailure(Throwable throwable) {
topicListingFuture.completeExceptionally(throwable);
}
}, now);
return new ListTopicsResult(topicListingFuture);
} | @Test
public void testSuccessfulRetryAfterRequestTimeout() throws Exception {
HashMap<Integer, Node> nodes = new HashMap<>();
MockTime time = new MockTime();
Node node0 = new Node(0, "localhost", 8121);
nodes.put(0, node0);
Cluster cluster = new Cluster("mockClusterId", nodes.values(),
singletonList(new PartitionInfo("foo", 0, node0, new Node[]{node0}, new Node[]{node0})),
Collections.emptySet(), Collections.emptySet(),
Collections.emptySet(), nodes.get(0));
final int requestTimeoutMs = 1000;
final int retryBackoffMs = 100;
final int apiTimeoutMs = 3000;
try (AdminClientUnitTestEnv env = new AdminClientUnitTestEnv(time, cluster,
AdminClientConfig.RETRY_BACKOFF_MS_CONFIG, String.valueOf(retryBackoffMs),
AdminClientConfig.RETRY_BACKOFF_MAX_MS_CONFIG, String.valueOf(retryBackoffMs),
AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, String.valueOf(requestTimeoutMs))) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
final ListTopicsResult result = env.adminClient()
.listTopics(new ListTopicsOptions().timeoutMs(apiTimeoutMs));
// Wait until the first attempt has been sent, then advance the time
TestUtils.waitForCondition(() -> env.kafkaClient().hasInFlightRequests(),
"Timed out waiting for Metadata request to be sent");
time.sleep(requestTimeoutMs + 1);
// Wait for the request to be timed out before backing off
TestUtils.waitForCondition(() -> !env.kafkaClient().hasInFlightRequests(),
"Timed out waiting for inFlightRequests to be timed out");
time.sleep(retryBackoffMs + 1);
// Since api timeout bound is not hit, AdminClient should retry
TestUtils.waitForCondition(() -> env.kafkaClient().hasInFlightRequests(),
"Failed to retry Metadata request");
env.kafkaClient().respond(prepareMetadataResponse(cluster, Errors.NONE));
assertEquals(1, result.listings().get().size());
assertEquals("foo", result.listings().get().iterator().next().name());
}
} |
public static boolean isDirectory(URL resourceURL) throws URISyntaxException {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final JarEntry entry = jarConnection.getJarEntry();
if (entry.isDirectory()) {
return true;
}
// WARNING! Heuristics ahead.
// It turns out that JarEntry#isDirectory() really just tests whether the filename ends in a '/'.
// If you try to open the same URL without a trailing '/', it'll succeed — but the result won't be
// what you want. We try to get around this by calling getInputStream() on the file inside the jar.
// This seems to return null for directories (though that behavior is undocumented as far as I
// can tell). If you have a better idea, please improve this.
final String relativeFilePath = entry.getName();
final JarFile jarFile = jarConnection.getJarFile();
final ZipEntry zipEntry = jarFile.getEntry(relativeFilePath);
final InputStream inputStream = jarFile.getInputStream(zipEntry);
return inputStream == null;
} catch (IOException e) {
throw new ResourceNotFoundException(e);
}
case "file":
return new File(resourceURL.toURI()).isDirectory();
default:
throw new IllegalArgumentException("Unsupported protocol " + resourceURL.getProtocol() +
" for resource " + resourceURL);
}
} | @Test
void isDirectoryThrowsResourceNotFoundExceptionForMissingDirectories() throws Exception {
final URL url = getClass().getResource("/META-INF/");
final URL nurl = new URL(url.toExternalForm() + "missing");
assertThatExceptionOfType(ResourceNotFoundException.class)
.isThrownBy(() -> ResourceURL.isDirectory(nurl));
} |
@Bean
public CircuitBreakerRegistry circuitBreakerRegistry(
EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry,
RegistryEventConsumer<CircuitBreaker> circuitBreakerRegistryEventConsumer,
@Qualifier("compositeCircuitBreakerCustomizer") CompositeCustomizer<CircuitBreakerConfigCustomizer> compositeCircuitBreakerCustomizer) {
CircuitBreakerRegistry circuitBreakerRegistry = createCircuitBreakerRegistry(
circuitBreakerProperties, circuitBreakerRegistryEventConsumer,
compositeCircuitBreakerCustomizer);
registerEventConsumer(circuitBreakerRegistry, eventConsumerRegistry);
// then pass the map here
initCircuitBreakerRegistry(circuitBreakerRegistry, compositeCircuitBreakerCustomizer);
return circuitBreakerRegistry;
} | @Test
public void testCreateCircuitBreakerRegistryWithUnknownConfig() {
CircuitBreakerConfigurationProperties circuitBreakerConfigurationProperties = new CircuitBreakerConfigurationProperties();
InstanceProperties instanceProperties = new InstanceProperties();
instanceProperties.setBaseConfig("unknownConfig");
circuitBreakerConfigurationProperties.getInstances().put("backend", instanceProperties);
CircuitBreakerConfiguration circuitBreakerConfiguration = new CircuitBreakerConfiguration(
circuitBreakerConfigurationProperties);
DefaultEventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry = new DefaultEventConsumerRegistry<>();
assertThatThrownBy(() -> circuitBreakerConfiguration
.circuitBreakerRegistry(eventConsumerRegistry,
new CompositeRegistryEventConsumer<>(emptyList()),
compositeCircuitBreakerCustomizerTestInstance()))
.isInstanceOf(ConfigurationNotFoundException.class)
.hasMessage("Configuration with name 'unknownConfig' does not exist");
} |
@Override
public void register(@NonNull ThreadPoolPlugin plugin) {
mainLock.runWithWriteLock(() -> {
String id = plugin.getId();
Assert.isTrue(!isRegistered(id), "The plugin with id [" + id + "] has been registered");
registeredPlugins.put(id, plugin);
forQuickIndexes(quickIndex -> quickIndex.addIfPossible(plugin));
plugin.start();
});
} | @Test
public void testGetPluginOfType() {
manager.register(new TestExecuteAwarePlugin());
Assert.assertTrue(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), TestExecuteAwarePlugin.class).isPresent());
Assert.assertTrue(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), ThreadPoolPlugin.class).isPresent());
Assert.assertFalse(manager.getPluginOfType(TestExecuteAwarePlugin.class.getSimpleName(), RejectedAwarePlugin.class).isPresent());
} |
@GET
public Response getApplication(@PathParam("version") String version,
@HeaderParam("Accept") final String acceptHeader,
@HeaderParam(EurekaAccept.HTTP_X_EUREKA_ACCEPT) String eurekaAccept) {
if (!registry.shouldAllowAccess(false)) {
return Response.status(Status.FORBIDDEN).build();
}
EurekaMonitors.GET_APPLICATION.increment();
CurrentRequestVersion.set(Version.toEnum(version));
KeyType keyType = Key.KeyType.JSON;
if (acceptHeader == null || !acceptHeader.contains("json")) {
keyType = Key.KeyType.XML;
}
Key cacheKey = new Key(
Key.EntityType.Application,
appName,
keyType,
CurrentRequestVersion.get(),
EurekaAccept.fromString(eurekaAccept)
);
String payLoad = responseCache.get(cacheKey);
CurrentRequestVersion.remove();
if (payLoad != null) {
logger.debug("Found: {}", appName);
return Response.ok(payLoad).build();
} else {
logger.debug("Not Found: {}", appName);
return Response.status(Status.NOT_FOUND).build();
}
} | @Test
public void testFullAppGet() throws Exception {
Response response = applicationResource.getApplication(
Version.V2.name(),
MediaType.APPLICATION_JSON,
EurekaAccept.full.name()
);
String json = String.valueOf(response.getEntity());
DecoderWrapper decoder = CodecWrappers.getDecoder(CodecWrappers.LegacyJacksonJson.class);
Application decodedApp = decoder.decode(json, Application.class);
assertThat(EurekaEntityComparators.equal(testApplication, decodedApp), is(true));
} |
public static InstanceInfo takeFirst(Applications applications) {
for (Application application : applications.getRegisteredApplications()) {
if (!application.getInstances().isEmpty()) {
return application.getInstances().get(0);
}
}
return null;
} | @Test
public void testTakeFirstIfNotNullReturnFirstInstance() {
Application application = createSingleInstanceApp("foo", "foo",
InstanceInfo.ActionType.ADDED);
Applications applications = createApplications(application);
applications.addApplication(application);
Assert.assertNull(EurekaEntityFunctions.takeFirst(new Applications()));
Assert.assertEquals(application.getByInstanceId("foo"),
EurekaEntityFunctions.takeFirst(applications));
} |
public PahoConfiguration getConfiguration() {
return configuration;
} | @Test
public void checkOptions() {
String uri = "paho:/test/topic" + "?clientId=sampleClient" + "&brokerUrl=" + service.serviceAddress()
+ "&qos=2"
+ "&persistence=file";
PahoEndpoint endpoint = getMandatoryEndpoint(uri, PahoEndpoint.class);
// Then
assertEquals("/test/topic", endpoint.getTopic());
assertEquals("sampleClient", endpoint.getConfiguration().getClientId());
assertEquals(service.serviceAddress(), endpoint.getConfiguration().getBrokerUrl());
assertEquals(2, endpoint.getConfiguration().getQos());
assertEquals(PahoPersistence.FILE, endpoint.getConfiguration().getPersistence());
} |
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @Nullable <InputT> TransformEvaluator<InputT> forApplication(
AppliedPTransform<?, ?, ?> application, CommittedBundle<?> inputBundle) {
return createEvaluator((AppliedPTransform) application);
} | @Test
public void noElementsAvailableReaderIncludedInResidual() throws Exception {
// Read with a very slow rate so by the second read there are no more elements
PCollection<Long> pcollection =
p.apply(Read.from(new TestUnboundedSource<>(VarLongCoder.of(), 1L)));
SplittableParDo.convertReadBasedSplittableDoFnsToPrimitiveReads(p);
AppliedPTransform<?, ?, ?> sourceTransform = getProducer(pcollection);
when(context.createRootBundle()).thenReturn(bundleFactory.createRootBundle());
Collection<CommittedBundle<?>> initialInputs =
new UnboundedReadEvaluatorFactory.InputProvider(context, p.getOptions())
.getInitialInputs(sourceTransform, 1);
// Process the initial shard. This might produce some output, and will produce a residual shard
// which should produce no output when read from within the following day.
when(context.createBundle(pcollection)).thenReturn(bundleFactory.createBundle(pcollection));
CommittedBundle<?> inputBundle = Iterables.getOnlyElement(initialInputs);
TransformEvaluator<UnboundedSourceShard<Long, TestCheckpointMark>> evaluator =
factory.forApplication(sourceTransform, inputBundle);
for (WindowedValue<?> value : inputBundle.getElements()) {
evaluator.processElement(
(WindowedValue<UnboundedSourceShard<Long, TestCheckpointMark>>) value);
}
TransformResult<UnboundedSourceShard<Long, TestCheckpointMark>> result =
evaluator.finishBundle();
// Read from the residual of the first read. This should not produce any output, but should
// include a residual shard in the result.
UncommittedBundle<Long> secondOutput = bundleFactory.createBundle(longs);
when(context.createBundle(longs)).thenReturn(secondOutput);
TransformEvaluator<UnboundedSourceShard<Long, TestCheckpointMark>> secondEvaluator =
factory.forApplication(sourceTransform, inputBundle);
WindowedValue<UnboundedSourceShard<Long, TestCheckpointMark>> residual =
(WindowedValue<UnboundedSourceShard<Long, TestCheckpointMark>>)
Iterables.getOnlyElement(result.getUnprocessedElements());
secondEvaluator.processElement(residual);
TransformResult<UnboundedSourceShard<Long, TestCheckpointMark>> secondResult =
secondEvaluator.finishBundle();
// Sanity check that nothing was output (The test would have to run for more than a day to do
// so correctly.)
assertThat(secondOutput.commit(Instant.now()).getElements(), Matchers.emptyIterable());
// Test that even though the reader produced no outputs, there is still a residual shard with
// the updated watermark.
WindowedValue<UnboundedSourceShard<Long, TestCheckpointMark>> unprocessed =
(WindowedValue<UnboundedSourceShard<Long, TestCheckpointMark>>)
Iterables.getOnlyElement(secondResult.getUnprocessedElements());
assertThat(unprocessed.getTimestamp(), Matchers.greaterThan(residual.getTimestamp()));
assertThat(unprocessed.getValue().getExistingReader(), not(nullValue()));
} |
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
} | @Test
void testIsNotEmpty() {
assertFalse(StringUtils.isNotEmpty(null));
assertFalse(StringUtils.isNotEmpty(""));
assertTrue(StringUtils.isNotEmpty(" "));
assertTrue(StringUtils.isNotEmpty("bob"));
assertTrue(StringUtils.isNotEmpty(" bob "));
} |
public static Pair<String, Integer> validateHostAndPort(String hostPort, boolean resolveHost) {
hostPort = hostPort.replaceAll("\\s+", "");
if (hostPort.isEmpty()) {
throw new SemanticException("Invalid host port: " + hostPort);
}
String[] hostInfo;
try {
hostInfo = NetUtils.resolveHostInfoFromHostPort(hostPort);
} catch (AnalysisException e) {
throw new SemanticException("Invalid host port: " + hostPort, e);
}
String host = hostInfo[0];
if (Strings.isNullOrEmpty(host)) {
throw new SemanticException("Host is null");
}
int heartbeatPort;
try {
// validate host
if (resolveHost && !InetAddressValidator.getInstance().isValid(host)) {
// maybe this is a hostname
// if no IP address for the host could be found, 'getByName'
// will throw
// UnknownHostException
InetAddress inetAddress = InetAddress.getByName(host);
host = inetAddress.getHostAddress();
}
// validate port
heartbeatPort = Integer.parseInt(hostInfo[1]);
if (heartbeatPort <= 0 || heartbeatPort >= 65536) {
throw new SemanticException("Port is out of range: " + heartbeatPort);
}
return new Pair<>(host, heartbeatPort);
} catch (UnknownHostException e) {
throw new SemanticException("Unknown host: " + e.getMessage());
} catch (Exception e) {
throw new SemanticException("Encounter unknown exception: " + e.getMessage());
}
} | @Test
public void testGetHostAndPort() {
String ipv4 = "192.168.1.2:9050";
String ipv6 = "[fe80::5054:ff:fec9:dee0]:9050";
String ipv6Error = "fe80::5054:ff:fec9:dee0:dee0";
try {
Pair<String, Integer> ipv4Addr = SystemInfoService.validateHostAndPort(ipv4, false);
Assert.assertEquals("192.168.1.2", ipv4Addr.first);
Assert.assertEquals(9050, ipv4Addr.second.intValue());
} catch (SemanticException e) {
e.printStackTrace();
Assert.fail();
}
try {
Pair<String, Integer> ipv6Addr = SystemInfoService.validateHostAndPort(ipv6, false);
Assert.assertEquals("fe80::5054:ff:fec9:dee0", ipv6Addr.first);
Assert.assertEquals(9050, ipv6Addr.second.intValue());
} catch (SemanticException e) {
e.printStackTrace();
Assert.fail();
}
try {
SystemInfoService.validateHostAndPort(ipv6Error, false);
Assert.fail();
} catch (SemanticException e) {
e.printStackTrace();
}
} |
@Override
public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception {
// ask for a mandatory type conversion to avoid a possible NPE beforehand as we do copy from the InputStream
final InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph);
final Deflater deflater = new Deflater(compressionLevel);
final DeflaterOutputStream zipOutput = new DeflaterOutputStream(stream, deflater);
try {
IOHelper.copy(is, zipOutput);
} finally {
IOHelper.close(is, zipOutput);
/*
* As we create the Deflater our self and do not use the stream default
* (see {@link java.util.zip.DeflaterOutputStream#usesDefaultDeflater})
* we need to close the Deflater to not risk a OutOfMemoryException
* in native code parts (see {@link java.util.zip.Deflater#end})
*/
deflater.end();
}
} | @Test
public void testMarshalTextToZipDefaultCompression() throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
from("direct:start")
.marshal().zipDeflater(Deflater.DEFAULT_COMPRESSION)
.process(new ZippedMessageProcessor());
}
});
context.start();
sendText();
} |
@Override
public ConcatIterator<T> iterator() throws IOException {
return new ConcatIterator<T>(
readerFactory, options, executionContext, operationContext, sources);
} | @Test
public void testReadEmptyList() throws Exception {
ConcatReader<String> concat =
new ConcatReader<>(
registry,
null /* options */,
null /* executionContext */,
TestOperationContext.create(),
new ArrayList<Source>());
ConcatReader.ConcatIterator<String> iterator = concat.iterator();
assertNotNull(iterator);
assertFalse(concat.iterator().start());
expectedException.expect(NoSuchElementException.class);
iterator.getCurrent();
} |
@SneakyThrows(IOException.class)
public static JDBCRepositorySQL load(final String type) {
JDBCRepositorySQL result = null;
try (Stream<String> resourceNameStream = ClasspathResourceDirectoryReader.read(JDBCRepositorySQLLoader.class.getClassLoader(), ROOT_DIRECTORY)) {
Iterable<String> resourceNameIterable = resourceNameStream::iterator;
for (String each : resourceNameIterable) {
if (!each.endsWith(FILE_EXTENSION)) {
continue;
}
JDBCRepositorySQL provider = XML_MAPPER.readValue(JDBCRepositorySQLLoader.class.getClassLoader().getResourceAsStream(each), JDBCRepositorySQL.class);
if (provider.isDefault()) {
result = provider;
}
if (Objects.equals(provider.getType(), type)) {
result = provider;
break;
}
}
}
return result;
} | @Test
void assertLoad() {
assertThat(JDBCRepositorySQLLoader.load("MySQL").getType(), is("MySQL"));
assertThat(JDBCRepositorySQLLoader.load("EmbeddedDerby").getType(), is("EmbeddedDerby"));
assertThat(JDBCRepositorySQLLoader.load("DerbyNetworkServer").getType(), is("DerbyNetworkServer"));
assertThat(JDBCRepositorySQLLoader.load("HSQLDB").getType(), is("HSQLDB"));
} |
public static boolean listenByOther(final int port) {
Optional<String> optionalPid = getPortOwner(port);
if (optionalPid.isPresent() && !optionalPid.get().equals(SystemUtils.getCurrentPID())) {
LOGGER.warn("PID {} is listening on port {}.", optionalPid.get(), port);
return true;
} else {
return false;
}
} | @Test
void listenByOther() throws IOException {
try (MockedStatic<SystemUtils> systemUtilsMockedStatic = mockStatic(SystemUtils.class)) {
systemUtilsMockedStatic.when(SystemUtils::getCurrentPID).thenReturn("0");
systemUtilsMockedStatic.when(SystemUtils::isWindows).thenReturn(true);
assertDoesNotThrow(() -> RuntimeUtils.listenByOther(9095));
systemUtilsMockedStatic.when(SystemUtils::isWindows).thenReturn(false);
assertDoesNotThrow(() -> RuntimeUtils.listenByOther(9095));
}
try (MockedStatic<Runtime> runtimeMockedStatic = mockStatic(Runtime.class)) {
runtimeMockedStatic.when(Runtime::getRuntime).thenThrow(RuntimeException.class);
assertFalse(RuntimeUtils.listenByOther(9095));
final Runtime runtime = mock(Runtime.class);
runtimeMockedStatic.when(Runtime::getRuntime).thenReturn(runtime);
final Process process = mock(Process.class);
when(runtime.exec(any(String[].class))).thenReturn(process);
final String text = "LISTEN xx:" + 9095 + " xx ";
InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
when(process.getInputStream()).thenReturn(stream);
assertFalse(RuntimeUtils.listenByOther(9095));
when(runtime.exec(any(String[].class))).thenReturn(null);
assertFalse(RuntimeUtils.listenByOther(9095));
}
assertFalse(RuntimeUtils.listenByOther(9095));
assertFalse(RuntimeUtils.listenByOther(99999));
assertFalse(RuntimeUtils.listenByOther(0));
} |
public final ResourceSkyline getResourceSkyline() {
return resourceSkyline;
} | @Test public final void testGetContainerSpec() {
final Resource containerAlloc =
jobMetaData.getResourceSkyline().getContainerSpec();
final Resource containerAlloc2 = Resource.newInstance(1, 1);
Assert.assertEquals(containerAlloc.getMemorySize(),
containerAlloc2.getMemorySize());
Assert.assertEquals(containerAlloc.getVirtualCores(),
containerAlloc2.getVirtualCores());
} |
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM)
{
String message = Text.removeTags(event.getMessage());
Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message);
Matcher dodgyProtectMatcher = DODGY_PROTECT_PATTERN.matcher(message);
Matcher dodgyBreakMatcher = DODGY_BREAK_PATTERN.matcher(message);
Matcher bindingNecklaceCheckMatcher = BINDING_CHECK_PATTERN.matcher(message);
Matcher bindingNecklaceUsedMatcher = BINDING_USED_PATTERN.matcher(message);
Matcher ringOfForgingCheckMatcher = RING_OF_FORGING_CHECK_PATTERN.matcher(message);
Matcher amuletOfChemistryCheckMatcher = AMULET_OF_CHEMISTRY_CHECK_PATTERN.matcher(message);
Matcher amuletOfChemistryUsedMatcher = AMULET_OF_CHEMISTRY_USED_PATTERN.matcher(message);
Matcher amuletOfChemistryBreakMatcher = AMULET_OF_CHEMISTRY_BREAK_PATTERN.matcher(message);
Matcher amuletOfBountyCheckMatcher = AMULET_OF_BOUNTY_CHECK_PATTERN.matcher(message);
Matcher amuletOfBountyUsedMatcher = AMULET_OF_BOUNTY_USED_PATTERN.matcher(message);
Matcher chronicleAddMatcher = CHRONICLE_ADD_PATTERN.matcher(message);
Matcher chronicleUseAndCheckMatcher = CHRONICLE_USE_AND_CHECK_PATTERN.matcher(message);
Matcher slaughterActivateMatcher = BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN.matcher(message);
Matcher slaughterCheckMatcher = BRACELET_OF_SLAUGHTER_CHECK_PATTERN.matcher(message);
Matcher expeditiousActivateMatcher = EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN.matcher(message);
Matcher expeditiousCheckMatcher = EXPEDITIOUS_BRACELET_CHECK_PATTERN.matcher(message);
Matcher bloodEssenceCheckMatcher = BLOOD_ESSENCE_CHECK_PATTERN.matcher(message);
Matcher bloodEssenceExtractMatcher = BLOOD_ESSENCE_EXTRACT_PATTERN.matcher(message);
Matcher braceletOfClayCheckMatcher = BRACELET_OF_CLAY_CHECK_PATTERN.matcher(message);
if (message.contains(RING_OF_RECOIL_BREAK_MESSAGE))
{
notifier.notify(config.recoilNotification(), "Your Ring of Recoil has shattered");
}
else if (dodgyBreakMatcher.find())
{
notifier.notify(config.dodgyNotification(), "Your dodgy necklace has crumbled to dust.");
updateDodgyNecklaceCharges(MAX_DODGY_CHARGES);
}
else if (dodgyCheckMatcher.find())
{
updateDodgyNecklaceCharges(Integer.parseInt(dodgyCheckMatcher.group(1)));
}
else if (dodgyProtectMatcher.find())
{
updateDodgyNecklaceCharges(Integer.parseInt(dodgyProtectMatcher.group(1)));
}
else if (amuletOfChemistryCheckMatcher.find())
{
updateAmuletOfChemistryCharges(Integer.parseInt(amuletOfChemistryCheckMatcher.group(1)));
}
else if (amuletOfChemistryUsedMatcher.find())
{
final String match = amuletOfChemistryUsedMatcher.group(1);
int charges = 1;
if (!match.equals("one"))
{
charges = Integer.parseInt(match);
}
updateAmuletOfChemistryCharges(charges);
}
else if (amuletOfChemistryBreakMatcher.find())
{
notifier.notify(config.amuletOfChemistryNotification(), "Your amulet of chemistry has crumbled to dust.");
updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES);
}
else if (amuletOfBountyCheckMatcher.find())
{
updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyCheckMatcher.group(1)));
}
else if (amuletOfBountyUsedMatcher.find())
{
updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyUsedMatcher.group(1)));
}
else if (message.equals(AMULET_OF_BOUNTY_BREAK_TEXT))
{
updateAmuletOfBountyCharges(MAX_AMULET_OF_BOUNTY_CHARGES);
}
else if (message.contains(BINDING_BREAK_TEXT))
{
notifier.notify(config.bindingNotification(), BINDING_BREAK_TEXT);
// This chat message triggers before the used message so add 1 to the max charges to ensure proper sync
updateBindingNecklaceCharges(MAX_BINDING_CHARGES + 1);
}
else if (bindingNecklaceUsedMatcher.find())
{
final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT);
if (equipment.contains(ItemID.BINDING_NECKLACE))
{
updateBindingNecklaceCharges(getItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE) - 1);
}
}
else if (bindingNecklaceCheckMatcher.find())
{
final String match = bindingNecklaceCheckMatcher.group(1);
int charges = 1;
if (!match.equals("one"))
{
charges = Integer.parseInt(match);
}
updateBindingNecklaceCharges(charges);
}
else if (ringOfForgingCheckMatcher.find())
{
final String match = ringOfForgingCheckMatcher.group(1);
int charges = 1;
if (!match.equals("one"))
{
charges = Integer.parseInt(match);
}
updateRingOfForgingCharges(charges);
}
else if (message.equals(RING_OF_FORGING_USED_TEXT) || message.equals(RING_OF_FORGING_VARROCK_PLATEBODY))
{
final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY);
final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT);
// Determine if the player smelted with a Ring of Forging equipped.
if (equipment == null)
{
return;
}
if (equipment.contains(ItemID.RING_OF_FORGING) && (message.equals(RING_OF_FORGING_USED_TEXT) || inventory.count(ItemID.IRON_ORE) > 1))
{
int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING) - 1, 0, MAX_RING_OF_FORGING_CHARGES);
updateRingOfForgingCharges(charges);
}
}
else if (message.equals(RING_OF_FORGING_BREAK_TEXT))
{
notifier.notify(config.ringOfForgingNotification(), "Your ring of forging has melted.");
// This chat message triggers before the used message so add 1 to the max charges to ensure proper sync
updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES + 1);
}
else if (chronicleAddMatcher.find())
{
final String match = chronicleAddMatcher.group(1);
if (match.equals("one"))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1);
}
else
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(match));
}
}
else if (chronicleUseAndCheckMatcher.find())
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(chronicleUseAndCheckMatcher.group(1)));
}
else if (message.equals(CHRONICLE_ONE_CHARGE_TEXT))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1);
}
else if (message.equals(CHRONICLE_EMPTY_TEXT) || message.equals(CHRONICLE_NO_CHARGES_TEXT))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 0);
}
else if (message.equals(CHRONICLE_FULL_TEXT))
{
setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1000);
}
else if (slaughterActivateMatcher.find())
{
final String found = slaughterActivateMatcher.group(1);
if (found == null)
{
updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES);
notifier.notify(config.slaughterNotification(), BRACELET_OF_SLAUGHTER_BREAK_TEXT);
}
else
{
updateBraceletOfSlaughterCharges(Integer.parseInt(found));
}
}
else if (slaughterCheckMatcher.find())
{
updateBraceletOfSlaughterCharges(Integer.parseInt(slaughterCheckMatcher.group(1)));
}
else if (expeditiousActivateMatcher.find())
{
final String found = expeditiousActivateMatcher.group(1);
if (found == null)
{
updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES);
notifier.notify(config.expeditiousNotification(), EXPEDITIOUS_BRACELET_BREAK_TEXT);
}
else
{
updateExpeditiousBraceletCharges(Integer.parseInt(found));
}
}
else if (expeditiousCheckMatcher.find())
{
updateExpeditiousBraceletCharges(Integer.parseInt(expeditiousCheckMatcher.group(1)));
}
else if (bloodEssenceCheckMatcher.find())
{
updateBloodEssenceCharges(Integer.parseInt(bloodEssenceCheckMatcher.group(1)));
}
else if (bloodEssenceExtractMatcher.find())
{
updateBloodEssenceCharges(getItemCharges(ItemChargeConfig.KEY_BLOOD_ESSENCE) - Integer.parseInt(bloodEssenceExtractMatcher.group(1)));
}
else if (message.contains(BLOOD_ESSENCE_ACTIVATE_TEXT))
{
updateBloodEssenceCharges(MAX_BLOOD_ESSENCE_CHARGES);
}
else if (braceletOfClayCheckMatcher.find())
{
updateBraceletOfClayCharges(Integer.parseInt(braceletOfClayCheckMatcher.group(1)));
}
else if (message.equals(BRACELET_OF_CLAY_USE_TEXT) || message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN))
{
final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT);
// Determine if the player mined with a Bracelet of Clay equipped.
if (equipment != null && equipment.contains(ItemID.BRACELET_OF_CLAY))
{
final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY);
// Charge is not used if only 1 inventory slot is available when mining in Prifddinas
boolean ignore = inventory != null
&& inventory.count() == 27
&& message.equals(BRACELET_OF_CLAY_USE_TEXT_TRAHAEARN);
if (!ignore)
{
int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_BRACELET_OF_CLAY) - 1, 0, MAX_BRACELET_OF_CLAY_CHARGES);
updateBraceletOfClayCharges(charges);
}
}
}
else if (message.equals(BRACELET_OF_CLAY_BREAK_TEXT))
{
notifier.notify(config.braceletOfClayNotification(), "Your bracelet of clay has crumbled to dust");
updateBraceletOfClayCharges(MAX_BRACELET_OF_CLAY_CHARGES);
}
}
} | @Test
public void testBraceletOfClayCheck()
{
ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", CHECK_BRACELET_OF_CLAY, "", 0);
itemChargePlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration(ItemChargeConfig.GROUP, ItemChargeConfig.KEY_BRACELET_OF_CLAY, 13);
} |
public final T getLast() {
return this.lastNode;
} | @Test
public void testGetLast() {
assertThat(this.list.getLast()).as("Empty list should return null on getLast()").isNull();
this.list.add( this.node1 );
assertThat(this.node1).as("Last node should be node1").isSameAs(this.list.getLast());
this.list.add( this.node2 );
assertThat(this.node2).as("Last node should be node2").isSameAs(this.list.getLast());
this.list.add( this.node3 );
assertThat(this.node3).as("Last node should be node3").isSameAs(this.list.getLast());
} |
public static String squeezeStatement(String sql)
{
TokenSource tokens = getLexer(sql, ImmutableSet.of());
StringBuilder sb = new StringBuilder();
while (true) {
Token token = tokens.nextToken();
if (token.getType() == Token.EOF) {
break;
}
if (token.getType() == SqlBaseLexer.WS) {
sb.append(' ');
}
else {
sb.append(token.getText());
}
}
return sb.toString().trim();
} | @Test
public void testSqueezeStatementError()
{
String sql = "select * from z#oops";
assertEquals(squeezeStatement(sql), "select * from z#oops");
} |
public void update(int key, int oldValue, int value) {
remove(key, oldValue);
insert(key, value);
} | @Test
public void testUpdate() {
GHSortedCollection instance = new GHSortedCollection();
assertTrue(instance.isEmpty());
instance.insert(0, 10);
instance.insert(1, 11);
assertEquals(10, instance.peekValue());
assertEquals(2, instance.getSize());
instance.update(0, 10, 12);
assertEquals(11, instance.peekValue());
assertEquals(2, instance.getSize());
} |
public int getOutputBufferProcessors() {
return outputBufferProcessors;
} | @Test
public void defaultProcessorNumbers() throws Exception {
// number of buffer processors:
// process, output
final int[][] baseline = {
{1, 1}, // 1 available processor
{1, 1}, // 2 available processors
{2, 1}, // 3 available processors
{2, 1}, // 4 available processors
{2, 1}, // 5 available processors
{3, 2}, // 6 available processors
{3, 2}, // 7 available processors
{4, 2}, // 8 available processors
{4, 2}, // 9 available processors
{4, 2}, // 10 available processors
{5, 2}, // 11 available processors
{5, 3}, // 12 available processors
{5, 3}, // 13 available processors
{6, 3}, // 14 available processors
{6, 3}, // 15 available processors
{6, 3}, // 16 available processors
};
final int[][] actual = new int[baseline.length][2];
for (int i = 0; i < actual.length; i++) {
try (final var tools = Mockito.mockStatic(Tools.class)) {
tools.when(Tools::availableProcessors).thenReturn(i + 1);
final Configuration config = initConfig(new Configuration(), validProperties);
actual[i][0] = config.getProcessBufferProcessors();
actual[i][1] = config.getOutputBufferProcessors();
}
}
assertThat(actual).isEqualTo(baseline);
} |
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws TbNodeException {
ctx.tellNext(msg, checkMatches(msg) ? TbNodeConnectionType.TRUE : TbNodeConnectionType.FALSE);
} | @Test
void givenTypeCircle_whenOnMsg_thenFalse() throws TbNodeException {
// GIVEN
var config = new TbGpsGeofencingFilterNodeConfiguration().defaultConfiguration();
config.setPerimeterType(PerimeterType.CIRCLE);
node.init(ctx, new TbNodeConfiguration(JacksonUtil.valueToTree(config)));
DeviceId deviceId = new DeviceId(UUID.randomUUID());
TbMsgMetaData metadata = getMetadataForNewVersionCirclePerimeter();
TbMsg msg = getTbMsg(deviceId, metadata,
POINT_OUTSIDE_CIRCLE.getLatitude(), POINT_OUTSIDE_CIRCLE.getLongitude());
// WHEN
node.onMsg(ctx, msg);
// THEN
ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
verify(ctx, times(1)).tellNext(newMsgCaptor.capture(), eq(TbNodeConnectionType.FALSE));
verify(ctx, never()).tellFailure(any(), any());
TbMsg newMsg = newMsgCaptor.getValue();
assertThat(newMsg).isNotNull();
assertThat(newMsg).isSameAs(msg);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.