focal_method
stringlengths 13
60.9k
| test_case
stringlengths 25
109k
|
---|---|
@Override
public List<Intent> compile(SinglePointToMultiPointIntent intent,
List<Intent> installable) {
Set<Link> links = new HashSet<>();
final boolean allowMissingPaths = intentAllowsPartialFailure(intent);
boolean hasPaths = false;
boolean missingSomePaths = false;
for (ConnectPoint egressPoint : intent.egressPoints()) {
if (egressPoint.deviceId().equals(intent.ingressPoint().deviceId())) {
// Do not need to look for paths, since ingress and egress
// devices are the same.
if (deviceService.isAvailable(egressPoint.deviceId())) {
hasPaths = true;
} else {
missingSomePaths = true;
}
continue;
}
Path path = getPath(intent, intent.ingressPoint().deviceId(), egressPoint.deviceId());
if (path != null) {
hasPaths = true;
links.addAll(path.links());
} else {
missingSomePaths = true;
}
}
// Allocate bandwidth if a bandwidth constraint is set
ConnectPoint ingressCP = intent.filteredIngressPoint().connectPoint();
List<ConnectPoint> egressCPs =
intent.filteredEgressPoints().stream()
.map(fcp -> fcp.connectPoint())
.collect(Collectors.toList());
List<ConnectPoint> pathCPs =
links.stream()
.flatMap(l -> Stream.of(l.src(), l.dst()))
.collect(Collectors.toList());
pathCPs.add(ingressCP);
pathCPs.addAll(egressCPs);
allocateBandwidth(intent, pathCPs);
if (!hasPaths) {
throw new IntentException("Cannot find any path between ingress and egress points.");
} else if (!allowMissingPaths && missingSomePaths) {
throw new IntentException("Missing some paths between ingress and egress points.");
}
Intent result = LinkCollectionIntent.builder()
.appId(intent.appId())
.key(intent.key())
.selector(intent.selector())
.treatment(intent.treatment())
.links(links)
.filteredIngressPoints(ImmutableSet.of(intent.filteredIngressPoint()))
.filteredEgressPoints(intent.filteredEgressPoints())
.priority(intent.priority())
.applyTreatmentOnEgress(true)
.constraints(intent.constraints())
.resourceGroup(intent.resourceGroup())
.build();
return Collections.singletonList(result);
}
|
@Test
public void testFilteredConnectPointIntent() {
FilteredConnectPoint ingress =
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
Set<FilteredConnectPoint> egress = ImmutableSet.of(
new FilteredConnectPoint(new ConnectPoint(DID_3, PORT_1),
DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("100")).build()),
new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_1),
DefaultTrafficSelector.builder().matchVlanId(VlanId.vlanId("200")).build())
);
SinglePointToMultiPointIntent intent = makeIntent(ingress, egress, selector);
String[] hops = {S2};
SinglePointToMultiPointIntentCompiler compiler = makeCompiler(hops);
assertThat(compiler, is(notNullValue()));
List<Intent> result = compiler.compile(intent, null);
assertThat(result, is(notNullValue()));
assertThat(result, hasSize(1));
Intent resultIntent = result.get(0);
assertThat(resultIntent, instanceOf(LinkCollectionIntent.class));
if (resultIntent instanceof LinkCollectionIntent) {
LinkCollectionIntent linkIntent = (LinkCollectionIntent) resultIntent;
assertThat(linkIntent.links(), hasSize(3));
assertThat(linkIntent.links(), linksHasPath(S1, S2));
assertThat(linkIntent.links(), linksHasPath(S2, S3));
assertThat(linkIntent.links(), linksHasPath(S2, S4));
Set<FilteredConnectPoint> ingressPoints = linkIntent.filteredIngressPoints();
assertThat("Link collection ingress points do not match base intent",
ingressPoints.size() == 1 && ingressPoints.contains(intent.filteredIngressPoint()));
assertThat("Link collection egress points do not match base intent",
linkIntent.filteredEgressPoints().equals(intent.filteredEgressPoints()));
}
assertThat("key is inherited", resultIntent.key(), is(intent.key()));
}
|
@Override
public String getName() {
return name;
}
|
@Test
public void testEqualsAndHashCode() {
assumeDifferentHashCodes();
EqualsVerifier.forClass(RingbufferConfig.class)
.suppress(Warning.NULL_FIELDS, Warning.NONFINAL_FIELDS)
.withPrefabValues(RingbufferStoreConfigReadOnly.class,
new RingbufferStoreConfigReadOnly(new RingbufferStoreConfig().setClassName("red")),
new RingbufferStoreConfigReadOnly(new RingbufferStoreConfig().setClassName("black")))
.withPrefabValues(MergePolicyConfig.class,
new MergePolicyConfig(PutIfAbsentMergePolicy.class.getName(), 100),
new MergePolicyConfig(DiscardMergePolicy.class.getName(), 200))
.verify();
}
|
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) {
OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers);
if (filteredOpenAPI == null) {
return filteredOpenAPI;
}
OpenAPI clone = new OpenAPI();
clone.info(filteredOpenAPI.getInfo());
clone.openapi(filteredOpenAPI.getOpenapi());
clone.jsonSchemaDialect(filteredOpenAPI.getJsonSchemaDialect());
clone.setSpecVersion(filteredOpenAPI.getSpecVersion());
clone.setExtensions(filteredOpenAPI.getExtensions());
clone.setExternalDocs(filteredOpenAPI.getExternalDocs());
clone.setSecurity(filteredOpenAPI.getSecurity());
clone.setServers(filteredOpenAPI.getServers());
clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags()));
final Set<String> allowedTags = new HashSet<>();
final Set<String> filteredTags = new HashSet<>();
Paths clonedPaths = new Paths();
if (filteredOpenAPI.getPaths() != null) {
for (String resourcePath : filteredOpenAPI.getPaths().keySet()) {
PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath);
PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers);
PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags);
if (clonedPathItem != null) {
if (!clonedPathItem.readOperations().isEmpty()) {
clonedPaths.addPathItem(resourcePath, clonedPathItem);
}
}
}
clone.paths(clonedPaths);
}
filteredTags.removeAll(allowedTags);
final List<Tag> tags = clone.getTags();
if (tags != null && !filteredTags.isEmpty()) {
tags.removeIf(tag -> filteredTags.contains(tag.getName()));
if (clone.getTags().isEmpty()) {
clone.setTags(null);
}
}
if (filteredOpenAPI.getWebhooks() != null) {
for (String resourcePath : filteredOpenAPI.getWebhooks().keySet()) {
PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath);
PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers);
PathItem clonedPathItem = cloneFilteredPathItem(filter,filteredPathItem, resourcePath, params, cookies, headers, allowedTags, filteredTags);
if (clonedPathItem != null) {
if (!clonedPathItem.readOperations().isEmpty()) {
clone.addWebhooks(resourcePath, clonedPathItem);
}
}
}
}
if (filteredOpenAPI.getComponents() != null) {
clone.components(new Components());
clone.getComponents().setSchemas(filterComponentsSchema(filter, filteredOpenAPI.getComponents().getSchemas(), params, cookies, headers));
clone.getComponents().setSecuritySchemes(filteredOpenAPI.getComponents().getSecuritySchemes());
clone.getComponents().setCallbacks(filteredOpenAPI.getComponents().getCallbacks());
clone.getComponents().setExamples(filteredOpenAPI.getComponents().getExamples());
clone.getComponents().setExtensions(filteredOpenAPI.getComponents().getExtensions());
clone.getComponents().setHeaders(filteredOpenAPI.getComponents().getHeaders());
clone.getComponents().setLinks(filteredOpenAPI.getComponents().getLinks());
clone.getComponents().setParameters(filteredOpenAPI.getComponents().getParameters());
clone.getComponents().setRequestBodies(filteredOpenAPI.getComponents().getRequestBodies());
clone.getComponents().setResponses(filteredOpenAPI.getComponents().getResponses());
clone.getComponents().setPathItems(filteredOpenAPI.getComponents().getPathItems());
}
if (filter.isRemovingUnreferencedDefinitions()) {
clone = removeBrokenReferenceDefinitions(clone);
}
return clone;
}
|
@Test
public void shouldNotRemoveGoodRefs() throws IOException {
final OpenAPI openAPI = getOpenAPI(RESOURCE_PATH);
assertNotNull(openAPI.getComponents().getSchemas().get("PetHeader"));
final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter();
final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null);
assertNotNull(filtered.getComponents().getSchemas().get("PetHeader"));
assertNotNull(filtered.getComponents().getSchemas().get("Category"));
}
|
@Override
public String toString() {
return toString(false, null, BitcoinNetwork.MAINNET);
}
|
@Test
public void testCanonicalSigs() throws Exception {
// Tests the canonical sigs from Bitcoin Core unit tests
InputStream in = getClass().getResourceAsStream("sig_canonical.json");
// Poor man's JSON parser (because pulling in a lib for this is overkill)
while (in.available() > 0) {
while (in.available() > 0 && in.read() != '"') ;
if (in.available() < 1)
break;
StringBuilder sig = new StringBuilder();
int c;
while (in.available() > 0 && (c = in.read()) != '"')
sig.append((char)c);
assertTrue(TransactionSignature.isEncodingCanonical(ByteUtils.parseHex(sig.toString())));
}
in.close();
}
|
String driverPath(File homeDir, Provider provider) {
String dirPath = provider.path;
File dir = new File(homeDir, dirPath);
if (!dir.exists()) {
throw new MessageException("Directory does not exist: " + dirPath);
}
List<File> files = new ArrayList<>(FileUtils.listFiles(dir, new String[] {"jar"}, false));
if (files.isEmpty()) {
throw new MessageException("Directory does not contain JDBC driver: " + dirPath);
}
if (files.size() > 1) {
throw new MessageException("Directory must contain only one JAR file: " + dirPath);
}
return files.get(0).getAbsolutePath();
}
|
@Test
public void driver_dir_does_not_exist() {
assertThatThrownBy(() -> underTest.driverPath(homeDir, Provider.ORACLE))
.isInstanceOf(MessageException.class)
.hasMessage("Directory does not exist: extensions/jdbc-driver/oracle");
}
|
@Override
public void incrementThreads() {
consumeTokens();
super.incrementThreads();
}
|
@Test
public void testIncrementThreads()
throws Exception {
// set test time first
_timeMillis = 100;
TestTokenSchedulerGroup group = new TestTokenSchedulerGroup();
int availableTokens = group.getAvailableTokens();
// verify token count is correctly set
assertEquals(availableTokens,
TestTokenSchedulerGroup.NUM_TOKENS_PER_MS * TestTokenSchedulerGroup.TOKEN_LIFETIME_MS);
// no threads in use...incrementing time has no effect
_timeMillis += 2 * TestTokenSchedulerGroup.TOKEN_LIFETIME_MS;
availableTokens = group.getAvailableTokens();
int startTime = _timeMillis;
assertEquals(availableTokens,
TestTokenSchedulerGroup.NUM_TOKENS_PER_MS * TestTokenSchedulerGroup.TOKEN_LIFETIME_MS);
int nThreads = 1;
incrementThreads(group, nThreads);
assertEquals(group.getThreadsInUse(), nThreads);
assertEquals(group.getAvailableTokens(), availableTokens);
// advance time
int timeIncrement = 20;
_timeMillis += timeIncrement;
group.decrementThreads();
assertEquals(group.getThreadsInUse(), 0);
assertEquals(group.getAvailableTokens(), availableTokens - timeIncrement * nThreads);
// more threads
availableTokens = group.getAvailableTokens();
nThreads = 5;
incrementThreads(group, nThreads);
assertEquals(group.getThreadsInUse(), nThreads);
// advance time now
_timeMillis += timeIncrement;
assertEquals(group.getAvailableTokens(), availableTokens - timeIncrement * nThreads);
// simple getAvailableTokens() updates tokens and reservedThreads has no effect
group.addReservedThreads(2 * nThreads);
availableTokens = group.getAvailableTokens();
timeIncrement = 10;
_timeMillis += timeIncrement;
assertEquals(group.getAvailableTokens(), availableTokens - timeIncrement * nThreads);
availableTokens = group.getAvailableTokens();
// decrement some threads
decrementThreads(group, 2);
nThreads -= 2;
_timeMillis += timeIncrement;
assertEquals(group.getAvailableTokens(), availableTokens - timeIncrement * nThreads);
// 3 threads still in use. Advance time beyond time quantum
availableTokens = group.getAvailableTokens();
int pendingTimeInQuantum = startTime + TestTokenSchedulerGroup.TOKEN_LIFETIME_MS - _timeMillis;
_timeMillis = startTime + TestTokenSchedulerGroup.TOKEN_LIFETIME_MS + timeIncrement;
int timeAdvance = pendingTimeInQuantum + timeIncrement;
// these are "roughly" the tokens in use since we apply decay. So we don't test for exact value
int expectedTokens =
TestTokenSchedulerGroup.NUM_TOKENS_PER_MS * TestTokenSchedulerGroup.TOKEN_LIFETIME_MS - timeAdvance * nThreads;
assertTrue(group.getAvailableTokens() < expectedTokens);
availableTokens = group.getAvailableTokens();
// increment by multiple quantums
_timeMillis = startTime + 3 * TestTokenSchedulerGroup.TOKEN_LIFETIME_MS + timeIncrement;
expectedTokens = TestTokenSchedulerGroup.NUM_TOKENS_PER_MS * TestTokenSchedulerGroup.TOKEN_LIFETIME_MS
- timeIncrement * nThreads;
assertTrue(group.getAvailableTokens() < expectedTokens);
}
|
@Override
public void updateHost(K8sHost host) {
checkNotNull(host, ERR_NULL_HOST);
hostStore.updateHost(host);
log.info(String.format(MSG_HOST, host.hostIp().toString(), MSG_UPDATED));
}
|
@Test
public void testAddNodesToHost() {
K8sHost updated = HOST_2.updateNodeNames(ImmutableSet.of("3", "4", "5"));
target.updateHost(updated);
validateEvents(K8S_HOST_UPDATED, K8S_NODES_ADDED);
}
|
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
int time = payload.getByteBuf().readUnsignedMediumLE();
if (0 == time) {
return MySQLTimeValueUtils.ZERO_OF_TIME;
}
int minuteSecond = Math.abs(time) % 10000;
return String.format("%02d:%02d:%02d", time / 10000, minuteSecond / 100, minuteSecond % 100);
}
|
@Test
void assertReadNullTime() {
when(payload.getByteBuf()).thenReturn(byteBuf);
when(byteBuf.readUnsignedMediumLE()).thenReturn(0);
assertThat(new MySQLTimeBinlogProtocolValue().read(columnDef, payload), is(MySQLTimeValueUtils.ZERO_OF_TIME));
}
|
public void isAnyOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
isIn(accumulate(first, second, rest));
}
|
@Test
public void isAnyOfJustTwo() {
assertThat("b").isAnyOf("a", "b");
}
|
@Override
public int read() {
if (nextChar == UNSET || nextChar >= buf.length) {
fill();
if (nextChar == UNSET) {
return END_OF_STREAM;
}
}
byte signedByte = buf[nextChar];
nextChar++;
return signedByte & 0xFF;
}
|
@Test
void read_from_ClosableIterator_with_single_empty_line() throws IOException {
assertThat(read(create(""))).isEmpty();
}
|
@Override
@SuppressWarnings("deprecation")
public HttpClientOperations addHandler(ChannelHandler handler) {
super.addHandler(handler);
return this;
}
|
@Test
void addEncoderReplaysLastHttp() {
ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
EmbeddedChannel channel = new EmbeddedChannel();
new HttpClientOperations(() -> channel, ConnectionObserver.emptyListener(),
ClientCookieEncoder.STRICT, ClientCookieDecoder.STRICT, ReactorNettyHttpMessageLogFactory.INSTANCE)
.addHandler(new JsonObjectDecoder());
channel.writeInbound(new DefaultLastHttpContent(buf));
assertThat(channel.pipeline().names()).first().isEqualTo("JsonObjectDecoder$extractor");
Object content = channel.readInbound();
assertThat(content).isInstanceOf(ByteBuf.class);
((ByteBuf) content).release();
content = channel.readInbound();
assertThat(content).isInstanceOf(LastHttpContent.class);
((LastHttpContent) content).release();
content = channel.readInbound();
assertThat(content).isNull();
}
|
@Override
public synchronized void execute() {
boolean debugMode = conf.isLoadBalancerDebugModeEnabled() || log.isDebugEnabled();
if (debugMode) {
log.info("Load balancer enabled: {}, Shedding enabled: {}.",
conf.isLoadBalancerEnabled(), conf.isLoadBalancerSheddingEnabled());
}
if (!isLoadBalancerSheddingEnabled()) {
if (debugMode) {
log.info("The load balancer or load balancer shedding already disabled. Skipping.");
}
return;
}
// Remove bundles who have been unloaded for longer than the grace period from the recently unloaded map.
final long timeout = System.currentTimeMillis()
- TimeUnit.MINUTES.toMillis(conf.getLoadBalancerSheddingGracePeriodMinutes());
recentlyUnloadedBundles.keySet().removeIf(e -> recentlyUnloadedBundles.get(e) < timeout);
long asyncOpTimeoutMs = conf.getNamespaceBundleUnloadingTimeoutMs();
synchronized (namespaceUnloadStrategy) {
try {
Boolean isChannelOwner = channel.isChannelOwnerAsync().get(asyncOpTimeoutMs, TimeUnit.MILLISECONDS);
if (!isChannelOwner) {
if (debugMode) {
log.info("Current broker is not channel owner. Skipping.");
}
return;
}
List<String> availableBrokers = context.brokerRegistry().getAvailableBrokersAsync()
.get(asyncOpTimeoutMs, TimeUnit.MILLISECONDS);
if (debugMode) {
log.info("Available brokers: {}", availableBrokers);
}
if (availableBrokers.size() <= 1) {
log.info("Only 1 broker available: no load shedding will be performed. Skipping.");
return;
}
final Set<UnloadDecision> decisions = namespaceUnloadStrategy
.findBundlesForUnloading(context, recentlyUnloadedBundles, recentlyUnloadedBrokers);
if (debugMode) {
log.info("[{}] Unload decision result: {}",
namespaceUnloadStrategy.getClass().getSimpleName(), decisions);
}
if (decisions.isEmpty()) {
if (debugMode) {
log.info("[{}] Unload decision unloads is empty. Skipping.",
namespaceUnloadStrategy.getClass().getSimpleName());
}
return;
}
List<CompletableFuture<Void>> futures = new ArrayList<>();
unloadBrokers.clear();
decisions.forEach(decision -> {
if (decision.getLabel() == Success) {
Unload unload = decision.getUnload();
log.info("[{}] Unloading bundle: {}",
namespaceUnloadStrategy.getClass().getSimpleName(), unload);
futures.add(unloadManager.waitAsync(channel.publishUnloadEventAsync(unload),
unload.serviceUnit(), decision, asyncOpTimeoutMs, TimeUnit.MILLISECONDS)
.thenAccept(__ -> {
unloadBrokers.add(unload.sourceBroker());
recentlyUnloadedBundles.put(unload.serviceUnit(), System.currentTimeMillis());
recentlyUnloadedBrokers.put(unload.sourceBroker(), System.currentTimeMillis());
}));
}
});
FutureUtil.waitForAll(futures)
.whenComplete((__, ex) -> counter.updateUnloadBrokerCount(unloadBrokers.size()))
.get(asyncOpTimeoutMs, TimeUnit.MILLISECONDS);
} catch (Exception ex) {
log.error("[{}] Namespace unload has exception.",
namespaceUnloadStrategy.getClass().getSimpleName(), ex);
} finally {
if (counter.updatedAt() > counterLastUpdatedAt) {
unloadMetrics.set(counter.toMetrics(pulsar.getAdvertisedAddress()));
counterLastUpdatedAt = counter.updatedAt();
}
}
}
}
|
@Test(timeOut = 30 * 1000)
public void testExecuteSuccess() {
AtomicReference<List<Metrics>> reference = new AtomicReference<>();
UnloadCounter counter = new UnloadCounter();
LoadManagerContext context = setupContext();
BrokerRegistry registry = context.brokerRegistry();
ServiceUnitStateChannel channel = mock(ServiceUnitStateChannel.class);
UnloadManager unloadManager = mock(UnloadManager.class);
PulsarService pulsar = mock(PulsarService.class);
NamespaceUnloadStrategy unloadStrategy = mock(NamespaceUnloadStrategy.class);
doReturn(CompletableFuture.completedFuture(true)).when(channel).isChannelOwnerAsync();
doReturn(CompletableFuture.completedFuture(Lists.newArrayList("broker-1", "broker-2")))
.when(registry).getAvailableBrokersAsync();
doReturn(CompletableFuture.completedFuture(null)).when(channel).publishUnloadEventAsync(any());
doReturn(CompletableFuture.completedFuture(null)).when(unloadManager)
.waitAsync(any(), any(), any(), anyLong(), any());
UnloadDecision decision = new UnloadDecision();
Unload unload = new Unload("broker-1", "bundle-1");
decision.setUnload(unload);
decision.setLabel(UnloadDecision.Label.Success);
doReturn(Set.of(decision)).when(unloadStrategy).findBundlesForUnloading(any(), any(), any());
UnloadScheduler scheduler = new UnloadScheduler(pulsar, loadManagerExecutor, unloadManager, context,
channel, unloadStrategy, counter, reference);
scheduler.execute();
verify(channel, times(1)).publishUnloadEventAsync(eq(unload));
// Test empty unload.
UnloadDecision emptyUnload = new UnloadDecision();
doReturn(Set.of(emptyUnload)).when(unloadStrategy).findBundlesForUnloading(any(), any(), any());
scheduler.execute();
verify(channel, times(1)).publishUnloadEventAsync(eq(unload));
}
|
@Override
protected EnumDeclaration create(CompilationUnit compilationUnit) {
EnumDeclaration lambdaClass = super.create(compilationUnit);
boolean hasDroolsParameter = lambdaParameters.stream().anyMatch(this::isDroolsParameter);
if (hasDroolsParameter) {
bitMaskVariables.forEach(vd -> vd.generateBitMaskField(lambdaClass));
}
return lambdaClass;
}
|
@Test
public void createConsequenceWithMultipleFieldUpdate() {
ArrayList<String> fields = new ArrayList<>();
fields.add("\"age\"");
fields.add("\"likes\"");
MaterializedLambda.BitMaskVariable bitMaskVariable = new MaterializedLambda.BitMaskVariableWithFields("DomainClassesMetadata53448E6B9A07CB05B976425EF329E308.org_drools_modelcompiler_domain_Person_Metadata_INSTANCE", fields, "mask_$p");
String consequenceBlock = "(org.drools.model.Drools drools, org.drools.model.codegen.execmodel.domain.Person $p) -> {{ ($p).setAge($p.getAge() + 1); ($p).setLikes(\"Cheese\"); drools.update($p,mask_$p); }}";
CreatedClass aClass = new MaterializedLambdaConsequence("defaultpkg",
"defaultpkg.Rules53448E6B9A07CB05B976425EF329E308",
List.of(bitMaskVariable))
.create(consequenceBlock, new ArrayList<>(), new ArrayList<>());
String classNameWithPackage = aClass.getClassNameWithPackage();
// There is no easy way to retrieve the originally created "hashcode" because it is calculated over a CompilationUnit that soon after is modified;
// so current "CreatedClass" contains a CompilationUnit that is different from the one used to calculate the hashcode
String expectedPackageName = classNameWithPackage.substring(0, classNameWithPackage.lastIndexOf('.'));
String expectedClassName = classNameWithPackage.substring(classNameWithPackage.lastIndexOf('.')+1);
//language=JAVA
String expectedResult = "" +
"package PACKAGE_TOREPLACE;\n" +
"\n" +
"import static defaultpkg.Rules53448E6B9A07CB05B976425EF329E308.*; \n" +
"import org.drools.modelcompiler.dsl.pattern.D; " +
"\n" +
"" +
"@org.drools.compiler.kie.builder.MaterializedLambda()\n" +
"public enum CLASS_TOREPLACE implements org.drools.model.functions.Block2<org.drools.model.Drools, org.drools.model.codegen.execmodel.domain.Person>, org.drools.model.functions.HashedExpression {\n" +
"\n" +
" INSTANCE;\n" +
" public static final String EXPRESSION_HASH = \"97D5F245AD110FEF0DE1D043C9DBB3B1\";\n" +
" public java.lang.String getExpressionHash() {\n" +
" return EXPRESSION_HASH;\n" +
" }" +
" private final org.drools.model.BitMask mask_$p = org.drools.model.BitMask.getPatternMask(DomainClassesMetadata53448E6B9A07CB05B976425EF329E308.org_drools_modelcompiler_domain_Person_Metadata_INSTANCE, \"age\", \"likes\");\n" +
"\n" +
" @Override()\n" +
" public void execute(org.drools.model.Drools drools, org.drools.model.codegen.execmodel.domain.Person $p) throws java.lang.Exception {\n" +
" {\n" +
" ($p).setAge($p.getAge() + 1);\n" +
" ($p).setLikes(\"Cheese\");\n" +
" drools.update($p, mask_$p);\n" +
" }\n" +
" }\n" +
"}";
// Workaround to keep the "//language=JAVA" working
expectedResult = expectedResult
.replace("PACKAGE_TOREPLACE", expectedPackageName)
.replace("CLASS_TOREPLACE", expectedClassName);
verifyCreatedClass(aClass, expectedResult);
}
|
@Override
public List<URI> get() {
return resultsCachingSupplier.get();
}
|
@Test
void testAutomaticDiscoveryOneUnconfigured() {
final IndexerDiscoveryProvider provider = new IndexerDiscoveryProvider(
Collections.emptyList(),
1,
Duration.seconds(1),
preflightConfig(PreflightConfigResult.FINISHED),
nodes("http://localhost:9200", ""), // the second node is not configured yet, has no transport address
NOOP_CERT_PROVISIONER
);
Assertions.assertThat(provider.get())
.hasSize(1)
.extracting(URI::toString)
.contains("http://localhost:9200");
}
|
public void setProperty(String name, String value) {
if (value == null) {
return;
}
name = Introspector.decapitalize(name);
PropertyDescriptor prop = getPropertyDescriptor(name);
if (prop == null) {
addWarn("No such property [" + name + "] in " + objClass.getName() + ".");
} else {
try {
setProperty(prop, name, value);
} catch (PropertySetterException ex) {
addWarn("Failed to set property [" + name + "] to value \"" + value
+ "\". ", ex);
}
}
}
|
@Test
public void testSetProperty() {
{
House house = new House();
PropertySetter setter = new PropertySetter(house);
setter.setProperty("count", "10");
setter.setProperty("temperature", "33.1");
setter.setProperty("name", "jack");
setter.setProperty("open", "true");
assertEquals(10, house.getCount());
assertEquals(33.1d, (double) house.getTemperature(), 0.01);
assertEquals("jack", house.getName());
assertTrue(house.isOpen());
}
{
House house = new House();
PropertySetter setter = new PropertySetter(house);
setter.setProperty("Count", "10");
setter.setProperty("Name", "jack");
setter.setProperty("Open", "true");
assertEquals(10, house.getCount());
assertEquals("jack", house.getName());
assertTrue(house.isOpen());
}
}
|
@Deprecated
public String getConnectionPath() {
return getPath();
}
|
@Test
public void getConnectionPathTest() {
VFSFile file = new VFSFile();
String pvfsPath = "pvfs://someConnectionName/bucket/to/file/file.txt";
file.setPath( pvfsPath );
file.setConnection( "someConnectionName" );
Assert.assertEquals( pvfsPath, file.getConnectionPath() );
}
|
@Override
public double getDouble(final int columnIndex) throws SQLException {
return (double) ResultSetUtils.convertValue(mergeResultSet.getValue(columnIndex, double.class), double.class);
}
|
@Test
void assertGetDoubleWithColumnLabel() throws SQLException {
when(mergeResultSet.getValue(1, double.class)).thenReturn(1.0D);
assertThat(shardingSphereResultSet.getDouble("label"), is(1.0D));
}
|
public boolean acquire(long messageCreateTime) {
if (isDelayed(messageCreateTime)) {
return eventRateLimiter.tryAcquire();
}
return false;
}
|
@Test
public void testAcquire() throws InterruptedException {
double permitsPerSecond = 0.5;
Duration delayThreshold = Duration.ofMillis(1000);
MessageDelayedEventLimiter delayedEventLimiter =
new MessageDelayedEventLimiter(delayThreshold, permitsPerSecond);
long endTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10);
long actualAcquiredCount = 0;
while (System.currentTimeMillis() < endTime) {
boolean acquired =
delayedEventLimiter.acquire(
System.currentTimeMillis() - (delayThreshold.toMillis() * 10));
if (acquired) {
actualAcquiredCount++;
}
Thread.sleep(1);
}
long expectedAcquiredCount = (long) (TimeUnit.SECONDS.toSeconds(10) * permitsPerSecond);
Assertions.assertTrue(expectedAcquiredCount >= actualAcquiredCount);
}
|
static <T extends Type> String encodeArrayValues(Array<T> value) {
StringBuilder result = new StringBuilder();
for (Type type : value.getValue()) {
result.append(encode(type));
}
return result.toString();
}
|
@Test
public void testDynamicStructStaticArray() {
StaticArray3<Foo> array =
new StaticArray3<>(
Foo.class, new Foo("", ""), new Foo("id", "name"), new Foo("", ""));
assertEquals(
("0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000080"
+ "0000000000000000000000000000000000000000000000000000000000000002"
+ "6964000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000004"
+ "6e616d6500000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000040"
+ "0000000000000000000000000000000000000000000000000000000000000060"
+ "0000000000000000000000000000000000000000000000000000000000000000"
+ "0000000000000000000000000000000000000000000000000000000000000000"),
TypeEncoder.encodeArrayValues(array));
}
|
@VisibleForTesting
CompletableFuture<Optional<SendPushNotificationResult>> sendNotification(final PushNotification pushNotification) {
if (pushNotification.tokenType() == PushNotification.TokenType.APN && !pushNotification.urgent()) {
// APNs imposes a per-device limit on background push notifications; schedule a notification for some time in the
// future (possibly even now!) rather than sending a notification directly
return pushNotificationScheduler
.scheduleBackgroundApnsNotification(pushNotification.destination(), pushNotification.destinationDevice())
.whenComplete(logErrors())
.thenApply(ignored -> Optional.<SendPushNotificationResult>empty())
.toCompletableFuture();
}
final PushNotificationSender sender = switch (pushNotification.tokenType()) {
case FCM -> fcmSender;
case APN, APN_VOIP -> apnSender;
};
return sender.sendNotification(pushNotification).whenComplete((result, throwable) -> {
if (throwable == null) {
Tags tags = Tags.of("tokenType", pushNotification.tokenType().name(),
"notificationType", pushNotification.notificationType().name(),
"urgent", String.valueOf(pushNotification.urgent()),
"accepted", String.valueOf(result.accepted()),
"unregistered", String.valueOf(result.unregistered()));
if (result.errorCode().isPresent()) {
tags = tags.and("errorCode", result.errorCode().get());
}
Metrics.counter(SENT_NOTIFICATION_COUNTER_NAME, tags).increment();
if (result.unregistered() && pushNotification.destination() != null
&& pushNotification.destinationDevice() != null) {
handleDeviceUnregistered(pushNotification.destination(),
pushNotification.destinationDevice(),
pushNotification.tokenType(),
result.errorCode(),
result.unregisteredTimestamp());
}
if (result.accepted() &&
pushNotification.tokenType() == PushNotification.TokenType.APN_VOIP &&
pushNotification.notificationType() == PushNotification.NotificationType.NOTIFICATION &&
pushNotification.destination() != null &&
pushNotification.destinationDevice() != null) {
pushNotificationScheduler.scheduleRecurringApnsVoipNotification(
pushNotification.destination(),
pushNotification.destinationDevice())
.whenComplete(logErrors());
}
} else {
logger.debug("Failed to deliver {} push notification to {} ({})",
pushNotification.notificationType(), pushNotification.deviceToken(), pushNotification.tokenType(),
throwable);
Metrics.counter(FAILED_NOTIFICATION_COUNTER_NAME, "cause", throwable.getClass().getSimpleName()).increment();
}
})
.thenApply(Optional::of);
}
|
@Test
void testSendNotificationUnregisteredApnTokenUpdated() {
final Instant tokenTimestamp = Instant.now();
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final UUID aci = UUID.randomUUID();
when(device.getId()).thenReturn(Device.PRIMARY_ID);
when(device.getApnId()).thenReturn("apns-token");
when(device.getVoipApnId()).thenReturn("apns-voip-token");
when(device.getPushTimestamp()).thenReturn(tokenTimestamp.toEpochMilli());
when(account.getDevice(Device.PRIMARY_ID)).thenReturn(Optional.of(device));
when(account.getUuid()).thenReturn(aci);
when(accountsManager.getByAccountIdentifier(aci)).thenReturn(Optional.of(account));
final PushNotification pushNotification = new PushNotification(
"token", PushNotification.TokenType.APN_VOIP, PushNotification.NotificationType.NOTIFICATION, null, account, device, true);
when(apnSender.sendNotification(pushNotification))
.thenReturn(CompletableFuture.completedFuture(new SendPushNotificationResult(false, Optional.empty(), true, Optional.of(tokenTimestamp.minusSeconds(60)))));
when(pushNotificationScheduler.cancelScheduledNotifications(account, device))
.thenReturn(CompletableFuture.completedFuture(null));
pushNotificationManager.sendNotification(pushNotification);
verifyNoInteractions(fcmSender);
verify(accountsManager, never()).updateDevice(eq(account), eq(Device.PRIMARY_ID), any());
verify(device, never()).setVoipApnId(any());
verify(device, never()).setApnId(any());
verify(pushNotificationScheduler, never()).cancelScheduledNotifications(account, device);
}
|
@Override
public void onAddedJobGraph(JobID jobId) {
runIfStateIs(State.RUNNING, () -> handleAddedJobGraph(jobId));
}
|
@Test
void onAddedJobGraph_submitsRecoveredJob() throws Exception {
final CompletableFuture<JobGraph> submittedJobFuture = new CompletableFuture<>();
final TestingDispatcherGateway testingDispatcherGateway =
TestingDispatcherGateway.newBuilder()
.setSubmitFunction(
submittedJob -> {
submittedJobFuture.complete(submittedJob);
return CompletableFuture.completedFuture(Acknowledge.get());
})
.build();
dispatcherServiceFactory =
createFactoryBasedOnGenericSupplier(
() ->
TestingDispatcherGatewayService.newBuilder()
.setDispatcherGateway(testingDispatcherGateway)
.build());
try (final SessionDispatcherLeaderProcess dispatcherLeaderProcess =
createDispatcherLeaderProcess()) {
dispatcherLeaderProcess.start();
// wait first for the dispatcher service to be created
dispatcherLeaderProcess.getDispatcherGateway().get();
jobGraphStore.putJobGraph(JOB_GRAPH);
dispatcherLeaderProcess.onAddedJobGraph(JOB_GRAPH.getJobID());
final JobGraph submittedJobGraph = submittedJobFuture.get();
assertThat(submittedJobGraph.getJobID()).isEqualTo(JOB_GRAPH.getJobID());
}
}
|
public Properties getProperties()
{
return properties;
}
|
@Test
void testUriWithSocksProxy()
throws SQLException
{
PrestoDriverUri parameters = createDriverUri("presto://localhost:8080?socksProxy=localhost:1234");
assertUriPortScheme(parameters, 8080, "http");
Properties properties = parameters.getProperties();
assertEquals(properties.getProperty(SOCKS_PROXY.getKey()), "localhost:1234");
}
|
@Override
public Object convert(String value) {
if (isNullOrEmpty(value)) {
return value;
}
if (value.contains("=")) {
final Map<String, String> fields = new HashMap<>();
Matcher m = PATTERN.matcher(value);
while (m.find()) {
if (m.groupCount() != 2) {
continue;
}
fields.put(removeQuotes(m.group(1)), removeQuotes(m.group(2)));
}
return fields;
} else {
return Collections.emptyMap();
}
}
|
@Test
public void testFilterWithMixedSingleQuotedAndPlainValues() {
TokenizerConverter f = new TokenizerConverter(new HashMap<String, Object>());
@SuppressWarnings("unchecked")
Map<String, String> result = (Map<String, String>) f.convert("otters in k1='v1' k2=v2 more otters");
assertThat(result)
.hasSize(2)
.containsEntry("k1", "v1")
.containsEntry("k2", "v2");
}
|
@Override
public String toString() {
final String s = red.toString();
final StringBuilder h = new StringBuilder();
// Hex dump the small ones.
if (s.length() < 8) {
for (int i = 0; i < s.length(); i++) {
h.append(" ").append(Integer.toHexString(s.charAt(i)));
}
}
return "[" + given + "]-\"" + s + "\"" + (h.length() > 0 ? " (" + h + ")" : "");
}
|
@Test
public void testToString() throws IOException {
String data = "test";
InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
XmlInputStream instance = new XmlInputStream(stream);
int r = instance.read();
assertEquals('t', r);
String expResult = "[1]-\"t\" ( 74)";
String result = instance.toString();
assertEquals(expResult, result);
r = instance.read();
assertEquals('e', r);
expResult = "[2]-\"te\" ( 74 65)";
result = instance.toString();
assertEquals(expResult, result);
}
|
@ExecuteOn(TaskExecutors.IO)
@Post(uri = "/replay/by-query")
@Operation(tags = {"Executions"}, summary = "Create new executions from old ones filter by query parameters. Keep the flow revision")
public HttpResponse<?> replayByQuery(
@Parameter(description = "A string filter") @Nullable @QueryValue(value = "q") String query,
@Parameter(description = "A namespace filter prefix") @Nullable @QueryValue String namespace,
@Parameter(description = "A flow id filter") @Nullable @QueryValue String flowId,
@Parameter(description = "The start datetime") @Nullable @Format("yyyy-MM-dd'T'HH:mm[:ss][.SSS][XXX]") @QueryValue ZonedDateTime startDate,
@Parameter(description = "The end datetime") @Nullable @Format("yyyy-MM-dd'T'HH:mm[:ss][.SSS][XXX]") @QueryValue ZonedDateTime endDate,
@Parameter(description = "A time range filter relative to the current time", examples = {
@ExampleObject(name = "Filter last 5 minutes", value = "PT5M"),
@ExampleObject(name = "Filter last 24 hours", value = "P1D")
}) @Nullable @QueryValue Duration timeRange,
@Parameter(description = "A state filter") @Nullable @QueryValue List<State.Type> state,
@Parameter(description = "A labels filter as a list of 'key:value'") @Nullable @QueryValue @Format("MULTI") List<String> labels,
@Parameter(description = "The trigger execution id") @Nullable @QueryValue String triggerExecutionId,
@Parameter(description = "A execution child filter") @Nullable @QueryValue ExecutionRepositoryInterface.ChildFilter childFilter
) throws Exception {
validateTimeline(startDate, endDate);
var ids = executionRepository
.find(
query,
tenantService.resolveTenant(),
namespace,
flowId,
resolveAbsoluteDateTime(startDate, timeRange, ZonedDateTime.now()),
endDate,
state,
RequestUtils.toMap(labels),
triggerExecutionId,
childFilter
)
.map(Execution::getId)
.collectList()
.block();
return replayByIds(ids);
}
|
@Test
void replayByQuery() throws TimeoutException {
Execution execution1 = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested");
Execution execution2 = runnerUtils.runOne(null, "io.kestra.tests", "each-sequential-nested");
assertThat(execution1.getState().isTerminated(), is(true));
assertThat(execution2.getState().isTerminated(), is(true));
PagedResults<?> executions = client.toBlocking().retrieve(
GET("/api/v1/executions/search"), PagedResults.class
);
assertThat(executions.getTotal(), is(2L));
// replay executions
BulkResponse resumeResponse = client.toBlocking().retrieve(
HttpRequest.POST("/api/v1/executions/replay/by-query?namespace=io.kestra.tests", null),
BulkResponse.class
);
assertThat(resumeResponse.getCount(), is(2));
executions = client.toBlocking().retrieve(
GET("/api/v1/executions/search"), PagedResults.class
);
assertThat(executions.getTotal(), is(4L));
}
|
@Override
public void define(Context context) {
NewController controller = context.createController("api/developers")
.setDescription("Return data needed by SonarLint.")
.setSince("1.0");
actions.forEach(action -> action.define(controller));
controller.done();
}
|
@Test
public void definition() {
WebService.Context context = new WebService.Context();
underTest.define(context);
WebService.Controller controller = context.controller("api/developers");
assertThat(controller).isNotNull();
assertThat(controller.description()).isNotEmpty();
assertThat(controller.since()).isEqualTo("1.0");
assertThat(controller.actions()).extracting(WebService.Action::key).isNotEmpty();
}
|
@PublicAPI(usage = ACCESS)
public JavaClass getClassWithSimpleName(String className) {
return getValue(tryGetClassWithSimpleName(className),
"This package does not contain any class with simple name '%s'", className);
}
|
@Test
public void rejects_retrieving_non_existing_classes_by_simple_name() {
assertThatThrownBy(
() -> importDefaultPackage().getClassWithSimpleName(Object.class.getSimpleName())
)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("does not contain")
.hasMessageContaining(Object.class.getSimpleName());
}
|
private void merge(ContentNodeStats stats, int factor) {
for (Map.Entry<String, BucketSpaceStats> entry : stats.bucketSpaces.entrySet()) {
BucketSpaceStats statsToUpdate = bucketSpaces.get(entry.getKey());
if (statsToUpdate == null && factor == 1) {
statsToUpdate = BucketSpaceStats.empty();
bucketSpaces.put(entry.getKey(), statsToUpdate);
}
if (statsToUpdate != null) {
statsToUpdate.merge(entry.getValue(), factor);
}
}
}
|
@Test
void bucket_space_stats_can_transition_from_invalid_to_valid() {
BucketSpaceStats stats = BucketSpaceStats.invalid();
assertFalse(stats.valid());
stats.merge(BucketSpaceStats.of(5, 1), 1);
assertFalse(stats.valid());
stats.merge(BucketSpaceStats.invalid(), -1);
assertTrue(stats.valid());
assertEquals(BucketSpaceStats.of(5, 1), stats);
}
|
public MonitorBuilder username(String username) {
this.username = username;
return getThis();
}
|
@Test
void username() {
MonitorBuilder builder = MonitorBuilder.newBuilder();
builder.username("username");
Assertions.assertEquals("username", builder.build().getUsername());
}
|
public void registerStrategy(BatchingStrategy<?, ?, ?> strategy) {
_strategies.add(strategy);
}
|
@Test
public void testBatchWithTimeoutAndSingleton() {
RecordingStrategy<Integer, Integer, String> strategy =
new RecordingStrategy<Integer, Integer, String>((key, promise) -> promise.done(String.valueOf(key)), key -> key % 2) {
@Override
public void executeBatch(final Integer group, final Batch<Integer, String> batch) {
getScheduler().schedule(() -> {
super.executeBatch(group, batch);
}, 250, TimeUnit.MILLISECONDS);
}
};
_batchingSupport.registerStrategy(strategy);
Task<String> task = Task.par(strategy.batchable(0).withTimeout(10, TimeUnit.MILLISECONDS).recover("toExceptionName", e -> e.getClass().getName()),
strategy.batchable(1), strategy.batchable(2))
.map("concat", (s0, s1, s2) -> s0 + s1 + s2);
String result = runAndWait("TestBatchingSupport.testBatchWithTimeoutAndSingleton", task);
assertEquals(result, "java.util.concurrent.TimeoutException12");
assertTrue(strategy.getClassifiedKeys().contains(0));
assertTrue(strategy.getClassifiedKeys().contains(1));
assertTrue(strategy.getClassifiedKeys().contains(2));
assertEquals(strategy.getExecutedBatches().size(), 1);
assertEquals(strategy.getExecutedSingletons().size(), 1);
}
|
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
}
|
@Test
public void nestedTabularDataTest() throws Exception {
JmxCollector jc = new JmxCollector("---").register(prometheusRegistry);
assertEquals(
338,
getSampleValue(
"Hadoop_DataNodeInfo_DatanodeNetworkCounts",
new String[] {"service", "key", "key_"},
new String[] {"DataNode", "1.2.3.4", "networkErrors"}),
.001);
}
|
boolean hasActivity(Activity activity) {
if (activity != null) {
return hashSet.contains(activity.hashCode());
}
return false;
}
|
@Test
public void hasActivity() {
mActivityLifecycle.addActivity(mActivity);
assertTrue(mActivityLifecycle.hasActivity(mActivity));
}
|
@Override
public synchronized void cancel(final BackgroundAction action) {
if(action.isRunning()) {
log.debug(String.format("Skip removing action %s currently running", action));
}
else {
this.remove(action);
}
}
|
@Test
public void testCancel() {
BackgroundActionRegistry r = new BackgroundActionRegistry();
final AbstractBackgroundAction action = new AbstractBackgroundAction() {
@Override
public Object run() {
return null;
}
};
assertTrue(r.add(action));
action.cancel();
r.remove(action);
assertFalse(r.contains(action));
assertNull(r.getCurrent());
}
|
@Override
public boolean containsEntry(Object key, Object value) {
return get(containsEntryAsync(key, value));
}
|
@Test
public void testContainsEntry() {
RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("test1");
map.put(new SimpleKey("0"), new SimpleValue("1"));
assertThat(map.containsEntry(new SimpleKey("0"), new SimpleValue("1"))).isTrue();
assertThat(map.containsEntry(new SimpleKey("0"), new SimpleValue("2"))).isFalse();
}
|
public boolean isActivated() {
return !StringUtils.isBlank(configuration.getSmtpHost());
}
|
@Test
public void isActivated_returns_false_if_smpt_host_is_null() {
when(configuration.getSmtpHost()).thenReturn(null);
assertThat(underTest.isActivated()).isFalse();
}
|
@ConstantFunction(name = "datediff", argTypes = {DATETIME, DATETIME}, returnType = INT, isMonotonic = true)
public static ConstantOperator dateDiff(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt((int) Duration.between(
second.getDatetime().truncatedTo(ChronoUnit.DAYS),
first.getDatetime().truncatedTo(ChronoUnit.DAYS)).toDays());
}
|
@Test
public void dateDiff() {
assertEquals(-1602,
ScalarOperatorFunctions.dateDiff(O_DT_20101102_183010, O_DT_20150323_092355).getInt());
assertEquals(-1572, ScalarOperatorFunctions.dateDiff(O_DT_20101202_023010, O_DT_20150323_092355).getInt());
}
|
@VisibleForTesting
static SwitchGenerationCase checkSwitchGenerationCase(Type type, List<RowExpression> values)
{
if (values.size() > 32) {
// 32 is chosen because
// * SET_CONTAINS performs worst when smaller than but close to power of 2
// * Benchmark shows performance of SET_CONTAINS is better at 50, but similar at 25.
return SwitchGenerationCase.SET_CONTAINS;
}
if (!(type instanceof IntegerType || type instanceof BigintType || type instanceof DateType)) {
return SwitchGenerationCase.HASH_SWITCH;
}
for (RowExpression expression : values) {
// For non-constant expressions, they will be added to the default case in the generated switch code. They do not affect any of
// the cases other than the default one. Therefore, it's okay to skip them when choosing between DIRECT_SWITCH and HASH_SWITCH.
// Same argument applies for nulls.
if (!(expression instanceof ConstantExpression)) {
continue;
}
Object constant = ((ConstantExpression) expression).getValue();
if (constant == null) {
continue;
}
long longConstant = ((Number) constant).longValue();
if (longConstant < Integer.MIN_VALUE || longConstant > Integer.MAX_VALUE) {
return SwitchGenerationCase.HASH_SWITCH;
}
}
return SwitchGenerationCase.DIRECT_SWITCH;
}
|
@Test
public void testVarchar()
{
List<RowExpression> values = new ArrayList<>();
values.add(constant(Slices.utf8Slice("1"), VARCHAR));
values.add(constant(Slices.utf8Slice("2"), VARCHAR));
values.add(constant(Slices.utf8Slice("3"), VARCHAR));
assertEquals(checkSwitchGenerationCase(VARCHAR, values), HASH_SWITCH);
values.add(constant(null, VARCHAR));
assertEquals(checkSwitchGenerationCase(VARCHAR, values), HASH_SWITCH);
for (int i = 5; i <= 32; ++i) {
values.add(constant(Slices.utf8Slice(String.valueOf(i)), VARCHAR));
}
assertEquals(checkSwitchGenerationCase(VARCHAR, values), HASH_SWITCH);
values.add(constant(Slices.utf8Slice("33"), VARCHAR));
assertEquals(checkSwitchGenerationCase(VARCHAR, values), SET_CONTAINS);
}
|
@Override
public Optional<ConfigItem> resolve(final String propertyName, final boolean strict) {
if (propertyName.startsWith(KSQL_REQUEST_CONFIG_PROPERTY_PREFIX)) {
return resolveRequestConfig(propertyName);
} else if (propertyName.startsWith(KSQL_CONFIG_PROPERTY_PREFIX)
&& !propertyName.startsWith(KSQL_STREAMS_PREFIX)) {
return resolveKsqlConfig(propertyName);
}
return resolveStreamsConfig(propertyName, strict);
}
|
@Test
public void shouldNotFindUnknownStreamsPrefixedConsumerPropertyIfStrict() {
// Given:
final String configName = KsqlConfig.KSQL_STREAMS_PREFIX
+ StreamsConfig.CONSUMER_PREFIX
+ "custom.interceptor.config";
// Then:
assertThat(resolver.resolve(configName, true), is(Optional.empty()));
}
|
void start(Iterable<ShardCheckpoint> checkpoints) {
LOG.info(
"Pool {} - starting for stream {} consumer {}. Checkpoints = {}",
poolId,
read.getStreamName(),
consumerArn,
checkpoints);
for (ShardCheckpoint shardCheckpoint : checkpoints) {
checkState(
!state.containsKey(shardCheckpoint.getShardId()),
"Duplicate shard id %s",
shardCheckpoint.getShardId());
ShardState shardState =
new ShardState(
initShardSubscriber(shardCheckpoint), shardCheckpoint, watermarkPolicyFactory);
state.put(shardCheckpoint.getShardId(), shardState);
}
}
|
@Test
public void poolReSubscribesWhenManyRecoverableErrorsOccur() throws Exception {
kinesis = new EFOStubbedKinesisAsyncClient(1);
for (int i = 0; i < 250; i++) {
kinesis
.stubSubscribeToShard("shard-000", eventsWithRecords(i, 1))
.failWith(new ReadTimeoutException());
}
kinesis.stubSubscribeToShard("shard-000", eventsWithoutRecords(250, 3));
kinesis
.stubSubscribeToShard("shard-001", eventsWithRecords(333, 250))
.failWith(SdkClientException.create("this is recoverable", new ReadTimeoutException()));
kinesis.stubSubscribeToShard("shard-001", eventsWithoutRecords(583, 3));
KinesisReaderCheckpoint initialCheckpoint =
initialLatestCheckpoint(ImmutableList.of("shard-000", "shard-001"));
pool = new EFOShardSubscribersPool(readSpec, consumerArn, kinesis, 1);
pool.start(initialCheckpoint);
PoolAssertion.assertPool(pool)
.givesCheckPointedRecords(
ShardAssertion.shard("shard-000")
.gives(KinesisRecordView.generate("shard-000", 0, 250))
.withLastCheckpointSequenceNumber(252),
ShardAssertion.shard("shard-001")
.gives(KinesisRecordView.generate("shard-001", 333, 250))
.withLastCheckpointSequenceNumber(585));
assertThat(kinesis.subscribeRequestsSeen().size()).isEqualTo(255);
}
|
public static void validate(JobMetaDataParameterObject parameterObject) {
Path jarPath = parameterObject.getJarPath();
validateJarPathNotNull(jarPath);
validateFileSizeIsNotZero(jarPath);
validateFileExtension(jarPath);
validateJobParameters(parameterObject.getJobParameters());
}
|
@Test
public void testValidateJarOnMember() {
JobMetaDataParameterObject parameterObject = new JobMetaDataParameterObject();
assertThatThrownBy(() -> JarOnMemberValidator.validate(parameterObject))
.isInstanceOf(JetException.class);
}
|
public JWT parse(String token) {
Assert.notBlank(token, "Token String must be not blank!");
final List<String> tokens = splitToken(token);
this.tokens = tokens;
this.header.parse(tokens.get(0), this.charset);
this.payload.parse(tokens.get(1), this.charset);
return this;
}
|
@Test
public void parseTest() {
final String rightToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." +
"eyJzdWIiOiIxMjM0NTY3ODkwIiwiYWRtaW4iOnRydWUsIm5hbWUiOiJsb29seSJ9." +
"U2aQkC2THYV9L0fTN-yBBI7gmo5xhmvMhATtu8v0zEA";
final JWT jwt = JWT.of(rightToken);
assertTrue(jwt.setKey("1234567890".getBytes()).verify());
//header
assertEquals("JWT", jwt.getHeader(JWTHeader.TYPE));
assertEquals("HS256", jwt.getHeader(JWTHeader.ALGORITHM));
assertNull(jwt.getHeader(JWTHeader.CONTENT_TYPE));
//payload
assertEquals("1234567890", jwt.getPayload("sub"));
assertEquals("looly", jwt.getPayload("name"));
assertEquals(true, jwt.getPayload("admin"));
}
|
@Override
public Map<Consumer, List<Range>> getConsumerKeyHashRanges() {
Map<Consumer, List<Range>> result = new HashMap<>();
Map.Entry<Integer, Consumer> prev = null;
for (Map.Entry<Integer, Consumer> entry: rangeMap.entrySet()) {
if (prev == null) {
prev = entry;
} else {
if (prev.getValue().equals(entry.getValue())) {
result.computeIfAbsent(entry.getValue(), key -> new ArrayList<>())
.add(Range.of(prev.getKey(), entry.getKey()));
}
prev = null;
}
}
return result;
}
|
@Test
public void testGetConsumerKeyHashRanges() throws ExecutionException, InterruptedException {
HashRangeExclusiveStickyKeyConsumerSelector selector = new HashRangeExclusiveStickyKeyConsumerSelector(10);
List<String> consumerName = Arrays.asList("consumer1", "consumer2", "consumer3", "consumer4");
List<int[]> range = Arrays.asList(new int[] {0, 2}, new int[] {3, 7}, new int[] {9, 12}, new int[] {15, 20});
List<Consumer> consumers = new ArrayList<>();
for (int index = 0; index < consumerName.size(); index++) {
Consumer consumer = mock(Consumer.class);
KeySharedMeta keySharedMeta = new KeySharedMeta()
.setKeySharedMode(KeySharedMode.STICKY);
keySharedMeta.addHashRange()
.setStart(range.get(index)[0])
.setEnd(range.get(index)[1]);
when(consumer.getKeySharedMeta()).thenReturn(keySharedMeta);
when(consumer.consumerName()).thenReturn(consumerName.get(index));
Assert.assertEquals(consumer.getKeySharedMeta(), keySharedMeta);
selector.addConsumer(consumer).get();
consumers.add(consumer);
}
Map<Consumer, List<Range>> expectedResult = new HashMap<>();
expectedResult.put(consumers.get(0), Collections.singletonList(Range.of(0, 2)));
expectedResult.put(consumers.get(1), Collections.singletonList(Range.of(3, 7)));
expectedResult.put(consumers.get(2), Collections.singletonList(Range.of(9, 12)));
expectedResult.put(consumers.get(3), Collections.singletonList(Range.of(15, 20)));
for (Map.Entry<Consumer, List<Range>> entry : selector.getConsumerKeyHashRanges().entrySet()) {
Assert.assertEquals(entry.getValue(), expectedResult.get(entry.getKey()));
expectedResult.remove(entry.getKey());
}
Assert.assertEquals(expectedResult.size(), 0);
}
|
private ItemDTO createItem(long namespaceId, long itemId, String value) {
ItemDTO item = new ItemDTO();
item.setId(itemId);
item.setNamespaceId(namespaceId);
item.setValue(value);
item.setLineNum(1);
item.setKey(ConfigConsts.CONFIG_FILE_CONTENT_KEY);
return item;
}
|
@Test
public void testCreateItem(){
ItemChangeSets changeSets = resolver.resolve(NAMESPACE, CONFIG_TEXT, Collections.emptyList());
Assert.assertEquals(1, changeSets.getCreateItems().size());
Assert.assertEquals(0, changeSets.getUpdateItems().size());
Assert.assertEquals(0, changeSets.getDeleteItems().size());
ItemDTO createdItem = changeSets.getCreateItems().get(0);
Assert.assertEquals(CONFIG_TEXT, createdItem.getValue());
}
|
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (chatMessage.getType() != ChatMessageType.TRADE
&& chatMessage.getType() != ChatMessageType.GAMEMESSAGE
&& chatMessage.getType() != ChatMessageType.SPAM
&& chatMessage.getType() != ChatMessageType.FRIENDSCHATNOTIFICATION)
{
return;
}
String message = chatMessage.getMessage();
Matcher matcher = KILLCOUNT_PATTERN.matcher(message);
if (matcher.find())
{
final String boss = matcher.group("boss");
final int kc = Integer.parseInt(matcher.group("kc"));
final String pre = matcher.group("pre");
final String post = matcher.group("post");
if (Strings.isNullOrEmpty(pre) && Strings.isNullOrEmpty(post))
{
unsetKc(boss);
return;
}
String renamedBoss = KILLCOUNT_RENAMES
.getOrDefault(boss, boss)
// The config service doesn't support keys with colons in them
.replace(":", "");
if (boss != renamedBoss)
{
// Unset old TOB kc
unsetKc(boss);
unsetPb(boss);
unsetKc(boss.replace(":", "."));
unsetPb(boss.replace(":", "."));
// Unset old story mode
unsetKc("Theatre of Blood Story Mode");
unsetPb("Theatre of Blood Story Mode");
}
setKc(renamedBoss, kc);
// We either already have the pb, or need to remember the boss for the upcoming pb
if (lastPb > -1)
{
log.debug("Got out-of-order personal best for {}: {}", renamedBoss, lastPb);
if (renamedBoss.contains("Theatre of Blood"))
{
// TOB team size isn't sent in the kill message, but can be computed from varbits
int tobTeamSize = tobTeamSize();
lastTeamSize = tobTeamSize == 1 ? "Solo" : (tobTeamSize + " players");
}
else if (renamedBoss.contains("Tombs of Amascut"))
{
// TOA team size isn't sent in the kill message, but can be computed from varbits
int toaTeamSize = toaTeamSize();
lastTeamSize = toaTeamSize == 1 ? "Solo" : (toaTeamSize + " players");
}
final double pb = getPb(renamedBoss);
// If a raid with a team size, only update the pb if it is lower than the existing pb
// so that the pb is the overall lowest of any team size
if (lastTeamSize == null || pb == 0 || lastPb < pb)
{
log.debug("Setting overall pb (old: {})", pb);
setPb(renamedBoss, lastPb);
}
if (lastTeamSize != null)
{
log.debug("Setting team size pb: {}", lastTeamSize);
setPb(renamedBoss + " " + lastTeamSize, lastPb);
}
lastPb = -1;
lastTeamSize = null;
}
else
{
lastBossKill = renamedBoss;
lastBossTime = client.getTickCount();
}
return;
}
matcher = DUEL_ARENA_WINS_PATTERN.matcher(message);
if (matcher.find())
{
final int oldWins = getKc("Duel Arena Wins");
final int wins = matcher.group(2).equals("one") ? 1 :
Integer.parseInt(matcher.group(2).replace(",", ""));
final String result = matcher.group(1);
int winningStreak = getKc("Duel Arena Win Streak");
int losingStreak = getKc("Duel Arena Lose Streak");
if (result.equals("won") && wins > oldWins)
{
losingStreak = 0;
winningStreak += 1;
}
else if (result.equals("were defeated"))
{
losingStreak += 1;
winningStreak = 0;
}
else
{
log.warn("unrecognized duel streak chat message: {}", message);
}
setKc("Duel Arena Wins", wins);
setKc("Duel Arena Win Streak", winningStreak);
setKc("Duel Arena Lose Streak", losingStreak);
}
matcher = DUEL_ARENA_LOSSES_PATTERN.matcher(message);
if (matcher.find())
{
int losses = matcher.group(1).equals("one") ? 1 :
Integer.parseInt(matcher.group(1).replace(",", ""));
setKc("Duel Arena Losses", losses);
}
matcher = KILL_DURATION_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = NEW_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = RAIDS_PB_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = RAIDS_DURATION_PATTERN.matcher(message);
if (matcher.find())
{
matchPb(matcher);
}
matcher = HS_PB_PATTERN.matcher(message);
if (matcher.find())
{
int floor = Integer.parseInt(matcher.group("floor"));
String floortime = matcher.group("floortime");
String floorpb = matcher.group("floorpb");
String otime = matcher.group("otime");
String opb = matcher.group("opb");
String pb = MoreObjects.firstNonNull(floorpb, floortime);
setPb("Hallowed Sepulchre Floor " + floor, timeStringToSeconds(pb));
if (otime != null)
{
pb = MoreObjects.firstNonNull(opb, otime);
setPb("Hallowed Sepulchre", timeStringToSeconds(pb));
}
}
matcher = HS_KC_FLOOR_PATTERN.matcher(message);
if (matcher.find())
{
int floor = Integer.parseInt(matcher.group(1));
int kc = Integer.parseInt(matcher.group(2).replaceAll(",", ""));
setKc("Hallowed Sepulchre Floor " + floor, kc);
}
matcher = HS_KC_GHC_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1).replaceAll(",", ""));
setKc("Hallowed Sepulchre", kc);
}
matcher = HUNTER_RUMOUR_KC_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1).replaceAll(",", ""));
setKc("Hunter Rumours", kc);
}
if (lastBossKill != null && lastBossTime != client.getTickCount())
{
lastBossKill = null;
lastBossTime = -1;
}
matcher = COLLECTION_LOG_ITEM_PATTERN.matcher(message);
if (matcher.find())
{
String item = matcher.group(1);
int petId = findPet(item);
if (petId != -1)
{
final List<Integer> petList = new ArrayList<>(getPetList());
if (!petList.contains(petId))
{
log.debug("New pet added: {}/{}", item, petId);
petList.add(petId);
setPetList(petList);
}
}
}
matcher = GUARDIANS_OF_THE_RIFT_PATTERN.matcher(message);
if (matcher.find())
{
int kc = Integer.parseInt(matcher.group(1));
setKc("Guardians of the Rift", kc);
}
}
|
@Test
public void testZukKill()
{
ChatMessage chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Your TzKal-Zuk kill count is: <col=ff0000>3</col>.", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Duration: <col=ff0000>172:18</col>. Personal best: 134:52", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration("personalbest", "tzkal-zuk", 134 * 60 + 52.0);
verify(configManager).setRSProfileConfiguration("killcount", "tzkal-zuk", 3);
// Precise times
chatMessage = new ChatMessage(null, GAMEMESSAGE, "", "Duration: <col=ff0000>172:18.40</col>. Personal best: 134:52.20", null, 0);
chatCommandsPlugin.onChatMessage(chatMessage);
verify(configManager).setRSProfileConfiguration("personalbest", "tzkal-zuk", 134 * 60 + 52.2);
}
|
public static Object cast(Class<?> clazz, Object value) {
try {
return clazz.cast(value);
} catch (ClassCastException e) {
return null;
}
}
|
@Test
public void castTest() {
TestClass testClass = new TestSubClass();
Object cast = ReflectUtil.cast(TestSubClass.class, testClass);
Assert.assertTrue(cast instanceof TestSubClass);
}
|
public static CuratorFramework createCurator(ZooKeeperCuratorConfiguration configuration) {
CuratorFramework curator = configuration.getCuratorFramework();
if (curator == null) {
// Validate parameters
ObjectHelper.notNull(configuration.getNodes(), "ZooKeeper Nodes");
RetryPolicy retryPolicy = configuration.getRetryPolicy();
if (retryPolicy == null) {
retryPolicy = new ExponentialBackoffRetry(
(int) configuration.getReconnectBaseSleepTimeUnit().toMillis(configuration.getReconnectBaseSleepTime()),
configuration.getReconnectMaxRetries(),
(int) configuration.getReconnectMaxSleepTimeUnit().toMillis(configuration.getReconnectMaxSleepTime()));
}
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(String.join(",", configuration.getNodes()))
.sessionTimeoutMs((int) configuration.getSessionTimeoutUnit().toMillis(configuration.getSessionTimeout()))
.connectionTimeoutMs(
(int) configuration.getConnectionTimeoutUnit().toMillis(configuration.getConnectionTimeout()))
.maxCloseWaitMs((int) configuration.getMaxCloseWaitUnit().toMillis(configuration.getMaxCloseWait()))
.retryPolicy(retryPolicy);
Optional.ofNullable(configuration.getNamespace()).ifPresent(builder::namespace);
Optional.ofNullable(configuration.getAuthInfoList()).ifPresent(builder::authorization);
curator = builder.build();
}
return curator;
}
|
@Test
public void testCreateCuratorRetryPolicy() {
ZooKeeperCuratorConfiguration configuration = new ZooKeeperCuratorConfiguration();
configuration.setNodes("nodes1,node2,node3");
configuration.setReconnectBaseSleepTime(10);
configuration.setReconnectMaxRetries(3);
configuration.setReconnectMaxSleepTime(50);
configuration.setRetryPolicy(null);
CuratorFramework curatorFramework = ZooKeeperCuratorHelper.createCurator(configuration);
assertNotNull(curatorFramework);
ExponentialBackoffRetry retryPolicy = (ExponentialBackoffRetry) curatorFramework.getZookeeperClient().getRetryPolicy();
assertEquals(configuration.getReconnectBaseSleepTime(), retryPolicy.getBaseSleepTimeMs(),
"retryPolicy.reconnectBaseSleepTime");
assertEquals(configuration.getReconnectMaxRetries(), retryPolicy.getN(), "retryPolicy.reconnectMaxRetries");
// retryPolicy.maxSleepMs not visible here
}
|
@Override
public Optional<ProtobufSystemInfo.SystemInfo> retrieveSystemInfo() {
return call(SystemInfoActionClient.INSTANCE);
}
|
@Test
public void retrieveSystemInfo_get_information_if_process_is_up() {
Buffer response = new Buffer();
response.read(ProtobufSystemInfo.Section.newBuilder().build().toByteArray());
server.enqueue(new MockResponse().setBody(response));
// initialize registration of process
setUpWithHttpUrl(ProcessId.COMPUTE_ENGINE);
Optional<ProtobufSystemInfo.SystemInfo> info = underTest.retrieveSystemInfo();
assertThat(info.get().getSectionsCount()).isZero();
}
|
public void cleanSelectorDataSelf(final List<SelectorData> selectorDataList) {
selectorDataList.forEach(this::removeSelectData);
}
|
@Test
public void testCleanSelectorDataSelf() throws NoSuchFieldException, IllegalAccessException {
SelectorData firstCachedSelectorData = SelectorData.builder().id("1").pluginName(mockPluginName1).build();
SelectorData secondCachedSelectorData = SelectorData.builder().id("2").pluginName(mockPluginName2).build();
ConcurrentHashMap<String, List<SelectorData>> selectorMap = getFieldByName(selectorMapStr);
selectorMap.put(mockPluginName1, Lists.newArrayList(firstCachedSelectorData));
selectorMap.put(mockPluginName2, Lists.newArrayList(secondCachedSelectorData));
BaseDataCache.getInstance().cleanSelectorDataSelf(Lists.newArrayList(firstCachedSelectorData));
assertEquals(Lists.newArrayList(), selectorMap.get(mockPluginName1));
assertEquals(Lists.newArrayList(secondCachedSelectorData), selectorMap.get(mockPluginName2));
}
|
public static Map<String, String> resolveAttachments(Object invocation, boolean isApache) {
if (invocation == null) {
return Collections.emptyMap();
}
final Map<String, String> attachments = new HashMap<>();
if (isApache) {
attachments.putAll(getAttachmentsFromContext(APACHE_RPC_CONTEXT));
} else {
attachments.putAll(getAttachmentsFromContext(ALIBABA_RPC_CONTEXT));
}
final Optional<Object> fieldValue = ReflectUtils.getFieldValue(invocation, ATTACHMENTS_FIELD);
if (fieldValue.isPresent() && fieldValue.get() instanceof Map) {
attachments.putAll((Map<String, String>) fieldValue.get());
}
return Collections.unmodifiableMap(attachments);
}
|
@Test
public void testNull() {
final Map<String, String> map = DubboAttachmentsHelper.resolveAttachments(null, false);
Assert.assertEquals(map, Collections.emptyMap());
final Map<String, String> map2 = DubboAttachmentsHelper.resolveAttachments(null, true);
Assert.assertEquals(map2, Collections.emptyMap());
}
|
public Node parse() throws ScanException {
return E();
}
|
@Test
public void lbcore193() throws Exception {
try {
Parser<Object> p = new Parser<>("hello%(abc");
p.setContext(context);
p.parse();
Assertions.fail("where the is exception?");
} catch (ScanException ise) {
Assertions.assertEquals("Expecting RIGHT_PARENTHESIS token but got null", ise.getMessage());
}
StatusChecker sc = new StatusChecker(context);
sc.assertContainsMatch("Expecting RIGHT_PARENTHESIS");
sc.assertContainsMatch("See also " + Parser.MISSING_RIGHT_PARENTHESIS);
}
|
@Override
public String asLongText() {
String longValue = this.longValue;
if (longValue == null) {
this.longValue = longValue = newLongValue();
}
return longValue;
}
|
@Test
public void testDeserialization() throws Exception {
// DefaultChannelId with 8 byte machineId
final DefaultChannelId c8 = new DefaultChannelId(
new byte[] {
(byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67,
(byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef
},
0x000052af,
0x00000000,
0x06504f638eb4c386L,
0xd964df5e);
// DefaultChannelId with 6 byte machineId
final DefaultChannelId c6 =
new DefaultChannelId(
new byte[] {
(byte) 0x01, (byte) 0x23, (byte) 0x45, (byte) 0x67,
(byte) 0x89, (byte) 0xab,
},
0xce005283,
0x00000001,
0x069e6dce9eb4516fL,
0x721757b7);
assertThat(c8.asLongText(), is("0123456789abcdef-000052af-00000000-06504f638eb4c386-d964df5e"));
assertThat(c6.asLongText(), is("0123456789ab-ce005283-00000001-069e6dce9eb4516f-721757b7"));
}
|
@Override
public PageResult<OAuth2AccessTokenDO> getAccessTokenPage(OAuth2AccessTokenPageReqVO reqVO) {
return oauth2AccessTokenMapper.selectPage(reqVO);
}
|
@Test
public void testGetAccessTokenPage() {
// mock 数据
OAuth2AccessTokenDO dbAccessToken = randomPojo(OAuth2AccessTokenDO.class, o -> { // 等会查询到
o.setUserId(10L);
o.setUserType(1);
o.setClientId("test_client");
o.setExpiresTime(LocalDateTime.now().plusDays(1));
});
oauth2AccessTokenMapper.insert(dbAccessToken);
// 测试 userId 不匹配
oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setUserId(20L)));
// 测试 userType 不匹配
oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setUserType(2)));
// 测试 userType 不匹配
oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setClientId("it_client")));
// 测试 expireTime 不匹配
oauth2AccessTokenMapper.insert(cloneIgnoreId(dbAccessToken, o -> o.setExpiresTime(LocalDateTimeUtil.now())));
// 准备参数
OAuth2AccessTokenPageReqVO reqVO = new OAuth2AccessTokenPageReqVO();
reqVO.setUserId(10L);
reqVO.setUserType(1);
reqVO.setClientId("test");
// 调用
PageResult<OAuth2AccessTokenDO> pageResult = oauth2TokenService.getAccessTokenPage(reqVO);
// 断言
assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size());
assertPojoEquals(dbAccessToken, pageResult.getList().get(0));
}
|
public synchronized TopologyDescription describe() {
return internalTopologyBuilder.describe();
}
|
@Test
public void sessionWindowZeroArgCountWithTopologyConfigShouldPreserveTopologyStructure() {
// override the default store into in-memory
final StreamsBuilder builder = new StreamsBuilder(overrideDefaultStore(StreamsConfig.IN_MEMORY));
builder.stream("input-topic")
.groupByKey()
.windowedBy(SessionWindows.with(ofMillis(1)))
.count();
final Topology topology = builder.build();
final TopologyDescription describe = topology.describe();
assertEquals(
"Topology: my-topology:\n" +
" Sub-topology: 0\n" +
" Source: KSTREAM-SOURCE-0000000000 (topics: [input-topic])\n" +
" --> KSTREAM-AGGREGATE-0000000002\n" +
" Processor: KSTREAM-AGGREGATE-0000000002 (stores: [KSTREAM-AGGREGATE-STATE-STORE-0000000001])\n" +
" --> none\n" +
" <-- KSTREAM-SOURCE-0000000000\n\n",
describe.toString()
);
topology.internalTopologyBuilder.setStreamsConfig(streamsConfig);
assertThat(topology.internalTopologyBuilder.setApplicationId("test").buildTopology().hasPersistentLocalStore(), is(false));
}
|
public static Read read() {
return new Read(null, "", new Scan());
}
|
@Test
public void testReadingKeyRangeMiddle() throws Exception {
final String table = tmpTable.getName();
final int numRows = 1001;
final byte[] startRow = "2".getBytes(StandardCharsets.UTF_8);
final byte[] stopRow = "9".getBytes(StandardCharsets.UTF_8);
createAndWriteData(table, numRows);
// Test restricted range: [startKey, endKey).
// This one tests the second signature of .withKeyRange
runReadTestLength(
HBaseIO.read().withConfiguration(conf).withTableId(table).withKeyRange(startRow, stopRow),
false,
441);
}
|
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 testIPListSpaces() {
//create MachineList with a ip string which has duplicate ip and spaces
MachineList ml = new MachineList(IP_LIST_SPACES, 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 void close() {
synchronized (this) {
if (!closed) {
leaderCopyRLMTasks.values().forEach(RLMTaskWithFuture::cancel);
leaderExpirationRLMTasks.values().forEach(RLMTaskWithFuture::cancel);
followerRLMTasks.values().forEach(RLMTaskWithFuture::cancel);
Utils.closeQuietly(remoteLogStorageManager, "RemoteLogStorageManager");
Utils.closeQuietly(remoteLogMetadataManager, "RemoteLogMetadataManager");
Utils.closeQuietly(indexCache, "RemoteIndexCache");
rlmCopyThreadPool.close();
rlmExpirationThreadPool.close();
followerThreadPool.close();
try {
shutdownAndAwaitTermination(remoteStorageReaderThreadPool, "RemoteStorageReaderThreadPool", 10, TimeUnit.SECONDS);
} finally {
removeMetrics();
}
leaderCopyRLMTasks.clear();
leaderExpirationRLMTasks.clear();
followerRLMTasks.clear();
closed = true;
}
}
}
|
@Test
void testIdempotentClose() throws IOException {
remoteLogManager.close();
remoteLogManager.close();
InOrder inorder = inOrder(remoteStorageManager, remoteLogMetadataManager);
inorder.verify(remoteStorageManager, times(1)).close();
inorder.verify(remoteLogMetadataManager, times(1)).close();
}
|
public SSLContext createContext(ContextAware context) throws NoSuchProviderException,
NoSuchAlgorithmException, KeyManagementException,
UnrecoverableKeyException, KeyStoreException, CertificateException {
SSLContext sslContext = getProvider() != null ?
SSLContext.getInstance(getProtocol(), getProvider())
: SSLContext.getInstance(getProtocol());
context.addInfo("SSL protocol '" + sslContext.getProtocol()
+ "' provider '" + sslContext.getProvider() + "'");
KeyManager[] keyManagers = createKeyManagers(context);
TrustManager[] trustManagers = createTrustManagers(context);
SecureRandom secureRandom = createSecureRandom(context);
sslContext.init(keyManagers, trustManagers, secureRandom);
return sslContext;
}
|
@Test
public void testCreateContext() throws Exception {
factoryBean.setKeyManagerFactory(keyManagerFactory);
factoryBean.setKeyStore(keyStore);
factoryBean.setTrustManagerFactory(trustManagerFactory);
factoryBean.setTrustStore(trustStore);
factoryBean.setSecureRandom(secureRandom);
assertNotNull(factoryBean.createContext(context));
assertTrue(keyManagerFactory.isFactoryCreated());
assertTrue(trustManagerFactory.isFactoryCreated());
assertTrue(keyStore.isKeyStoreCreated());
assertTrue(trustStore.isKeyStoreCreated());
assertTrue(secureRandom.isSecureRandomCreated());
// it's important that each configured component output an appropriate
// informational message to the context; i.e. this logging is not just
// for programmers, it's there for systems administrators to use in
// verifying that SSL is configured properly
assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN));
assertTrue(context.hasInfoMatching(KEY_MANAGER_FACTORY_MESSAGE_PATTERN));
assertTrue(context.hasInfoMatching(TRUST_MANAGER_FACTORY_MESSAGE_PATTERN));
assertTrue(context.hasInfoMatching(KEY_STORE_MESSAGE_PATTERN));
assertTrue(context.hasInfoMatching(TRUST_STORE_MESSAGE_PATTERN));
assertTrue(context.hasInfoMatching(SECURE_RANDOM_MESSAGE_PATTERN));
}
|
@Override
public HttpOverXmppResp parse(XmlPullParser parser, int initialDepth, IqData iqData, XmlEnvironment xmlEnvironment) throws IOException, XmlPullParserException, SmackParsingException {
String version = parser.getAttributeValue("", ATTRIBUTE_VERSION);
String statusMessage = parser.getAttributeValue("", ATTRIBUTE_STATUS_MESSAGE);
String statusCodeString = parser.getAttributeValue("", ATTRIBUTE_STATUS_CODE);
int statusCode = Integer.parseInt(statusCodeString);
HeadersExtension headers = parseHeaders(parser);
AbstractHttpOverXmpp.Data data = parseData(parser);
return HttpOverXmppResp.builder().setHeaders(headers).setData(data).setStatusCode(statusCode).setStatusMessage(statusMessage).setVersion(version).build();
}
|
@Test
public void areAllRespAttributesCorrectlyParsed() throws Exception {
String string = "<resp xmlns='urn:xmpp:http' version='1.1' statusCode='200' statusMessage='OK'/>";
HttpOverXmppRespProvider provider = new HttpOverXmppRespProvider();
XmlPullParser parser = PacketParserUtils.getParserFor(string);
IQ iq = provider.parse(parser, null);
assertTrue(iq instanceof HttpOverXmppResp);
HttpOverXmppResp resp = (HttpOverXmppResp) iq;
assertEquals(resp.getVersion(), "1.1");
assertEquals(resp.getStatusCode(), 200);
assertEquals(resp.getStatusMessage(), "OK");
}
|
@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
return super.convert(exchange)
// validate the password
.<Authentication>flatMap(token -> {
var credentials = (String) token.getCredentials();
byte[] credentialsBytes;
try {
credentialsBytes = Base64.getDecoder().decode(credentials);
} catch (IllegalArgumentException e) {
// the credentials are not in valid Base64 scheme
return Mono.error(new BadCredentialsException("Invalid Base64 scheme."));
}
return cryptoService.decrypt(credentialsBytes)
.onErrorMap(InvalidEncryptedMessageException.class,
error -> new BadCredentialsException("Invalid credential.", error))
.map(decryptedCredentials -> new UsernamePasswordAuthenticationToken(
token.getPrincipal(),
new String(decryptedCredentials, UTF_8)));
})
.transformDeferred(createIpBasedRateLimiter(exchange))
.onErrorMap(RequestNotPermitted.class, RateLimitExceededException::new);
}
|
@Test
void applyPasswordWithoutBase64FormatThenBadCredentialsException() {
var username = "username";
var password = "+invalid-base64-format-password";
formData.add("username", username);
formData.add("password", password);
StepVerifier.create(converter.convert(exchange))
.verifyError(BadCredentialsException.class);
}
|
@Override
public int division(int n1, int n2) throws Exception {
int n5 = n1 / n2;
return n5;
}
|
@Test
public void testDivision() throws Exception {
Controlador controlador = new Controlador();
int result = controlador.division(6, 3);
assertEquals(2, result);
}
|
public static String removeLeadingAndEndingQuotes(final String s) {
if (ObjectHelper.isEmpty(s)) {
return s;
}
String copy = s.trim();
if (copy.length() < 2) {
return s;
}
if (copy.startsWith("'") && copy.endsWith("'")) {
return copy.substring(1, copy.length() - 1);
}
if (copy.startsWith("\"") && copy.endsWith("\"")) {
return copy.substring(1, copy.length() - 1);
}
// no quotes, so return as-is
return s;
}
|
@Test
public void testRemoveLeadingAndEndingQuotes() {
assertEquals("abc", removeLeadingAndEndingQuotes("'abc'"));
assertEquals("abc", removeLeadingAndEndingQuotes("\"abc\""));
assertEquals("a'b'c", removeLeadingAndEndingQuotes("a'b'c"));
assertEquals("'b'c", removeLeadingAndEndingQuotes("'b'c"));
assertEquals("", removeLeadingAndEndingQuotes("''"));
assertEquals("'", removeLeadingAndEndingQuotes("'"));
}
|
public void fillMaxSpeed(Graph graph, EncodingManager em) {
// In DefaultMaxSpeedParser and in OSMMaxSpeedParser we don't have the rural/urban info,
// but now we have and can fill the country-dependent max_speed value where missing.
EnumEncodedValue<UrbanDensity> udEnc = em.getEnumEncodedValue(UrbanDensity.KEY, UrbanDensity.class);
fillMaxSpeed(graph, em, edge -> edge.get(udEnc) != UrbanDensity.RURAL);
}
|
@Test
public void testLanes() {
ReaderWay way = new ReaderWay(0L);
way.setTag("country", Country.CHL);
way.setTag("highway", "primary");
EdgeIteratorState edge = createEdge(way).set(urbanDensity, RURAL);
calc.fillMaxSpeed(graph, em);
assertEquals(100, edge.get(maxSpeedEnc), 1);
way = new ReaderWay(0L);
way.setTag("country", Country.CHL);
way.setTag("highway", "primary");
way.setTag("lanes", "4"); // 2 in each direction!
edge = createEdge(way).set(urbanDensity, RURAL);
calc.fillMaxSpeed(graph, em);
assertEquals(120, edge.get(maxSpeedEnc), 1);
}
|
boolean eosEnabled() {
return StreamsConfigUtils.eosEnabled(processingMode);
}
|
@Test
public void shouldEnableEosIfEosAlphaEnabled() {
assertThat(eosAlphaStreamsProducer.eosEnabled(), is(true));
}
|
@PublicEvolving
public static CongestionControlRateLimitingStrategyBuilder builder() {
return new CongestionControlRateLimitingStrategyBuilder();
}
|
@Test
void testInvalidMaxInFlightRequests() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(
() ->
CongestionControlRateLimitingStrategy.builder()
.setMaxInFlightRequests(0)
.setInitialMaxInFlightMessages(10)
.setScalingStrategy(AIMDScalingStrategy.builder(10).build())
.build())
.withMessageContaining("maxInFlightRequests must be a positive integer.");
}
|
@Override
public FSDataOutputStream create(Path path, boolean overwrite, int bufferSize, short replication,
long blockSize, Progressable progress) throws IOException {
String confUmask = mAlluxioConf.getString(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_UMASK);
Mode mode = ModeUtils.applyFileUMask(Mode.defaults(), confUmask);
return this.create(path, new FsPermission(mode.toShort()), overwrite, bufferSize, replication,
blockSize, progress);
}
|
@Test
public void hadoopShouldLoadFsWithMultiMasterUri() throws Exception {
URI uri = URI.create("alluxio://host1:19998,host2:19998,host3:19998/path");
org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.get(uri, getConf());
assertTrue(fs instanceof FileSystem);
uri = URI.create("alluxio://host1:19998;host2:19998;host3:19998/path");
fs = org.apache.hadoop.fs.FileSystem.get(uri, getConf());
assertTrue(fs instanceof FileSystem);
}
|
@Override
public List<StateInstance> queryStateInstanceListByMachineInstanceId(String stateMachineInstanceId) {
List<StateInstance> stateInstanceList = selectList(
stateLogStoreSqls.getQueryStateInstancesByMachineInstanceIdSql(dbType), RESULT_SET_TO_STATE_INSTANCE,
stateMachineInstanceId);
if (CollectionUtils.isEmpty(stateInstanceList)) {
return stateInstanceList;
}
StateInstance lastStateInstance = CollectionUtils.getLast(stateInstanceList);
if (lastStateInstance.getGmtEnd() == null) {
lastStateInstance.setStatus(ExecutionStatus.RU);
}
Map<String, StateInstance> originStateMap = new HashMap<>();
Map<String/* originStateId */, StateInstance/* compensatedState */> compensatedStateMap = new HashMap<>();
Map<String/* originStateId */, StateInstance/* retriedState */> retriedStateMap = new HashMap<>();
for (StateInstance tempStateInstance : stateInstanceList) {
deserializeParamsAndException(tempStateInstance);
if (StringUtils.hasText(tempStateInstance.getStateIdCompensatedFor())) {
putLastStateToMap(compensatedStateMap, tempStateInstance, tempStateInstance.getStateIdCompensatedFor());
} else {
if (StringUtils.hasText(tempStateInstance.getStateIdRetriedFor())) {
putLastStateToMap(retriedStateMap, tempStateInstance, tempStateInstance.getStateIdRetriedFor());
}
originStateMap.put(tempStateInstance.getId(), tempStateInstance);
}
}
if (compensatedStateMap.size() != 0) {
for (StateInstance origState : originStateMap.values()) {
origState.setCompensationState(compensatedStateMap.get(origState.getId()));
}
}
if (retriedStateMap.size() != 0) {
for (StateInstance origState : originStateMap.values()) {
if (retriedStateMap.containsKey(origState.getId())) {
origState.setIgnoreStatus(true);
}
}
}
return stateInstanceList;
}
|
@Test
public void testQueryStateInstanceListByMachineInstanceId() {
Assertions.assertDoesNotThrow(() -> dbAndReportTcStateLogStore.queryStateInstanceListByMachineInstanceId("test"));
}
|
public Mono<Void> resetToLatest(
KafkaCluster cluster, String group, String topic, Collection<Integer> partitions) {
return checkGroupCondition(cluster, group)
.flatMap(ac ->
offsets(ac, topic, partitions, OffsetSpec.latest())
.flatMap(offsets -> resetOffsets(ac, group, offsets)));
}
|
@Test
void resetToLatest() {
sendMsgsToPartition(Map.of(0, 10, 1, 10, 2, 10, 3, 10, 4, 10));
commit(Map.of(0, 5L, 1, 5L, 2, 5L));
offsetsResetService.resetToLatest(cluster, groupId, topic, List.of(0, 1)).block();
assertOffsets(Map.of(0, 10L, 1, 10L, 2, 5L));
commit(Map.of(0, 5L, 1, 5L, 2, 5L));
offsetsResetService.resetToLatest(cluster, groupId, topic, null).block();
assertOffsets(Map.of(0, 10L, 1, 10L, 2, 10L, 3, 10L, 4, 10L));
}
|
@Override
public final void getSize(@NonNull SizeReadyCallback cb) {
sizeDeterminer.getSize(cb);
}
|
@Test
public void getSize_withWrapContentWidthAndValidHeight_usesDisplayDimenAndValidHeight() {
int height = 100;
LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, height);
view.setLayoutParams(params);
setDisplayDimens(100, 200);
activity.visible();
view.setRight(0);
target.getSize(cb);
verify(cb).onSizeReady(200, height);
}
|
public String[] getS3ObjectsNames( String bucketName ) throws Exception {
Bucket bucket = getBucket( bucketName );
if ( bucket == null ) {
throw new Exception( Messages.getString( "S3DefaultService.Exception.UnableToFindBucket.Message", bucketName ) );
}
return getS3Objects( bucket ).getObjectSummaries().stream().map( b -> b.getKey() ).toArray( String[]::new );
}
|
@Test public void testGetObjectsNamesInBucketWithObjects() throws Exception {
List<String> actual = Arrays.asList( provider.getS3ObjectsNames( BUCKET2_NAME ) );
assertEquals( bucket2Objects.getObjectSummaries().size(), actual.size() );
List<S3ObjectSummary> expectedList = bucket2Objects.getObjectSummaries();
expectedList.stream().forEach( i -> assertTrue( actual.contains( i.getKey() ) ) );
}
|
public static SchemaPath schemaPathFromPath(String path) {
return new SchemaPath(path);
}
|
@Test
public void schemaPathFromPathWellFormed() {
SchemaPath path = PubsubClient.schemaPathFromPath("projects/projectId/schemas/schemaId");
assertEquals("projects/projectId/schemas/schemaId", path.getPath());
assertEquals("schemaId", path.getId());
}
|
public static boolean hasIntfAleadyInDevice(DeviceId deviceId,
String intfName,
DeviceService deviceService) {
checkNotNull(deviceId);
checkNotNull(intfName);
return deviceService.getPorts(deviceId).stream().anyMatch(port ->
Objects.equals(port.annotations().value(PORT_NAME), intfName));
}
|
@Test
public void testHasIntfAleadyInDevice() {
DeviceService deviceService = new TestDeviceService();
assertTrue(OpenstackNetworkingUtil.hasIntfAleadyInDevice(DeviceId.deviceId("deviceId"),
"port1", deviceService));
assertTrue(OpenstackNetworkingUtil.hasIntfAleadyInDevice(DeviceId.deviceId("deviceId"),
"port2", deviceService));
assertTrue(OpenstackNetworkingUtil.hasIntfAleadyInDevice(DeviceId.deviceId("deviceId"),
"port3", deviceService));
assertFalse(OpenstackNetworkingUtil.hasIntfAleadyInDevice(DeviceId.deviceId("deviceId"),
"port4", deviceService));
}
|
<T extends PipelineOptions> T as(Class<T> iface) {
checkNotNull(iface);
checkArgument(iface.isInterface(), "Not an interface: %s", iface);
T existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
synchronized (this) {
// double check
existingOption = computedProperties.interfaceToProxyCache.getInstance(iface);
if (existingOption == null) {
Registration<T> registration =
PipelineOptionsFactory.CACHE
.get()
.validateWellFormed(iface, computedProperties.knownInterfaces);
List<PropertyDescriptor> propertyDescriptors = registration.getPropertyDescriptors();
Class<T> proxyClass = registration.getProxyClass();
existingOption =
InstanceBuilder.ofType(proxyClass)
.fromClass(proxyClass)
.withArg(InvocationHandler.class, this)
.build();
computedProperties =
computedProperties.updated(iface, existingOption, propertyDescriptors);
}
}
}
return existingOption;
}
|
@Test
public void testSiblingMethodConflict() throws Exception {
ProxyInvocationHandler handler = new ProxyInvocationHandler(Maps.newHashMap());
SiblingMethodConflict siblingMethodConflict = handler.as(SiblingMethodConflict.class);
siblingMethodConflict.setString("siblingValue");
assertEquals("siblingValue", siblingMethodConflict.getString());
assertEquals("siblingValue", siblingMethodConflict.as(Simple.class).getString());
assertEquals("siblingValue", siblingMethodConflict.as(SimpleSibling.class).getString());
}
|
public void updateLags() {
for (final Task t: tasks.activeTasks()) {
t.updateLags();
}
}
|
@Test
public void shouldUpdateLagForAllActiveTasks() {
final StreamTask activeTask1 = statefulTask(taskId00, taskId00ChangelogPartitions)
.inState(State.RUNNING)
.withInputPartitions(taskId00Partitions).build();
final StreamTask activeTask2 = statefulTask(taskId01, taskId01ChangelogPartitions)
.inState(State.RUNNING)
.withInputPartitions(taskId01Partitions).build();
final TasksRegistry tasks = mock(TasksRegistry.class);
final TaskManager taskManager = setUpTaskManager(ProcessingMode.AT_LEAST_ONCE, tasks, true);
when(tasks.activeTasks()).thenReturn(mkSet(activeTask1, activeTask2));
taskManager.updateLags();
verify(activeTask1).updateLags();
verify(activeTask2).updateLags();
}
|
public void onGlobalPropertyChange(String key, @Nullable String value) {
GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create(key, value);
for (GlobalPropertyChangeHandler changeHandler : changeHandlers) {
changeHandler.onChange(change);
}
}
|
@Test
public void onGlobalPropertyChange() {
GlobalPropertyChangeHandler handler = mock(GlobalPropertyChangeHandler.class);
SettingsChangeNotifier notifier = new SettingsChangeNotifier(new GlobalPropertyChangeHandler[] {handler});
notifier.onGlobalPropertyChange("foo", "bar");
verify(handler).onChange(argThat(change -> change.getKey().equals("foo") && change.getNewValue().equals("bar")));
}
|
public boolean verifySignedPip(ASN1Sequence signedPip) throws BsnkException {
ASN1Sequence signedPipContent = (ASN1Sequence) signedPip.getObjectAt(1);
ASN1Sequence pipSignatureSequence = (ASN1Sequence) signedPip.getObjectAt(2);
ASN1Sequence pipSignature = (ASN1Sequence) pipSignatureSequence.getObjectAt(1);
byte[] pipBytes;
try {
pipBytes = signedPipContent.getEncoded();
} catch (IOException ex) {
throw new BsnkException("SignedPipIOFault", "Failed to get byte[] from pip or pip signature.", ex);
}
BigInteger pipKsv = ((ASN1Integer) signedPipContent.getObjectAt(2)).getValue();
if (!pipKsv.equals(bsnkUKsv)) {
throw new BsnkException("SignedpipKsvMismatch",
String.format("Signedpip ksv mismatch. U: '%s'. Pip: '%s'", bsnkUKsv, pipKsv), null);
}
String oid = ((ASN1ObjectIdentifier) pipSignatureSequence.getObjectAt(0)).getId();
BigInteger r = ((ASN1Integer) pipSignature.getObjectAt(0)).getValue();
BigInteger s = ((ASN1Integer) pipSignature.getObjectAt(1)).getValue();
SignatureEcdsa signature = (SignatureEcdsa) SignatureEcdsa.from(oid, r, s);
try {
signature.verify(bsnkUPubkey, pipBytes);
return true;
} catch (CryptoException ex) {
logger.error(String.format("Exception during pip verification: '%s", ex.getMessage()));
return false;
}
}
|
@Test
public void verifySignedPipTest() throws IOException, BsnkException {
assertTrue(bsnkUtil.verifySignedPip(signedPip));
}
|
public static KafkaRebalanceState rebalanceState(KafkaRebalanceStatus kafkaRebalanceStatus) {
if (kafkaRebalanceStatus != null) {
Condition rebalanceStateCondition = rebalanceStateCondition(kafkaRebalanceStatus);
String statusString = rebalanceStateCondition != null ? rebalanceStateCondition.getType() : null;
if (statusString != null) {
return KafkaRebalanceState.valueOf(statusString);
}
}
return null;
}
|
@Test
public void testNoConditionWithState() {
KafkaRebalanceStatus kafkaRebalanceStatus = new KafkaRebalanceStatusBuilder()
.withConditions(
new ConditionBuilder()
.withType("Some other type")
.withStatus("True")
.build())
.build();
KafkaRebalanceState state = KafkaRebalanceUtils.rebalanceState(kafkaRebalanceStatus);
assertThat(state, is(nullValue()));
}
|
public Connector createConnector(Props props) {
Connector connector = new Connector(HTTP_PROTOCOL);
connector.setURIEncoding("UTF-8");
connector.setProperty("address", props.value(WEB_HOST.getKey(), "0.0.0.0"));
connector.setProperty("socket.soReuseAddress", "true");
// See Tomcat configuration reference: https://tomcat.apache.org/tomcat-9.0-doc/config/http.html
connector.setProperty("relaxedQueryChars", "\"<>[\\]^`{|}");
connector.setProperty("maxHttpHeaderSize", String.valueOf(MAX_HTTP_HEADER_SIZE_BYTES));
connector.setMaxPostSize(MAX_POST_SIZE);
configurePort(connector, props);
configurePool(props, connector);
configureCompression(connector);
return connector;
}
|
@Test
public void createConnector_whenNotValidPort_shouldThrow() {
Props props = getEmptyProps();
props.set("sonar.web.port", "-1");
assertThatThrownBy(() -> tomcatHttpConnectorFactory.createConnector(props))
.isInstanceOf(IllegalStateException.class)
.hasMessage("HTTP port -1 is invalid");
}
|
@Override
public PTransformOverrideFactory.PTransformReplacement<
PCollection<? extends InputT>, PCollection<OutputT>>
getReplacementTransform(
AppliedPTransform<
PCollection<? extends InputT>,
PCollection<OutputT>,
SingleOutput<InputT, OutputT>>
transform) {
return PTransformOverrideFactory.PTransformReplacement.of(
PTransformReplacements.getSingletonMainInput(transform),
new ParDoSingle<>(
transform.getTransform(),
Iterables.getOnlyElement(transform.getOutputs().keySet()),
PTransformReplacements.getSingletonMainOutput(transform).getCoder()));
}
|
@Test
public void getReplacementTransformPopulateDisplayData() {
ParDo.SingleOutput<Integer, Long> originalTransform = ParDo.of(new ToLongFn());
DisplayData originalDisplayData = DisplayData.from(originalTransform);
PCollection<? extends Integer> input = pipeline.apply(Create.of(1, 2, 3));
AppliedPTransform<
PCollection<? extends Integer>, PCollection<Long>, ParDo.SingleOutput<Integer, Long>>
application =
AppliedPTransform.of(
"original",
PValues.expandInput(input),
PValues.expandOutput(input.apply(originalTransform)),
originalTransform,
ResourceHints.create(),
pipeline);
PTransformReplacement<PCollection<? extends Integer>, PCollection<Long>> replacement =
factory.getReplacementTransform(application);
DisplayData replacementDisplayData = DisplayData.from(replacement.getTransform());
assertThat(replacementDisplayData, equalTo(originalDisplayData));
DisplayData primitiveDisplayData =
Iterables.getOnlyElement(
DisplayDataEvaluator.create()
.displayDataForPrimitiveTransforms(replacement.getTransform(), VarIntCoder.of()));
assertThat(primitiveDisplayData, equalTo(replacementDisplayData));
}
|
public CompressionProvider getCompressionProvider() {
return compressionProvider;
}
|
@Test
public void getCompressionProvider() {
CompressionProvider provider = inStream.getCompressionProvider();
assertEquals( provider.getName(), PROVIDER_NAME );
}
|
public void checkExecutePrerequisites(final ExecutionContext executionContext) {
ShardingSpherePreconditions.checkState(isValidExecutePrerequisites(executionContext), () -> new TableModifyInTransactionException(getTableName(executionContext)));
}
|
@Test
void assertCheckExecutePrerequisitesWhenExecuteCursorInPostgreSQLTransaction() {
when(transactionRule.getDefaultType()).thenReturn(TransactionType.LOCAL);
ExecutionContext executionContext = new ExecutionContext(
new QueryContext(createCursorStatementContext(), "", Collections.emptyList(), new HintValueContext(), mockConnectionContext(), mock(ShardingSphereMetaData.class)),
Collections.emptyList(), mock(RouteContext.class));
new ProxySQLExecutor(JDBCDriverType.STATEMENT, databaseConnectionManager, mock(DatabaseConnector.class), mockQueryContext()).checkExecutePrerequisites(executionContext);
}
|
@Override
public void set(String name, String value) {
checkKey(name);
String[] keyParts = splitKey(name);
String ns = registry.getNamespaceURI(keyParts[0]);
if (ns != null) {
try {
xmpData.setProperty(ns, keyParts[1], value);
} catch (XMPException e) {
// Ignore
}
}
}
|
@Test
public void set_unknownPrefixKey_throw() {
assertThrows(PropertyTypeException.class, () -> {
xmpMeta.set("unknown:key", "value");
});
}
|
public Timeline getStepInstanceTimeline(
String workflowId,
long workflowInstanceId,
long workflowRunId,
String stepId,
String stepAttempt) {
return getStepInstanceFieldByIds(
StepInstanceField.TIMELINE,
workflowId,
workflowInstanceId,
workflowRunId,
stepId,
stepAttempt,
this::getTimeline);
}
|
@Test
public void testGetStepInstanceTimeline() {
Timeline timeline = stepDao.getStepInstanceTimeline(TEST_WORKFLOW_ID, 1, 1, "job1", "1");
assertTrue(timeline.isEmpty());
Timeline latest = stepDao.getStepInstanceTimeline(TEST_WORKFLOW_ID, 1, 1, "job1", "latest");
assertEquals(timeline, latest);
}
|
public static void addContainerEnvsToExistingEnvs(Reconciliation reconciliation, List<EnvVar> existingEnvs, ContainerTemplate template) {
if (template != null && template.getEnv() != null) {
// Create set of env var names to test if any user defined template env vars will conflict with those set above
Set<String> predefinedEnvs = new HashSet<>();
for (EnvVar envVar : existingEnvs) {
predefinedEnvs.add(envVar.getName());
}
// Set custom env vars from the user defined template
for (ContainerEnvVar containerEnvVar : template.getEnv()) {
if (predefinedEnvs.contains(containerEnvVar.getName())) {
AbstractModel.LOGGER.warnCr(reconciliation, "User defined container template environment variable {} is already in use and will be ignored", containerEnvVar.getName());
} else {
existingEnvs.add(createEnvVar(containerEnvVar.getName(), containerEnvVar.getValue()));
}
}
}
}
|
@Test
public void testAddContainerToEnvVarsWithNullTemplate() {
List<EnvVar> vars = new ArrayList<>();
vars.add(new EnvVarBuilder().withName("VAR_1").withValue("value1").build());
ContainerUtils.addContainerEnvsToExistingEnvs(Reconciliation.DUMMY_RECONCILIATION, vars, null);
assertThat(vars.size(), is(1));
assertThat(vars.get(0).getName(), is("VAR_1"));
assertThat(vars.get(0).getValue(), is("value1"));
}
|
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
}
|
@Test
public void getStringLines_mix() {
Settings settings = new MapSettings();
settings.setProperty("foo", "one\r\ntwo\nthree");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two", "three"});
}
|
public boolean overlaps(final BoundingBox pBoundingBox, double pZoom) {
//FIXME this is a total hack but it works around a number of issues related to vertical map
//replication and horiztonal replication that can cause polygons to completely disappear when
//panning
if (pZoom < 3)
return true;
boolean latMatch = false;
boolean lonMatch = false;
//vertical wrapping detection
if (pBoundingBox.mLatSouth <= mLatNorth &&
pBoundingBox.mLatSouth >= mLatSouth)
latMatch = true;
//normal case, non overlapping
if (mLonWest >= pBoundingBox.mLonWest && mLonWest <= pBoundingBox.mLonEast)
lonMatch = true;
//normal case, non overlapping
if (mLonEast >= pBoundingBox.mLonWest && mLonWest <= pBoundingBox.mLonEast)
lonMatch = true;
//special case for when *this completely surrounds the pBoundbox
if (mLonWest <= pBoundingBox.mLonWest &&
mLonEast >= pBoundingBox.mLonEast &&
mLatNorth >= pBoundingBox.mLatNorth &&
mLatSouth <= pBoundingBox.mLatSouth)
return true;
//normal case, non overlapping
if (mLatNorth >= pBoundingBox.mLatSouth && mLatNorth <= mLatSouth)
latMatch = true;
//normal case, non overlapping
if (mLatSouth >= pBoundingBox.mLatSouth && mLatSouth <= mLatSouth)
latMatch = true;
if (mLonWest > mLonEast) {
//the date line is included in the bounding box
//we want to match lon from the dateline to the eastern bounds of the box
//and the dateline to the western bounds of the box
if (mLonEast <= pBoundingBox.mLonEast && pBoundingBox.mLonWest >= mLonWest)
lonMatch = true;
if (mLonWest >= pBoundingBox.mLonEast &&
mLonEast <= pBoundingBox.mLonEast) {
lonMatch = true;
if (pBoundingBox.mLonEast < mLonWest &&
pBoundingBox.mLonWest < mLonWest)
lonMatch = false;
if (pBoundingBox.mLonEast > mLonEast &&
pBoundingBox.mLonWest > mLonEast)
lonMatch = false;
}
if (mLonWest >= pBoundingBox.mLonEast &&
mLonEast >= pBoundingBox.mLonEast) {
lonMatch = true;
}
/*
//that is completely within this
if (mLonWest>= pBoundingBox.mLonEast &&
mLonEast<= pBoundingBox.mLonEast) {
lonMatch = true;
if (pBoundingBox.mLonEast < mLonWest &&
pBoundingBox.mLonWest < mLonWest)
lonMatch = false;
if (pBoundingBox.mLonEast > mLonEast &&
pBoundingBox.mLonWest > mLonEast )
lonMatch = false;
}
if (mLonWest>= pBoundingBox.mLonEast &&
mLonEast>= pBoundingBox.mLonEast) {
lonMatch = true;
}*/
}
return latMatch && lonMatch;
}
|
@Test
public void testOverlapsWorld() {
// ________________
// | | |
// | | |
// |------+-------|
// | | |
// | | |
// ----------------
//box is notated as *
//test area is notated as &
TileSystem ts = new TileSystemWebMercator();
BoundingBox box = new BoundingBox(ts.getMaxLatitude(), 180, ts.getMinLatitude(), -180);
Assert.assertTrue(box.overlaps(box, 4));
BoundingBox farAway = new BoundingBox(45, 44, 44, 45);
Assert.assertTrue(farAway.overlaps(farAway, 4));
Assert.assertTrue(box.overlaps(farAway, 4));
farAway = new BoundingBox(1, 44, 1, 45);
Assert.assertTrue(farAway.overlaps(farAway, 4));
Assert.assertTrue(box.overlaps(farAway, 4));
farAway = new BoundingBox(2, 2, -2, -2);
Assert.assertTrue(farAway.overlaps(farAway, 4));
Assert.assertTrue(box.overlaps(farAway, 4));
//this is completely within the test box
farAway = new BoundingBox(0.5, 0.5, -0.5, -0.5);
Assert.assertTrue(box.overlaps(farAway, 4));
}
|
@VisibleForTesting
static Map<String, List<String>> getCombinedHeaders(final Map<String, List<String>> upgradeRequestHeaders, final Map<String, String> requestMessageHeaders) {
final Map<String, List<String>> combinedHeaders = new HashMap<>();
upgradeRequestHeaders.entrySet().stream()
.filter(entry -> shouldIncludeUpgradeRequestHeader(entry.getKey()))
.forEach(entry -> combinedHeaders.put(entry.getKey(), entry.getValue()));
requestMessageHeaders.entrySet().stream()
.filter(entry -> shouldIncludeRequestMessageHeader(entry.getKey()))
.forEach(entry -> combinedHeaders.put(entry.getKey(), List.of(entry.getValue())));
return combinedHeaders;
}
|
@Test
void testGetCombinedHeaders() {
final Map<String, List<String>> upgradeRequestHeaders = Map.of(
"Host", List.of("server.example.com"),
"Upgrade", List.of("websocket"),
"Connection", List.of("Upgrade"),
"Sec-WebSocket-Key", List.of("dGhlIHNhbXBsZSBub25jZQ=="),
"Sec-WebSocket-Protocol", List.of("chat, superchat"),
"Sec-WebSocket-Version", List.of("13"),
HttpHeaders.X_FORWARDED_FOR, List.of("127.0.0.1"),
HttpHeaders.USER_AGENT, List.of("Upgrade request user agent"));
final Map<String, String> requestMessageHeaders = Map.of(
HttpHeaders.X_FORWARDED_FOR, "192.168.0.1",
HttpHeaders.USER_AGENT, "Request message user agent");
final Map<String, List<String>> expectedHeaders = Map.of(
"Host", List.of("server.example.com"),
HttpHeaders.X_FORWARDED_FOR, List.of("127.0.0.1"),
HttpHeaders.USER_AGENT, List.of("Request message user agent"));
assertThat(WebSocketResourceProvider.getCombinedHeaders(upgradeRequestHeaders, requestMessageHeaders)).isEqualTo(
expectedHeaders);
}
|
@CheckForNull
@Override
public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path projectBaseDir, Set<Path> changedFiles) {
return branchChangedLinesWithFileMovementDetection(targetBranchName, projectBaseDir, toChangedFileByPathsMap(changedFiles));
}
|
@Test
public void branchChangedLines_should_not_fail_with_patience_diff_algo() throws IOException {
Path gitConfig = worktree.resolve(".git").resolve("config");
Files.write(gitConfig, "[diff]\nalgorithm = patience\n".getBytes(StandardCharsets.UTF_8));
Repository repo = FileRepositoryBuilder.create(worktree.resolve(".git").toFile());
git = new Git(repo);
assertThat(newScmProvider().branchChangedLines("main", worktree, Collections.singleton(Paths.get("file")))).isNull();
}
|
@Override
protected Set<StepField> getUsedFields( RestMeta stepMeta ) {
Set<StepField> usedFields = new HashSet<>();
// add url field
if ( stepMeta.isUrlInField() && StringUtils.isNotEmpty( stepMeta.getUrlField() ) ) {
usedFields.addAll( createStepFields( stepMeta.getUrlField(), getInputs() ) );
}
// add method field
if ( stepMeta.isDynamicMethod() && StringUtils.isNotEmpty( stepMeta.getMethodFieldName() ) ) {
usedFields.addAll( createStepFields( stepMeta.getMethodFieldName(), getInputs() ) );
}
// add body field
if ( StringUtils.isNotEmpty( stepMeta.getBodyField() ) ) {
usedFields.addAll( createStepFields( stepMeta.getBodyField(), getInputs() ) );
}
// add parameters as used fields
String[] parameterFields = stepMeta.getParameterField();
if ( ArrayUtils.isNotEmpty( parameterFields ) ) {
for ( String paramField : parameterFields ) {
usedFields.addAll( createStepFields( paramField, getInputs() ) );
}
}
// add headers as used fields
String[] headerFields = stepMeta.getHeaderField();
if ( ArrayUtils.isNotEmpty( headerFields ) ) {
for ( String headerField : headerFields ) {
usedFields.addAll( createStepFields( headerField, getInputs() ) );
}
}
return usedFields;
}
|
@Test
public void testGetUsedFields_urlInField() throws Exception {
Set<StepField> fields = new HashSet<>();
when( meta.isUrlInField() ).thenReturn( true );
when( meta.getUrlField() ).thenReturn( "url" );
doReturn( stepNodes ).when( analyzer ).getInputs();
doReturn( fields ).when( analyzer ).createStepFields( "url", stepNodes );
Set<StepField> usedFields = analyzer.getUsedFields( meta );
verify( analyzer ).createStepFields( "url", stepNodes );
}
|
@Override
public void stop() {
lock.unlock();
}
|
@Test
/**
* If there is an error starting up the scan, we'll still try to unlock even if the lock
* was never done
*/
public void stopWithoutStarting() {
lock.stop();
lock.stop();
}
|
@Override
public void execute(String commandName, BufferedReader reader, BufferedWriter writer)
throws Py4JException, IOException {
char subCommand = safeReadLine(reader).charAt(0);
String returnCommand = null;
if (subCommand == LIST_SLICE_SUB_COMMAND_NAME) {
returnCommand = slice_list(reader);
} else if (subCommand == LIST_CONCAT_SUB_COMMAND_NAME) {
returnCommand = concat_list(reader);
} else if (subCommand == LIST_MULT_SUB_COMMAND_NAME) {
returnCommand = mult_list(reader);
} else if (subCommand == LIST_IMULT_SUB_COMMAND_NAME) {
returnCommand = imult_list(reader);
} else if (subCommand == LIST_COUNT_SUB_COMMAND_NAME) {
returnCommand = count_list(reader);
} else {
returnCommand = call_collections_method(reader, subCommand);
}
logger.finest("Returning command: " + returnCommand);
writer.write(returnCommand);
writer.flush();
}
|
@SuppressWarnings("rawtypes")
@Test
public void testConcat() {
String inputCommand = ListCommand.LIST_CONCAT_SUB_COMMAND_NAME + "\n" + target + "\n" + target2 + "\ne\n";
try {
// concat l + l2
command.execute("l", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!ylo2\n", sWriter.toString());
List newList = (List) gateway.getObject("o2");
assertEquals(7, newList.size());
assertEquals(4, list.size());
assertEquals(3, list2.size());
assertEquals(newList.get(4), list2.get(0));
// concat l + l
inputCommand = ListCommand.LIST_CONCAT_SUB_COMMAND_NAME + "\n" + target + "\n" + target + "\ne\n";
command.execute("l", new BufferedReader(new StringReader(inputCommand)), writer);
assertEquals("!ylo2\n!ylo3\n", sWriter.toString());
newList = (List) gateway.getObject("o3");
assertEquals(8, newList.size());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
|
public void printStreamedRow(final StreamedRow row) {
row.getErrorMessage().ifPresent(this::printErrorMessage);
row.getFinalMessage().ifPresent(finalMsg -> writer().println(finalMsg));
row.getHeader().ifPresent(this::printRowHeader);
if (row.getRow().isPresent()) {
switch (outputFormat) {
case JSON:
printAsJson(row.getRow().get());
break;
case TABULAR:
printAsTable(row.getRow().get());
break;
default:
throw new RuntimeException(String.format(
"Unexpected output format: '%s'",
outputFormat.name()
));
}
}
}
|
@Test
public void testPrintErrorStreamedRow() {
final FakeException exception = new FakeException();
console.printStreamedRow(StreamedRow.error(exception, Errors.ERROR_CODE_SERVER_ERROR));
assertThat(terminal.getOutputString(), is(exception.getMessage() + NEWLINE));
}
|
@SuppressWarnings( "unchecked" )
@Nullable
public <T extends VFSConnectionDetails> VFSConnectionProvider<T> getProvider(
@NonNull ConnectionManager manager,
@Nullable String key ) {
return (VFSConnectionProvider<T>) manager.getConnectionProvider( key );
}
|
@Test
public void testGetProviderReturnsNullForNonExistingProviderInManager() {
VFSConnectionProvider<VFSConnectionDetails> result =
vfsConnectionManagerHelper.getProvider( connectionManager, "missingProvider1" );
assertNull( result );
}
|
public static long noHeapMemoryMax() {
return noHeapMemoryUsage.getMax();
}
|
@Test
public void noHeapMemoryMax() {
long memoryUsed = MemoryUtil.noHeapMemoryMax();
Assert.assertNotEquals(0, memoryUsed);
}
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof DisplayModel))
return false;
DisplayModel other = (DisplayModel) obj;
if (this.backgroundColor != other.backgroundColor)
return false;
if (this.filter != other.filter)
return false;
if (this.fixedTileSize != other.fixedTileSize)
return false;
if (this.maxTextWidth != other.maxTextWidth)
return false;
if (Float.floatToIntBits(this.maxTextWidthFactor) != Float.floatToIntBits(other.maxTextWidthFactor))
return false;
if (this.tileSize != other.tileSize)
return false;
if (this.tileSizeMultiple != other.tileSizeMultiple)
return false;
if (Float.floatToIntBits(this.userScaleFactor) != Float.floatToIntBits(other.userScaleFactor))
return false;
return true;
}
|
@Test
public void equalsTest() {
DisplayModel displayModel1 = new DisplayModel();
DisplayModel displayModel2 = new DisplayModel();
DisplayModel displayModel3 = new DisplayModel();
displayModel3.setBackgroundColor(0xffff0000);
DisplayModel displayModel4 = new DisplayModel();
displayModel4.setFixedTileSize(512);
DisplayModel displayModel5 = new DisplayModel();
displayModel5.setMaxTextWidthFactor(0.5f);
DisplayModel displayModel6 = new DisplayModel();
displayModel6.setTileSizeMultiple(200);
DisplayModel displayModel7 = new DisplayModel();
displayModel7.setUserScaleFactor(0.3f);
TestUtils.equalsTest(displayModel1, displayModel2);
TestUtils.notEqualsTest(displayModel1, displayModel3);
TestUtils.notEqualsTest(displayModel1, displayModel4);
TestUtils.notEqualsTest(displayModel1, displayModel5);
TestUtils.notEqualsTest(displayModel1, displayModel6);
TestUtils.notEqualsTest(displayModel1, displayModel7);
TestUtils.notEqualsTest(displayModel1, new Object());
TestUtils.notEqualsTest(displayModel1, null);
}
|
public Protocol forName(final String identifier) {
return this.forName(identifier, null);
}
|
@Test
public void testPrioritizeNonDeprecatedWithTypeLookup() {
final TestProtocol first = new TestProtocol(Scheme.http) {
@Override
public Type getType() {
return Type.dracoon;
}
@Override
public String getProvider() {
return "test-provider1";
}
@Override
public boolean isBundled() {
return false;
}
@Override
public boolean isDeprecated() {
return true;
}
};
final TestProtocol second = new TestProtocol(Scheme.http) {
@Override
public Type getType() {
return Type.dracoon;
}
@Override
public String getProvider() {
return "test-provider2";
}
@Override
public boolean isBundled() {
return false;
}
};
final ProtocolFactory f = new ProtocolFactory(new LinkedHashSet<>(Arrays.asList(first, second)));
assertEquals(second, f.forName("test", "test-provider2"));
assertEquals(first, f.forName("test", "test-provider1"));
assertEquals(second, f.forName("dracoon"));
}
|
@Override
public ScannerReport.Metadata readMetadata() {
ensureInitialized();
if (this.metadata == null) {
this.metadata = delegate.readMetadata();
}
return this.metadata;
}
|
@Test
public void readMetadata_result_is_cached() {
ScannerReport.Metadata metadata = ScannerReport.Metadata.newBuilder().build();
writer.writeMetadata(metadata);
ScannerReport.Metadata res = underTest.readMetadata();
assertThat(res).isEqualTo(metadata);
assertThat(underTest.readMetadata()).isSameAs(res);
}
|
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj != null && obj.getClass() == ResourceSpec.class) {
ResourceSpec that = (ResourceSpec) obj;
return Objects.equals(this.cpuCores, that.cpuCores)
&& Objects.equals(this.taskHeapMemory, that.taskHeapMemory)
&& Objects.equals(this.taskOffHeapMemory, that.taskOffHeapMemory)
&& Objects.equals(this.managedMemory, that.managedMemory)
&& Objects.equals(extendedResources, that.extendedResources);
} else {
return false;
}
}
|
@Test
void testEquals() {
ResourceSpec rs1 = ResourceSpec.newBuilder(1.0, 100).build();
ResourceSpec rs2 = ResourceSpec.newBuilder(1.0, 100).build();
assertThat(rs2).isEqualTo(rs1);
assertThat(rs1).isEqualTo(rs2);
ResourceSpec rs3 =
ResourceSpec.newBuilder(1.0, 100)
.setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 2.2))
.build();
ResourceSpec rs4 =
ResourceSpec.newBuilder(1.0, 100)
.setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 1))
.build();
assertThat(rs4).isNotEqualTo(rs3);
ResourceSpec rs5 =
ResourceSpec.newBuilder(1.0, 100)
.setExtendedResource(new ExternalResource(EXTERNAL_RESOURCE_NAME, 2.2))
.build();
assertThat(rs5).isEqualTo(rs3);
}
|
@Override
public boolean putRow( RowMetaInterface rowMeta, Object[] rowData ) {
this.rowMeta = rowMeta;
this.row = rowData;
return true;
}
|
@Test
public void testPutRow() throws Exception {
rowSet.putRow( new RowMeta(), row );
assertSame( row, rowSet.getRow() );
}
|
public static KeyStore loadKeyStore(final String name, final char[] password) {
InputStream stream = null;
try {
stream = Config.getInstance().getInputStreamFromFile(name);
if (stream == null) {
String message = "Unable to load keystore '" + name + "', please provide the keystore matching the configuration in client.yml/server.yml to enable TLS connection.";
if (logger.isErrorEnabled()) {
logger.error(message);
}
throw new RuntimeException(message);
}
// try to load keystore as JKS
try {
KeyStore loadedKeystore = KeyStore.getInstance("JKS");
loadedKeystore.load(stream, password);
return loadedKeystore;
} catch (Exception e) {
// if JKS fails, attempt to load as PKCS12
try {
stream.close();
stream = Config.getInstance().getInputStreamFromFile(name);
KeyStore loadedKeystore = KeyStore.getInstance("PKCS12");
loadedKeystore.load(stream, password);
return loadedKeystore;
} catch (Exception e2) {
logger.error("Unable to load keystore " + name, e2);
throw new RuntimeException("Unable to load keystore " + name, e2);
}
}
} catch (Exception e) {
logger.error("Unable to load stream for keystore " + name, e);
throw new RuntimeException("Unable to load stream for keystore " + name, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
logger.error("Unable to close stream for keystore " + name, e);
}
}
}
}
|
@Test
public void testLoadValidKeyStore() {
KeyStore keyStore = TlsUtil.loadKeyStore(KEYSTORE_NAME, PASSWORD);
Assert.assertNotNull(keyStore);
}
|
@Override
public <T> T unwrap(final Class<T> iface) {
return null;
}
|
@Test
void assertUnwrap() {
assertNull(metaData.unwrap(null));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.