language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/discriminator/associations/OneToManyJoinFetchDiscriminatorTest.java | {
"start": 3149,
"end": 3547
} | class ____ extends BaseEntity {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "person", cascade = CascadeType.ALL)
private Set<Leg> legs = new HashSet<>();
public Set<Leg> getLegs() {
return legs;
}
}
@Entity(name = "BodyPart")
@Table(name = "body_part")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "discriminator")
public abstract static | Person |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/webapp/dao/TestJobInfo.java | {
"start": 2204,
"end": 7315
} | class ____ {
@Test
@Timeout(value = 10)
public void testAverageMergeTime() throws IOException {
String historyFileName =
"job_1329348432655_0001-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist";
String confFileName =
"job_1329348432655_0001_conf.xml";
Configuration conf = new Configuration();
JobACLsManager jobAclsMgr = new JobACLsManager(conf);
Path fulleHistoryPath =
new Path(TestJobHistoryEntities.class.getClassLoader()
.getResource(historyFileName)
.getFile());
Path fullConfPath =
new Path(TestJobHistoryEntities.class.getClassLoader()
.getResource(confFileName)
.getFile());
HistoryFileInfo info = mock(HistoryFileInfo.class);
when(info.getConfFile()).thenReturn(fullConfPath);
when(info.getHistoryFile()).thenReturn(fulleHistoryPath);
JobId jobId = MRBuilderUtils.newJobId(1329348432655L, 1, 1);
CompletedJob completedJob =
new CompletedJob(conf, jobId, fulleHistoryPath, true, "user",
info, jobAclsMgr);
JobInfo jobInfo = new JobInfo(completedJob);
// There are 2 tasks with merge time of 45 and 55 respectively. So average
// merge time should be 50.
assertEquals(50L, jobInfo.getAvgMergeTime().longValue());
}
@Test
public void testAverageReduceTime() {
Job job = mock(CompletedJob.class);
final Task task1 = mock(Task.class);
final Task task2 = mock(Task.class);
JobId jobId = MRBuilderUtils.newJobId(1L, 1, 1);
final TaskId taskId1 = MRBuilderUtils.newTaskId(jobId, 1, TaskType.REDUCE);
final TaskId taskId2 = MRBuilderUtils.newTaskId(jobId, 2, TaskType.REDUCE);
final TaskAttemptId taskAttemptId1 = MRBuilderUtils.
newTaskAttemptId(taskId1, 1);
final TaskAttemptId taskAttemptId2 = MRBuilderUtils.
newTaskAttemptId(taskId2, 2);
final TaskAttempt taskAttempt1 = mock(TaskAttempt.class);
final TaskAttempt taskAttempt2 = mock(TaskAttempt.class);
JobReport jobReport = mock(JobReport.class);
when(taskAttempt1.getState()).thenReturn(TaskAttemptState.SUCCEEDED);
when(taskAttempt1.getLaunchTime()).thenReturn(0L);
when(taskAttempt1.getShuffleFinishTime()).thenReturn(4L);
when(taskAttempt1.getSortFinishTime()).thenReturn(6L);
when(taskAttempt1.getFinishTime()).thenReturn(8L);
when(taskAttempt2.getState()).thenReturn(TaskAttemptState.SUCCEEDED);
when(taskAttempt2.getLaunchTime()).thenReturn(5L);
when(taskAttempt2.getShuffleFinishTime()).thenReturn(10L);
when(taskAttempt2.getSortFinishTime()).thenReturn(22L);
when(taskAttempt2.getFinishTime()).thenReturn(42L);
when(task1.getType()).thenReturn(TaskType.REDUCE);
when(task2.getType()).thenReturn(TaskType.REDUCE);
when(task1.getAttempts()).thenReturn
(new HashMap<TaskAttemptId, TaskAttempt>()
{{put(taskAttemptId1,taskAttempt1); }});
when(task2.getAttempts()).thenReturn
(new HashMap<TaskAttemptId, TaskAttempt>()
{{put(taskAttemptId2,taskAttempt2); }});
when(job.getTasks()).thenReturn
(new HashMap<TaskId, Task>()
{{ put(taskId1,task1); put(taskId2, task2); }});
when(job.getID()).thenReturn(jobId);
when(job.getReport()).thenReturn(jobReport);
when(job.getName()).thenReturn("TestJobInfo");
when(job.getState()).thenReturn(JobState.SUCCEEDED);
JobInfo jobInfo = new JobInfo(job);
assertEquals(11L, jobInfo.getAvgReduceTime().longValue());
}
@Test
public void testGetStartTimeStr() {
JobReport jobReport = mock(JobReport.class);
when(jobReport.getStartTime()).thenReturn(-1L);
Job job = mock(Job.class);
when(job.getReport()).thenReturn(jobReport);
when(job.getName()).thenReturn("TestJobInfo");
when(job.getState()).thenReturn(JobState.SUCCEEDED);
JobId jobId = MRBuilderUtils.newJobId(1L, 1, 1);
when(job.getID()).thenReturn(jobId);
JobInfo jobInfo = new JobInfo(job);
assertEquals(JobInfo.NA, jobInfo.getStartTimeStr());
Date date = new Date();
when(jobReport.getStartTime()).thenReturn(date.getTime());
jobInfo = new JobInfo(job);
assertEquals(date.toString(), jobInfo.getStartTimeStr());
}
@Test
public void testGetFormattedStartTimeStr() {
JobReport jobReport = mock(JobReport.class);
when(jobReport.getStartTime()).thenReturn(-1L);
Job job = mock(Job.class);
when(job.getReport()).thenReturn(jobReport);
when(job.getName()).thenReturn("TestJobInfo");
when(job.getState()).thenReturn(JobState.SUCCEEDED);
JobId jobId = MRBuilderUtils.newJobId(1L, 1, 1);
when(job.getID()).thenReturn(jobId);
DateFormat dateFormat = new SimpleDateFormat();
JobInfo jobInfo = new JobInfo(job);
assertEquals(JobInfo.NA, jobInfo.getFormattedStartTimeStr(dateFormat));
Date date = new Date();
when(jobReport.getStartTime()).thenReturn(date.getTime());
jobInfo = new JobInfo(job);
assertEquals(dateFormat.format(date), jobInfo.getFormattedStartTimeStr(dateFormat));
}
}
| TestJobInfo |
java | apache__rocketmq | test/src/main/java/org/apache/rocketmq/test/util/StatUtil.java | {
"start": 2768,
"end": 17015
} | class ____ implements Comparable<SecondInvoke> {
AtomicLong total = new AtomicLong();
AtomicLong fail = new AtomicLong();
AtomicLong sumRt = new AtomicLong();
AtomicLong maxRt = new AtomicLong();
AtomicLong minRt = new AtomicLong();
Long second = nowSecond();
@Override
public int compareTo(SecondInvoke o) {
return o.second.compareTo(second);
}
}
static {
daemon.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
printInvokeStat();
printSecondInvokeStat();
} catch (Exception e) {
logger.error("", e);
}
}
}, STAT_WINDOW_SECONDS, STAT_WINDOW_SECONDS, TimeUnit.SECONDS);
}
private static void printInvokeStat() {
Map<String, Invoke> tmp = invokeCache;
invokeCache = new ConcurrentHashMap<>(64);
sysLogger.warn("printInvokeStat key count:{}", tmp.size());
for (Map.Entry<String, Invoke> entry : tmp.entrySet()) {
String key = entry.getKey();
Invoke invoke = entry.getValue();
logger.warn("{}",
buildLog(key, invoke.topSecondPv.get(), invoke.totalPv.get(), invoke.failPv.get(), invoke.minRt.get(),
invoke.maxRt.get(), invoke.sumRt.get()));
}
}
private static void printSecondInvokeStat() {
sysLogger.warn("printSecondInvokeStat key count:{}", secondInvokeCache.size());
for (Map.Entry<String, Map<Long, SecondInvoke>> entry : secondInvokeCache.entrySet()) {
String key = entry.getKey();
Map<Long, SecondInvoke> secondInvokeMap = entry.getValue();
long totalPv = 0L;
long failPv = 0L;
long topSecondPv = 0L;
long sumRt = 0L;
long maxRt = 0L;
long minRt = 0L;
for (Map.Entry<Long, SecondInvoke> invokeEntry : secondInvokeMap.entrySet()) {
long second = invokeEntry.getKey();
SecondInvoke secondInvoke = invokeEntry.getValue();
if (nowSecond() - second >= STAT_WINDOW_SECONDS) {
secondInvokeMap.remove(second);
continue;
}
long secondPv = secondInvoke.total.get();
totalPv += secondPv;
failPv += secondInvoke.fail.get();
sumRt += secondInvoke.sumRt.get();
if (maxRt < secondInvoke.maxRt.get()) {
maxRt = secondInvoke.maxRt.get();
}
if (minRt > secondInvoke.minRt.get()) {
minRt = secondInvoke.minRt.get();
}
if (topSecondPv < secondPv) {
topSecondPv = secondPv;
}
}
if (secondInvokeMap.isEmpty()) {
secondInvokeCache.remove(key);
continue;
}
logger.warn("{}", buildLog(key, topSecondPv, totalPv, failPv, minRt, maxRt, sumRt));
}
}
private static String buildLog(String key, long topSecondPv, long totalPv, long failPv, long minRt, long maxRt,
long sumRt) {
StringBuilder sb = new StringBuilder();
sb.append(SPLITTER);
sb.append(key);
sb.append(SPLITTER);
sb.append(topSecondPv);
sb.append(SPLITTER);
int tps = new BigDecimal(totalPv).divide(new BigDecimal(STAT_WINDOW_SECONDS),
ROUND_HALF_UP).intValue();
sb.append(tps);
sb.append(SPLITTER);
sb.append(totalPv);
sb.append(SPLITTER);
sb.append(failPv);
sb.append(SPLITTER);
sb.append(minRt);
sb.append(SPLITTER);
long avg = new BigDecimal(sumRt).divide(new BigDecimal(totalPv),
ROUND_HALF_UP).longValue();
sb.append(avg);
sb.append(SPLITTER);
sb.append(maxRt);
return sb.toString();
}
public static String buildKey(String... keys) {
if (keys == null || keys.length <= 0) {
return null;
}
StringBuilder sb = new StringBuilder();
for (String key : keys) {
sb.append(key);
sb.append(",");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
public static void addInvoke(String key, long rt) {
addInvoke(key, rt, true);
}
private static Invoke getAndSetInvoke(String key) {
Invoke invoke = invokeCache.get(key);
if (invoke == null) {
invokeCache.putIfAbsent(key, new Invoke());
}
return invokeCache.get(key);
}
public static void addInvoke(String key, int num, long rt, boolean success) {
if (invokeCache.size() > MAX_KEY_NUM || secondInvokeCache.size() > MAX_KEY_NUM) {
return;
}
Invoke invoke = getAndSetInvoke(key);
if (invoke == null) {
return;
}
invoke.totalPv.getAndAdd(num);
if (!success) {
invoke.failPv.getAndAdd(num);
}
long now = nowSecond();
AtomicLong oldSecond = invoke.second;
if (oldSecond.get() == now) {
invoke.secondPv.getAndAdd(num);
} else {
if (oldSecond.compareAndSet(oldSecond.get(), now)) {
if (invoke.secondPv.get() > invoke.topSecondPv.get()) {
invoke.topSecondPv.set(invoke.secondPv.get());
}
invoke.secondPv.set(num);
} else {
invoke.secondPv.getAndAdd(num);
}
}
invoke.sumRt.addAndGet(rt);
if (invoke.maxRt.get() < rt) {
invoke.maxRt.set(rt);
}
if (invoke.minRt.get() > rt) {
invoke.minRt.set(rt);
}
}
public static void addInvoke(String key, long rt, boolean success) {
if (invokeCache.size() > MAX_KEY_NUM || secondInvokeCache.size() > MAX_KEY_NUM) {
return;
}
Invoke invoke = getAndSetInvoke(key);
if (invoke == null) {
return;
}
invoke.totalPv.getAndIncrement();
if (!success) {
invoke.failPv.getAndIncrement();
}
long now = nowSecond();
AtomicLong oldSecond = invoke.second;
if (oldSecond.get() == now) {
invoke.secondPv.getAndIncrement();
} else {
if (oldSecond.compareAndSet(oldSecond.get(), now)) {
if (invoke.secondPv.get() > invoke.topSecondPv.get()) {
invoke.topSecondPv.set(invoke.secondPv.get());
}
invoke.secondPv.set(1);
} else {
invoke.secondPv.getAndIncrement();
}
}
invoke.sumRt.addAndGet(rt);
if (invoke.maxRt.get() < rt) {
invoke.maxRt.set(rt);
}
if (invoke.minRt.get() > rt) {
invoke.minRt.set(rt);
}
}
public static SecondInvoke getAndSetSecondInvoke(String key) {
if (!secondInvokeCache.containsKey(key)) {
secondInvokeCache.putIfAbsent(key, new ConcurrentHashMap<>(STAT_WINDOW_SECONDS));
}
Map<Long, SecondInvoke> secondInvokeMap = secondInvokeCache.get(key);
if (secondInvokeMap == null) {
return null;
}
long second = nowSecond();
if (!secondInvokeMap.containsKey(second)) {
secondInvokeMap.putIfAbsent(second, new SecondInvoke());
}
return secondInvokeMap.get(second);
}
public static void addSecondInvoke(String key, long rt) {
addSecondInvoke(key, rt, true);
}
public static void addSecondInvoke(String key, long rt, boolean success) {
if (invokeCache.size() > MAX_KEY_NUM || secondInvokeCache.size() > MAX_KEY_NUM) {
return;
}
SecondInvoke secondInvoke = getAndSetSecondInvoke(key);
if (secondInvoke == null) {
return;
}
secondInvoke.total.addAndGet(1);
if (!success) {
secondInvoke.fail.addAndGet(1);
}
secondInvoke.sumRt.addAndGet(rt);
if (secondInvoke.maxRt.get() < rt) {
secondInvoke.maxRt.set(rt);
}
if (secondInvoke.minRt.get() > rt) {
secondInvoke.minRt.set(rt);
}
}
public static void addPv(String key, long totalPv) {
addPv(key, totalPv, true);
}
public static void addPv(String key, long totalPv, boolean success) {
if (invokeCache.size() > MAX_KEY_NUM || secondInvokeCache.size() > MAX_KEY_NUM) {
return;
}
if (totalPv <= 0) {
return;
}
Invoke invoke = getAndSetInvoke(key);
if (invoke == null) {
return;
}
invoke.totalPv.addAndGet(totalPv);
if (!success) {
invoke.failPv.addAndGet(totalPv);
}
long now = nowSecond();
AtomicLong oldSecond = invoke.second;
if (oldSecond.get() == now) {
invoke.secondPv.addAndGet((int)totalPv);
} else {
if (oldSecond.compareAndSet(oldSecond.get(), now)) {
if (invoke.secondPv.get() > invoke.topSecondPv.get()) {
invoke.topSecondPv.set(invoke.secondPv.get());
}
invoke.secondPv.set((int)totalPv);
} else {
invoke.secondPv.addAndGet((int)totalPv);
}
}
}
public static void addSecondPv(String key, long totalPv) {
addSecondPv(key, totalPv, true);
}
public static void addSecondPv(String key, long totalPv, boolean success) {
if (invokeCache.size() > MAX_KEY_NUM || secondInvokeCache.size() > MAX_KEY_NUM) {
return;
}
if (totalPv <= 0) {
return;
}
SecondInvoke secondInvoke = getAndSetSecondInvoke(key);
if (secondInvoke == null) {
return;
}
secondInvoke.total.addAndGet(totalPv);
if (!success) {
secondInvoke.fail.addAndGet(totalPv);
}
}
public static boolean isOverFlow(String key, int tps) {
return nowTps(key) >= tps;
}
public static int nowTps(String key) {
Map<Long, SecondInvoke> secondInvokeMap = secondInvokeCache.get(key);
if (secondInvokeMap != null) {
SecondInvoke secondInvoke = secondInvokeMap.get(nowSecond());
if (secondInvoke != null) {
return (int)secondInvoke.total.get();
}
}
Invoke invoke = invokeCache.get(key);
if (invoke == null) {
return 0;
}
AtomicLong oldSecond = invoke.second;
if (oldSecond.get() == nowSecond()) {
return invoke.secondPv.get();
}
return 0;
}
public static int totalPvInWindow(String key, int windowSeconds) {
List<SecondInvoke> list = secondInvokeList(key, windowSeconds);
long totalPv = 0;
for (int i = 0; i < windowSeconds && i < list.size(); i++) {
totalPv += list.get(i).total.get();
}
return (int)totalPv;
}
public static int failPvInWindow(String key, int windowSeconds) {
List<SecondInvoke> list = secondInvokeList(key, windowSeconds);
long failPv = 0;
for (int i = 0; i < windowSeconds && i < list.size(); i++) {
failPv += list.get(i).fail.get();
}
return (int)failPv;
}
public static int topTpsInWindow(String key, int windowSeconds) {
List<SecondInvoke> list = secondInvokeList(key, windowSeconds);
long topTps = 0;
for (int i = 0; i < windowSeconds && i < list.size(); i++) {
long secondPv = list.get(i).total.get();
if (topTps < secondPv) {
topTps = secondPv;
}
}
return (int)topTps;
}
public static int avgRtInWindow(String key, int windowSeconds) {
List<SecondInvoke> list = secondInvokeList(key, windowSeconds);
long sumRt = 0;
long totalPv = 0;
for (int i = 0; i < windowSeconds && i < list.size(); i++) {
sumRt += list.get(i).sumRt.get();
totalPv += list.get(i).total.get();
}
if (totalPv <= 0) {
return 0;
}
long avg = new BigDecimal(sumRt).divide(new BigDecimal(totalPv),
ROUND_HALF_UP).longValue();
return (int)avg;
}
public static int maxRtInWindow(String key, int windowSeconds) {
List<SecondInvoke> list = secondInvokeList(key, windowSeconds);
long maxRt = 0;
long totalPv = 0;
for (int i = 0; i < windowSeconds && i < list.size(); i++) {
if (maxRt < list.get(i).maxRt.get()) {
maxRt = list.get(i).maxRt.get();
}
}
return (int)maxRt;
}
public static int minRtInWindow(String key, int windowSeconds) {
List<SecondInvoke> list = secondInvokeList(key, windowSeconds);
long minRt = 0;
long totalPv = 0;
for (int i = 0; i < windowSeconds && i < list.size(); i++) {
if (minRt < list.get(i).minRt.get()) {
minRt = list.get(i).minRt.get();
}
}
return (int)minRt;
}
private static List<SecondInvoke> secondInvokeList(String key, int windowSeconds) {
if (windowSeconds > STAT_WINDOW_SECONDS || windowSeconds <= 0) {
throw new IllegalArgumentException("windowSeconds Must Not be great than " + STAT_WINDOW_SECONDS);
}
Map<Long, SecondInvoke> secondInvokeMap = secondInvokeCache.get(key);
if (secondInvokeMap == null || secondInvokeMap.isEmpty()) {
return new ArrayList<>();
}
List<SecondInvoke> list = new ArrayList<>();
list.addAll(secondInvokeMap.values());
Collections.sort(list);
return list;
}
private static long nowSecond() {
return System.currentTimeMillis() / 1000L;
}
}
| SecondInvoke |
java | grpc__grpc-java | android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java | {
"start": 34839,
"end": 37821
} | class ____
extends io.grpc.stub.AbstractBlockingStub<TestServiceBlockingStub> {
private TestServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected TestServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new TestServiceBlockingStub(channel, callOptions);
}
/**
* <pre>
* One empty request followed by one empty response.
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty emptyCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getEmptyCallMethod(), getCallOptions(), request);
}
/**
* <pre>
* One request followed by one response.
* </pre>
*/
public io.grpc.testing.integration.Messages.SimpleResponse unaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnaryCallMethod(), getCallOptions(), request);
}
/**
* <pre>
* One request followed by one response. Response has cache control
* headers set such that a caching HTTP proxy (such as GFE) can
* satisfy subsequent requests.
* </pre>
*/
public io.grpc.testing.integration.Messages.SimpleResponse cacheableUnaryCall(io.grpc.testing.integration.Messages.SimpleRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCacheableUnaryCallMethod(), getCallOptions(), request);
}
/**
* <pre>
* One request followed by a sequence of responses (streamed download).
* The server returns the payload with client desired type and sizes.
* </pre>
*/
public java.util.Iterator<io.grpc.testing.integration.Messages.StreamingOutputCallResponse> streamingOutputCall(
io.grpc.testing.integration.Messages.StreamingOutputCallRequest request) {
return io.grpc.stub.ClientCalls.blockingServerStreamingCall(
getChannel(), getStreamingOutputCallMethod(), getCallOptions(), request);
}
/**
* <pre>
* The test server will not implement this method. It will be used
* to test the behavior when clients call unimplemented methods.
* </pre>
*/
public io.grpc.testing.integration.EmptyProtos.Empty unimplementedCall(io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUnimplementedCallMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service TestService.
* <pre>
* A simple service to test the various types of RPCs and experiment with
* performance with various types of payload.
* </pre>
*/
public static final | TestServiceBlockingStub |
java | quarkusio__quarkus | extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/devui/DevInterceptorInfo.java | {
"start": 327,
"end": 2901
} | class ____ implements Comparable<DevInterceptorInfo> {
public static DevInterceptorInfo from(InterceptorInfo interceptor, CompletedApplicationClassPredicateBuildItem predicate) {
boolean isApplicationBean = predicate.test(interceptor.getBeanClass());
Set<Name> bindings = new HashSet<>();
for (AnnotationInstance binding : interceptor.getBindings()) {
bindings.add(Name.from(binding));
}
Set<InterceptionType> intercepts = new HashSet<>();
if (interceptor.intercepts(InterceptionType.AROUND_INVOKE)) {
intercepts.add(InterceptionType.AROUND_INVOKE);
}
if (interceptor.intercepts(InterceptionType.AROUND_CONSTRUCT)) {
intercepts.add(InterceptionType.AROUND_CONSTRUCT);
}
if (interceptor.intercepts(InterceptionType.POST_CONSTRUCT)) {
intercepts.add(InterceptionType.POST_CONSTRUCT);
}
if (interceptor.intercepts(InterceptionType.PRE_DESTROY)) {
intercepts.add(InterceptionType.PRE_DESTROY);
}
return new DevInterceptorInfo(interceptor.getIdentifier(), Name.from(interceptor.getBeanClass()), bindings,
interceptor.getPriority(), intercepts,
isApplicationBean);
}
private final String id;
private final Name interceptorClass;
private final Set<Name> bindings;
private final int priority;
private final Set<InterceptionType> intercepts;
private final boolean isApplicationBean;
DevInterceptorInfo(String id, Name interceptorClass, Set<Name> bindings, int priority,
Set<InterceptionType> intercepts, boolean isApplicationBean) {
this.id = id;
this.interceptorClass = interceptorClass;
this.bindings = bindings;
this.priority = priority;
this.intercepts = intercepts;
this.isApplicationBean = isApplicationBean;
}
public String getId() {
return id;
}
public Name getInterceptorClass() {
return interceptorClass;
}
public Set<Name> getBindings() {
return bindings;
}
public int getPriority() {
return priority;
}
public Set<InterceptionType> getIntercepts() {
return intercepts;
}
@Override
public int compareTo(DevInterceptorInfo o) {
// Application beans should go first
if (isApplicationBean == o.isApplicationBean) {
return interceptorClass.compareTo(o.interceptorClass);
}
return isApplicationBean ? -1 : 1;
}
}
| DevInterceptorInfo |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/appender/AlwaysFailAppender.java | {
"start": 1524,
"end": 2085
} | class ____ extends AbstractAppender {
private AlwaysFailAppender(final String name) {
super(name, null, null, false, Property.EMPTY_ARRAY);
}
@Override
public void append(final LogEvent event) {
throw new LoggingException("Always fail");
}
@PluginFactory
public static AlwaysFailAppender createAppender(
@PluginAttribute("name") @Required(message = "A name for the Appender must be specified")
final String name) {
return new AlwaysFailAppender(name);
}
}
| AlwaysFailAppender |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4361ForceDependencySnapshotUpdateTest.java | {
"start": 1212,
"end": 3381
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that snapshot updates of dependencies can be forced from the command line via "-U". In more detail,
* this means updating the JAR and its accompanying hierarchy of POMs.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4361");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteArtifacts("org.apache.maven.its.mng4361");
verifier.addCliArgument("-s");
verifier.addCliArgument("settings.xml");
Map<String, String> filterProps = verifier.newDefaultFilterMap();
filterProps.put("@repo@", "repo-1");
verifier.filterFile("settings-template.xml", "settings.xml", filterProps);
verifier.setLogFileName("log-force-1.txt");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
assertNull(verifier.loadProperties("target/checksum.properties").getProperty("b-0.1-SNAPSHOT.jar"));
filterProps.put("@repo@", "repo-2");
verifier.filterFile("settings-template.xml", "settings.xml", filterProps);
verifier.setLogFileName("log-force-2.txt");
verifier.deleteDirectory("target");
verifier.addCliArgument("-U");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties checksums = verifier.loadProperties("target/checksum.properties");
assertChecksum("2a22eeca91211193e927ea3b2ecdf56481585064", "a-0.1-SNAPSHOT.jar", checksums);
assertChecksum("ae352eb0047059b2e47fae397eb8ae6bd5b1c8ea", "b-0.1-SNAPSHOT.jar", checksums);
assertChecksum("6e6ef8590f166bcf610965c74c165128776214b9", "c-0.1-SNAPSHOT.jar", checksums);
}
private void assertChecksum(String checksum, String jar, Properties checksums) {
assertEquals(checksum, checksums.getProperty(jar, "").toLowerCase(java.util.Locale.ENGLISH));
}
}
| MavenITmng4361ForceDependencySnapshotUpdateTest |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/notification/email/EmailSecretsIntegrationTests.java | {
"start": 2544,
"end": 7497
} | class ____ extends AbstractWatcherIntegrationTestCase {
private EmailServer server;
private Boolean encryptSensitiveData;
private byte[] encryptionKey;
@Override
public void setUp() throws Exception {
super.setUp();
server = EmailServer.localhost(logger);
}
@After
public void cleanup() throws Exception {
server.stop();
}
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
if (encryptSensitiveData == null) {
encryptSensitiveData = randomBoolean();
if (encryptSensitiveData) {
encryptionKey = CryptoServiceTests.generateKey();
}
}
Settings.Builder builder = Settings.builder()
.put(super.nodeSettings(nodeOrdinal, otherSettings))
.put("xpack.notification.email.account.test.smtp.auth", true)
.put("xpack.notification.email.account.test.smtp.port", server.port())
.put("xpack.notification.email.account.test.smtp.host", "localhost")
.put("xpack.watcher.encrypt_sensitive_data", encryptSensitiveData);
if (encryptSensitiveData) {
MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setFile(WatcherField.ENCRYPTION_KEY_SETTING.getKey(), encryptionKey);
builder.setSecureSettings(secureSettings);
}
return builder.build();
}
public void testEmail() throws Exception {
new PutWatchRequestBuilder(client(), "_id").setSource(
watchBuilder().trigger(schedule(cron("0 0 0 1 * ? 2020")))
.input(simpleInput())
.condition(InternalAlwaysCondition.INSTANCE)
.addAction(
"_email",
ActionBuilders.emailAction(EmailTemplate.builder().from("from@example.org").to("to@example.org").subject("_subject"))
.setAuthentication(EmailServer.USERNAME, EmailServer.PASSWORD.toCharArray())
)
).get();
// verifying the email password is stored encrypted in the index
GetResponse response = client().prepareGet().setIndex(Watch.INDEX).setId("_id").get();
assertThat(response, notNullValue());
assertThat(response.getId(), is("_id"));
Map<String, Object> source = response.getSource();
Object value = XContentMapValues.extractValue("actions._email.email.password", source);
assertThat(value, notNullValue());
if (encryptSensitiveData) {
assertThat(value, not(is(EmailServer.PASSWORD)));
MockSecureSettings mockSecureSettings = new MockSecureSettings();
mockSecureSettings.setFile(WatcherField.ENCRYPTION_KEY_SETTING.getKey(), encryptionKey);
Settings settings = Settings.builder().setSecureSettings(mockSecureSettings).build();
CryptoService cryptoService = new CryptoService(settings);
assertThat(new String(cryptoService.decrypt(((String) value).toCharArray())), is(EmailServer.PASSWORD));
} else {
assertThat(value, is(EmailServer.PASSWORD));
}
// verifying the password is not returned by the GET watch API
GetWatchResponse watchResponse = new GetWatchRequestBuilder(client(), "_id").get();
assertThat(watchResponse, notNullValue());
assertThat(watchResponse.getId(), is("_id"));
XContentSource contentSource = watchResponse.getSource();
value = contentSource.getValue("actions._email.email.password");
if (encryptSensitiveData) {
assertThat(value.toString(), startsWith("::es_encrypted::"));
} else {
assertThat(value, is("::es_redacted::"));
}
// now we restart, to make sure the watches and their secrets are reloaded from the index properly
stopWatcher();
startWatcher();
// now lets execute the watch manually
final CountDownLatch latch = new CountDownLatch(1);
server.addListener(message -> {
assertThat(message.getSubject(), is("_subject"));
latch.countDown();
});
TriggerEvent triggerEvent = new ScheduleTriggerEvent(ZonedDateTime.now(ZoneOffset.UTC), ZonedDateTime.now(ZoneOffset.UTC));
ExecuteWatchResponse executeResponse = new ExecuteWatchRequestBuilder(client(), "_id").setRecordExecution(false)
.setTriggerEvent(triggerEvent)
.setActionMode("_all", ActionExecutionMode.FORCE_EXECUTE)
.get();
assertThat(executeResponse, notNullValue());
contentSource = executeResponse.getRecordSource();
value = contentSource.getValue("result.actions.0.status");
assertThat(value, is("success"));
if (latch.await(5, TimeUnit.SECONDS) == false) {
fail("waiting too long for the email to be sent");
}
}
}
| EmailSecretsIntegrationTests |
java | elastic__elasticsearch | x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/EqlStatsResponse.java | {
"start": 1880,
"end": 3067
} | class ____ extends BaseNodeResponse implements ToXContentObject {
private Counters stats;
public NodeStatsResponse(StreamInput in) throws IOException {
super(in);
if (in.readBoolean()) {
stats = new Counters(in);
}
}
public NodeStatsResponse(DiscoveryNode node) {
super(node);
}
public Counters getStats() {
return stats;
}
public void setStats(Counters stats) {
this.stats = stats;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(stats != null);
if (stats != null) {
stats.writeTo(out);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (stats != null && stats.hasCounters()) {
builder.field("stats", stats.toNestedMap());
}
builder.endObject();
return builder;
}
}
}
| NodeStatsResponse |
java | elastic__elasticsearch | x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ModelPlotsIT.java | {
"start": 1569,
"end": 7966
} | class ____ extends MlNativeAutodetectIntegTestCase {
private static final String DATA_INDEX = "model-plots-test-data";
@Before
public void setUpData() {
indicesAdmin().prepareCreate(DATA_INDEX).setMapping("time", "type=date,format=epoch_millis", "user", "type=keyword").get();
List<String> users = Arrays.asList("user_1", "user_2", "user_3");
// We are going to create data for last day
long nowMillis = System.currentTimeMillis();
int totalBuckets = 24;
BulkRequestBuilder bulkRequestBuilder = client().prepareBulk();
for (int bucket = 0; bucket < totalBuckets; bucket++) {
long timestamp = nowMillis - TimeValue.timeValueHours(totalBuckets - bucket).getMillis();
for (String user : users) {
IndexRequest indexRequest = new IndexRequest(DATA_INDEX);
indexRequest.source("time", timestamp, "user", user);
bulkRequestBuilder.add(indexRequest);
}
}
BulkResponse bulkResponse = bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
assertThat(bulkResponse.hasFailures(), is(false));
}
@After
public void tearDownData() {
client().admin().indices().prepareDelete(DATA_INDEX).get();
cleanUp();
}
public void testPartitionFieldWithoutTerms() throws Exception {
Job.Builder job = jobWithPartitionUser("model-plots-it-test-partition-field-without-terms");
job.setModelPlotConfig(new ModelPlotConfig());
putJob(job);
String datafeedId = job.getId() + "-feed";
DatafeedConfig datafeed = newDatafeed(datafeedId, job.getId());
putDatafeed(datafeed);
openJob(job.getId());
startDatafeed(datafeedId, 0, System.currentTimeMillis());
waitUntilJobIsClosed(job.getId());
// As the initial time is random, there's a chance the first record is
// aligned on a bucket start. Thus we check the buckets are in [23, 24]
assertThat(getBuckets(job.getId()).size(), greaterThanOrEqualTo(23));
assertThat(getBuckets(job.getId()).size(), lessThanOrEqualTo(24));
Set<String> modelPlotTerms = modelPlotTerms(job.getId(), "partition_field_value");
assertThat(modelPlotTerms, containsInAnyOrder("user_1", "user_2", "user_3"));
}
public void testPartitionFieldWithTerms() throws Exception {
Job.Builder job = jobWithPartitionUser("model-plots-it-test-partition-field-with-terms");
job.setModelPlotConfig(new ModelPlotConfig(true, "user_2,user_3", false));
putJob(job);
String datafeedId = job.getId() + "-feed";
DatafeedConfig datafeed = newDatafeed(datafeedId, job.getId());
putDatafeed(datafeed);
openJob(job.getId());
startDatafeed(datafeedId, 0, System.currentTimeMillis());
waitUntilJobIsClosed(job.getId());
// As the initial time is random, there's a chance the first record is
// aligned on a bucket start. Thus we check the buckets are in [23, 24]
assertThat(getBuckets(job.getId()).size(), greaterThanOrEqualTo(23));
assertThat(getBuckets(job.getId()).size(), lessThanOrEqualTo(24));
Set<String> modelPlotTerms = modelPlotTerms(job.getId(), "partition_field_value");
assertThat(modelPlotTerms, containsInAnyOrder("user_2", "user_3"));
}
public void testByFieldWithTerms() throws Exception {
Job.Builder job = jobWithByUser("model-plots-it-test-by-field-with-terms");
job.setModelPlotConfig(new ModelPlotConfig(true, "user_2,user_3", false));
putJob(job);
String datafeedId = job.getId() + "-feed";
DatafeedConfig datafeed = newDatafeed(datafeedId, job.getId());
putDatafeed(datafeed);
openJob(job.getId());
startDatafeed(datafeedId, 0, System.currentTimeMillis());
waitUntilJobIsClosed(job.getId());
// As the initial time is random, there's a chance the first record is
// aligned on a bucket start. Thus we check the buckets are in [23, 24]
assertThat(getBuckets(job.getId()).size(), greaterThanOrEqualTo(23));
assertThat(getBuckets(job.getId()).size(), lessThanOrEqualTo(24));
Set<String> modelPlotTerms = modelPlotTerms(job.getId(), "by_field_value");
assertThat(modelPlotTerms, containsInAnyOrder("user_2", "user_3"));
}
private static Job.Builder jobWithPartitionUser(String id) {
Detector.Builder detector = new Detector.Builder();
detector.setFunction("count");
detector.setPartitionFieldName("user");
return newJobBuilder(id, detector.build());
}
private static Job.Builder jobWithByUser(String id) {
Detector.Builder detector = new Detector.Builder();
detector.setFunction("count");
detector.setByFieldName("user");
return newJobBuilder(id, detector.build());
}
private static Job.Builder newJobBuilder(String id, Detector detector) {
AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Arrays.asList(detector));
analysisConfig.setBucketSpan(TimeValue.timeValueHours(1));
DataDescription.Builder dataDescription = new DataDescription.Builder();
dataDescription.setTimeField("time");
Job.Builder jobBuilder = new Job.Builder(id);
jobBuilder.setAnalysisConfig(analysisConfig);
jobBuilder.setDataDescription(dataDescription);
return jobBuilder;
}
private static DatafeedConfig newDatafeed(String datafeedId, String jobId) {
DatafeedConfig.Builder datafeedConfig = new DatafeedConfig.Builder(datafeedId, jobId);
datafeedConfig.setIndices(Arrays.asList(DATA_INDEX));
return datafeedConfig.build();
}
private Set<String> modelPlotTerms(String jobId, String fieldName) {
Set<String> set = new HashSet<>();
assertResponse(
prepareSearch(".ml-anomalies-" + jobId).setQuery(QueryBuilders.termQuery("result_type", "model_plot"))
.addAggregation(AggregationBuilders.terms("model_plot_terms").field(fieldName)),
searchResponse -> ((Terms) searchResponse.getAggregations().get("model_plot_terms")).getBuckets()
.forEach(bucket -> set.add(bucket.getKeyAsString()))
);
return set;
}
}
| ModelPlotsIT |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/columnar/vector/LongColumnVector.java | {
"start": 947,
"end": 1024
} | interface ____ extends ColumnVector {
long getLong(int i);
}
| LongColumnVector |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/calcite/rex/RexUtil.java | {
"start": 96102,
"end": 97210
} | class ____ extends RexVisitorImpl<Void> {
private int limit = -1;
private final RelDataType inputRowType;
ForwardRefFinder(RelDataType inputRowType) {
super(true);
this.inputRowType = inputRowType;
}
@Override
public Void visitInputRef(RexInputRef inputRef) {
super.visitInputRef(inputRef);
if (inputRef.getIndex() >= inputRowType.getFieldCount()) {
throw new IllegalForwardRefException();
}
return null;
}
@Override
public Void visitLocalRef(RexLocalRef inputRef) {
super.visitLocalRef(inputRef);
if (inputRef.getIndex() >= limit) {
throw new IllegalForwardRefException();
}
return null;
}
public void setLimit(int limit) {
this.limit = limit;
}
/**
* Thrown to abort a visit when we find an illegal forward reference. It changes control
* flow but is not considered an error.
*/
static | ForwardRefFinder |
java | mockito__mockito | mockito-extensions/mockito-errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveTypeTest.java | {
"start": 3036,
"end": 3477
} | class ____ {",
" public void test() {",
" Foo foo = mock(Foo.class);",
" when(foo.run(any(String.class))).thenReturn(5);",
" when(foo.runWithInt(anyInt())).thenReturn(5);",
" when(foo.runWithBoth(any(String.class), anyInt())).thenReturn(5);",
" }",
" static | Test |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DynamicRouterEndpointBuilderFactory.java | {
"start": 1515,
"end": 1653
} | interface ____ {
/**
* Builder for endpoint for the Dynamic Router component.
*/
public | DynamicRouterEndpointBuilderFactory |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java | {
"start": 13393,
"end": 15474
} | class ____ {
private static final Method uniToPublisher = ClassUtils.getMethod(io.smallrye.mutiny.groups.UniConvert.class, "toPublisher");
@SuppressWarnings("unchecked")
void registerAdapters(ReactiveAdapterRegistry registry) {
ReactiveTypeDescriptor uniDesc = ReactiveTypeDescriptor.singleOptionalValue(
io.smallrye.mutiny.Uni.class,
() -> io.smallrye.mutiny.Uni.createFrom().nothing());
ReactiveTypeDescriptor multiDesc = ReactiveTypeDescriptor.multiValue(
io.smallrye.mutiny.Multi.class,
() -> io.smallrye.mutiny.Multi.createFrom().empty());
if (Flow.Publisher.class.isAssignableFrom(uniToPublisher.getReturnType())) {
// Mutiny 2 based on Flow.Publisher
Method uniPublisher = ClassUtils.getMethod(
io.smallrye.mutiny.groups.UniCreate.class, "publisher", Flow.Publisher.class);
Method multiPublisher = ClassUtils.getMethod(
io.smallrye.mutiny.groups.MultiCreate.class, "publisher", Flow.Publisher.class);
registry.registerReactiveType(uniDesc,
uni -> FlowAdapters.toPublisher((Flow.Publisher<Object>)
Objects.requireNonNull(ReflectionUtils.invokeMethod(uniToPublisher, ((Uni<?>) uni).convert()))),
publisher -> Objects.requireNonNull(ReflectionUtils.invokeMethod(uniPublisher, Uni.createFrom(),
FlowAdapters.toFlowPublisher(publisher))));
registry.registerReactiveType(multiDesc,
multi -> FlowAdapters.toPublisher((Flow.Publisher<Object>) multi),
publisher -> Objects.requireNonNull(ReflectionUtils.invokeMethod(multiPublisher, Multi.createFrom(),
FlowAdapters.toFlowPublisher(publisher))));
}
else {
// Mutiny 1 based on Reactive Streams
registry.registerReactiveType(uniDesc,
uni -> ((io.smallrye.mutiny.Uni<?>) uni).convert().toPublisher(),
publisher -> io.smallrye.mutiny.Uni.createFrom().publisher(publisher));
registry.registerReactiveType(multiDesc,
multi -> (io.smallrye.mutiny.Multi<?>) multi,
publisher -> io.smallrye.mutiny.Multi.createFrom().publisher(publisher));
}
}
}
private static | MutinyRegistrar |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elastic/ccm/CCMFeatureFlag.java | {
"start": 377,
"end": 788
} | class ____ {
/**
* {@link org.elasticsearch.xpack.inference.services.custom.CustomService} feature flag. When the feature is complete,
* this flag will be removed.
* Enable feature via JVM option: `-Des.inference_api_ccm_feature_flag_enabled=true`.
*/
public static final FeatureFlag FEATURE_FLAG = new FeatureFlag("inference_api_ccm");
private CCMFeatureFlag() {}
}
| CCMFeatureFlag |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/visitors/data/Sort.java | {
"start": 6034,
"end": 6659
} | enum ____ {
ASC, DESC
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return ignoreCase == order.ignoreCase &&
property.equals(order.property) &&
direction == order.direction;
}
@Override
public int hashCode() {
return Objects.hash(property, direction, ignoreCase);
}
}
}
| Direction |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java | {
"start": 2680,
"end": 2799
} | class ____ {
@Bean
TestBean y() {
return new TestBean();
}
}
@Configuration
@Import({Z1.class, Z2.class})
| Y |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/spi/BytecodeProvider.java | {
"start": 1313,
"end": 2004
} | class ____ be reflected upon.
* @param getterNames Names of all property getters to be accessed via reflection.
* @param setterNames Names of all property setters to be accessed via reflection.
* @param types The types of all properties to be accessed.
* @return The reflection optimization delegate.
* @deprecated Use {@link #getReflectionOptimizer(Class, Map)} insstead
*/
@Deprecated(forRemoval = true)
ReflectionOptimizer getReflectionOptimizer(Class clazz, String[] getterNames, String[] setterNames, Class[] types);
/**
* Retrieve the ReflectionOptimizer delegate for this provider
* capable of generating reflection optimization components.
*
* @param clazz The | to |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/type/NestedTypes1604Test.java | {
"start": 949,
"end": 1135
} | class ____<T> extends Data<List<T>> {
public DataList(List<T> data) {
super(data);
}
}
// And then add one level between types
public static | DataList |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/MountSnapshotStepTests.java | {
"start": 1580,
"end": 28584
} | class ____ extends AbstractStepTestCase<MountSnapshotStep> {
private static final String RESTORED_INDEX_PREFIX = "restored-";
@Override
public MountSnapshotStep createRandomInstance() {
StepKey stepKey = randomStepKey();
StepKey nextStepKey = randomStepKey();
String restoredIndexPrefix = randomAlphaOfLength(10);
MountSearchableSnapshotRequest.Storage storage = randomStorageType();
Integer totalShardsPerNode = randomTotalShardsPerNode(true);
return new MountSnapshotStep(stepKey, nextStepKey, client, restoredIndexPrefix, storage, totalShardsPerNode, 0);
}
public static MountSearchableSnapshotRequest.Storage randomStorageType() {
if (randomBoolean()) {
return MountSearchableSnapshotRequest.Storage.FULL_COPY;
} else {
return MountSearchableSnapshotRequest.Storage.SHARED_CACHE;
}
}
@Override
protected MountSnapshotStep copyInstance(MountSnapshotStep instance) {
return new MountSnapshotStep(
instance.getKey(),
instance.getNextStepKey(),
instance.getClientWithoutProject(),
instance.getRestoredIndexPrefix(),
instance.getStorage(),
instance.getTotalShardsPerNode(),
instance.getReplicas()
);
}
@Override
public MountSnapshotStep mutateInstance(MountSnapshotStep instance) {
StepKey key = instance.getKey();
StepKey nextKey = instance.getNextStepKey();
String restoredIndexPrefix = instance.getRestoredIndexPrefix();
MountSearchableSnapshotRequest.Storage storage = instance.getStorage();
Integer totalShardsPerNode = instance.getTotalShardsPerNode();
int replicas = instance.getReplicas();
switch (between(0, 5)) {
case 0:
key = new StepKey(key.phase(), key.action(), key.name() + randomAlphaOfLength(5));
break;
case 1:
nextKey = new StepKey(nextKey.phase(), nextKey.action(), nextKey.name() + randomAlphaOfLength(5));
break;
case 2:
restoredIndexPrefix = randomValueOtherThan(restoredIndexPrefix, () -> randomAlphaOfLengthBetween(1, 10));
break;
case 3:
if (storage == MountSearchableSnapshotRequest.Storage.FULL_COPY) {
storage = MountSearchableSnapshotRequest.Storage.SHARED_CACHE;
} else if (storage == MountSearchableSnapshotRequest.Storage.SHARED_CACHE) {
storage = MountSearchableSnapshotRequest.Storage.FULL_COPY;
} else {
throw new AssertionError("unknown storage type: " + storage);
}
break;
case 4:
totalShardsPerNode = totalShardsPerNode == null ? 1 : totalShardsPerNode + randomIntBetween(1, 100);
break;
case 5:
replicas = replicas == 0 ? 1 : 0; // swap between 0 and 1
break;
default:
throw new AssertionError("Illegal randomisation branch");
}
return new MountSnapshotStep(
key,
nextKey,
instance.getClientWithoutProject(),
restoredIndexPrefix,
storage,
totalShardsPerNode,
replicas
);
}
public void testCreateWithInvalidTotalShardsPerNode() throws Exception {
int invalidTotalShardsPerNode = randomIntBetween(-100, 0);
IllegalArgumentException exception = expectThrows(
IllegalArgumentException.class,
() -> new MountSnapshotStep(
randomStepKey(),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
invalidTotalShardsPerNode,
0
)
);
assertEquals("[total_shards_per_node] must be >= 1", exception.getMessage());
}
public void testPerformActionFailure() {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
{
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
MountSnapshotStep mountSnapshotStep = createRandomInstance();
Exception e = expectThrows(
IllegalStateException.class,
() -> performActionAndWait(mountSnapshotStep, indexMetadata, state, null)
);
assertThat(
e.getMessage(),
is("snapshot repository is not present for policy [" + policyName + "] and index [" + indexName + "]")
);
}
{
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
Map<String, String> ilmCustom = new HashMap<>();
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
indexMetadataBuilder.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom);
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
MountSnapshotStep mountSnapshotStep = createRandomInstance();
Exception e = expectThrows(
IllegalStateException.class,
() -> performActionAndWait(mountSnapshotStep, indexMetadata, state, null)
);
assertThat(e.getMessage(), is("snapshot name was not generated for policy [" + policyName + "] and index [" + indexName + "]"));
}
}
public void testPerformAction() throws Exception {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
try (var threadPool = createThreadPool()) {
final var client = getRestoreSnapshotRequestAssertingClient(
threadPool,
repository,
snapshotName,
indexName,
RESTORED_INDEX_PREFIX,
indexName,
new String[] { LifecycleSettings.LIFECYCLE_NAME },
null,
0
);
MountSnapshotStep step = new MountSnapshotStep(
randomStepKey(),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
null,
0
);
performActionAndWait(step, indexMetadata, state, null);
}
}
public void testResponseStatusHandling() throws Exception {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
{
RestoreSnapshotResponse responseWithOKStatus = new RestoreSnapshotResponse(new RestoreInfo("test", List.of(), 1, 1));
try (var threadPool = createThreadPool()) {
final var clientPropagatingOKResponse = getClientTriggeringResponse(threadPool, responseWithOKStatus);
MountSnapshotStep step = new MountSnapshotStep(
randomStepKey(),
randomStepKey(),
clientPropagatingOKResponse,
RESTORED_INDEX_PREFIX,
randomStorageType(),
null,
0
);
performActionAndWait(step, indexMetadata, state, null);
}
}
{
RestoreSnapshotResponse responseWithACCEPTEDStatus = new RestoreSnapshotResponse((RestoreInfo) null);
try (var threadPool = createThreadPool()) {
final var clientPropagatingACCEPTEDResponse = getClientTriggeringResponse(threadPool, responseWithACCEPTEDStatus);
MountSnapshotStep step = new MountSnapshotStep(
randomStepKey(),
randomStepKey(),
clientPropagatingACCEPTEDResponse,
RESTORED_INDEX_PREFIX,
randomStorageType(),
null,
0
);
performActionAndWait(step, indexMetadata, state, null);
}
}
}
public void testBestEffortNameResolution() {
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("potato"), equalTo("potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("restored-potato"), equalTo("potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("partial-potato"), equalTo("potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("partial-restored-potato"), equalTo("potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("restored-partial-potato"), equalTo("partial-potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("my-restored-potato"), equalTo("my-restored-potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("my-partial-potato"), equalTo("my-partial-potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("my-partial-restored-potato"), equalTo("my-partial-restored-potato"));
assertThat(MountSnapshotStep.bestEffortIndexNameResolution("my-restored-partial-potato"), equalTo("my-restored-partial-potato"));
}
public void testMountWithNoPrefix() throws Exception {
doTestMountWithoutSnapshotIndexNameInState("");
}
public void testMountWithRestorePrefix() throws Exception {
doTestMountWithoutSnapshotIndexNameInState(SearchableSnapshotAction.FULL_RESTORED_INDEX_PREFIX);
}
public void testMountWithPartialPrefix() throws Exception {
doTestMountWithoutSnapshotIndexNameInState(SearchableSnapshotAction.PARTIAL_RESTORED_INDEX_PREFIX);
}
public void testMountWithPartialAndRestoredPrefix() throws Exception {
doTestMountWithoutSnapshotIndexNameInState(
SearchableSnapshotAction.PARTIAL_RESTORED_INDEX_PREFIX + SearchableSnapshotAction.FULL_RESTORED_INDEX_PREFIX
);
}
private void doTestMountWithoutSnapshotIndexNameInState(String prefix) throws Exception {
String indexNameSnippet = randomAlphaOfLength(10);
String indexName = prefix + indexNameSnippet;
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
try (var threadPool = createThreadPool()) {
final var client = getRestoreSnapshotRequestAssertingClient(
threadPool,
repository,
snapshotName,
indexName,
RESTORED_INDEX_PREFIX,
indexNameSnippet,
new String[] { LifecycleSettings.LIFECYCLE_NAME },
null,
0
);
MountSnapshotStep step = new MountSnapshotStep(
randomStepKey(),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
null,
0
);
performActionAndWait(step, indexMetadata, state, null);
}
}
public void testIgnoreTotalShardsPerNodeInFrozenPhase() throws Exception {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
try (var threadPool = createThreadPool()) {
final var client = getRestoreSnapshotRequestAssertingClient(
threadPool,
repository,
snapshotName,
indexName,
RESTORED_INDEX_PREFIX,
indexName,
new String[] {
LifecycleSettings.LIFECYCLE_NAME,
ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey() },
null,
0
);
MountSnapshotStep step = new MountSnapshotStep(
new StepKey(TimeseriesLifecycleType.FROZEN_PHASE, randomAlphaOfLength(10), randomAlphaOfLength(10)),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
null,
0
);
performActionAndWait(step, indexMetadata, state, null);
}
}
public void testDoNotIgnorePropagatedTotalShardsPerNodeInColdPhase() throws Exception {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
try (var threadPool = createThreadPool()) {
final var client = getRestoreSnapshotRequestAssertingClient(
threadPool,
repository,
snapshotName,
indexName,
RESTORED_INDEX_PREFIX,
indexName,
new String[] { LifecycleSettings.LIFECYCLE_NAME },
null,
0
);
MountSnapshotStep step = new MountSnapshotStep(
new StepKey(TimeseriesLifecycleType.COLD_PHASE, randomAlphaOfLength(10), randomAlphaOfLength(10)),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
null,
0
);
performActionAndWait(step, indexMetadata, state, null);
}
}
public void testDoNotIgnoreTotalShardsPerNodeAndReplicasIfSetInFrozenPhase() throws Exception {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
final Integer totalShardsPerNode = randomTotalShardsPerNode(false);
final int replicas = randomIntBetween(1, 5);
try (var threadPool = createThreadPool()) {
final var client = getRestoreSnapshotRequestAssertingClient(
threadPool,
repository,
snapshotName,
indexName,
RESTORED_INDEX_PREFIX,
indexName,
new String[] { LifecycleSettings.LIFECYCLE_NAME },
totalShardsPerNode,
replicas
);
MountSnapshotStep step = new MountSnapshotStep(
new StepKey(TimeseriesLifecycleType.FROZEN_PHASE, randomAlphaOfLength(10), randomAlphaOfLength(10)),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
totalShardsPerNode,
replicas
);
performActionAndWait(step, indexMetadata, state, null);
}
}
public void testDoNotIgnoreTotalShardsPerNodeAndReplicasIfSetInCold() throws Exception {
String indexName = randomAlphaOfLength(10);
String policyName = "test-ilm-policy";
Map<String, String> ilmCustom = new HashMap<>();
String snapshotName = indexName + "-" + policyName;
ilmCustom.put("snapshot_name", snapshotName);
String repository = "repository";
ilmCustom.put("snapshot_repository", repository);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(indexName)
.settings(settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_NAME, policyName))
.putCustom(LifecycleExecutionState.ILM_CUSTOM_METADATA_KEY, ilmCustom)
.numberOfShards(randomIntBetween(1, 5))
.numberOfReplicas(randomIntBetween(0, 5));
IndexMetadata indexMetadata = indexMetadataBuilder.build();
ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomProjectIdOrDefault()).put(indexMetadata, true));
final Integer totalShardsPerNode = randomTotalShardsPerNode(false);
final int replicas = randomIntBetween(1, 5);
try (var threadPool = createThreadPool()) {
final var client = getRestoreSnapshotRequestAssertingClient(
threadPool,
repository,
snapshotName,
indexName,
RESTORED_INDEX_PREFIX,
indexName,
new String[] { LifecycleSettings.LIFECYCLE_NAME },
totalShardsPerNode,
replicas
);
MountSnapshotStep step = new MountSnapshotStep(
new StepKey(TimeseriesLifecycleType.COLD_PHASE, randomAlphaOfLength(10), randomAlphaOfLength(10)),
randomStepKey(),
client,
RESTORED_INDEX_PREFIX,
randomStorageType(),
totalShardsPerNode,
replicas
);
performActionAndWait(step, indexMetadata, state, null);
}
}
@SuppressWarnings("unchecked")
private NoOpClient getClientTriggeringResponse(ThreadPool threadPool, RestoreSnapshotResponse response) {
return new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())) {
@Override
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
listener.onResponse((Response) response);
}
};
}
@SuppressWarnings("unchecked")
private NoOpClient getRestoreSnapshotRequestAssertingClient(
ThreadPool threadPool,
String expectedRepoName,
String expectedSnapshotName,
String indexName,
String restoredIndexPrefix,
String expectedSnapshotIndexName,
String[] expectedIgnoredIndexSettings,
@Nullable Integer totalShardsPerNode,
int replicas
) {
return new NoOpClient(threadPool, TestProjectResolvers.usingRequestHeader(threadPool.getThreadContext())) {
@Override
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
assertThat(action.name(), is(MountSearchableSnapshotAction.NAME));
assertTrue(request instanceof MountSearchableSnapshotRequest);
MountSearchableSnapshotRequest mountSearchableSnapshotRequest = (MountSearchableSnapshotRequest) request;
assertThat(mountSearchableSnapshotRequest.repositoryName(), is(expectedRepoName));
assertThat(mountSearchableSnapshotRequest.snapshotName(), is(expectedSnapshotName));
assertThat(
"another ILM step will wait for the restore to complete. the " + MountSnapshotStep.NAME + " step should not",
mountSearchableSnapshotRequest.waitForCompletion(),
is(false)
);
assertThat(mountSearchableSnapshotRequest.ignoreIndexSettings(), is(expectedIgnoredIndexSettings));
assertThat(mountSearchableSnapshotRequest.mountedIndexName(), is(restoredIndexPrefix + indexName));
assertThat(mountSearchableSnapshotRequest.snapshotIndexName(), is(expectedSnapshotIndexName));
if (totalShardsPerNode != null) {
Integer totalShardsPerNodeSettingValue = ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.get(
mountSearchableSnapshotRequest.indexSettings()
);
assertThat(totalShardsPerNodeSettingValue, is(totalShardsPerNode));
} else {
assertThat(
mountSearchableSnapshotRequest.indexSettings()
.hasValue(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey()),
is(false)
);
}
if (replicas > 0) {
Integer numberOfReplicasSettingValue = IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.get(
mountSearchableSnapshotRequest.indexSettings()
);
assertThat(numberOfReplicasSettingValue, is(replicas));
} else {
assertThat(
mountSearchableSnapshotRequest.indexSettings().hasValue(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey()),
is(false)
);
}
// invoke the awaiting listener with a very generic 'response', just to fulfill the contract
listener.onResponse((Response) new RestoreSnapshotResponse((RestoreInfo) null));
}
};
}
private Integer randomTotalShardsPerNode(boolean nullable) {
Integer randomInt = randomIntBetween(1, 100);
Integer randomIntNullable = (randomBoolean() ? null : randomInt);
return nullable ? randomIntNullable : randomInt;
}
}
| MountSnapshotStepTests |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoBean.java | {
"start": 1721,
"end": 1863
} | class ____ any superclass or implemented interface
* in the type hierarchy above the test class.</li>
* <li>At the type level on an enclosing | or |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestPathData.java | {
"start": 1584,
"end": 9327
} | class ____ {
private static final String TEST_ROOT_DIR =
GenericTestUtils.getTestDir("testPD").getAbsolutePath();
protected Configuration conf;
protected FileSystem fs;
protected Path testDir;
@BeforeEach
public void initialize() throws Exception {
conf = new Configuration();
fs = FileSystem.getLocal(conf);
testDir = new Path(TEST_ROOT_DIR);
// don't want scheme on the path, just an absolute path
testDir = new Path(fs.makeQualified(testDir).toUri().getPath());
fs.mkdirs(testDir);
FileSystem.setDefaultUri(conf, fs.getUri());
fs.setWorkingDirectory(testDir);
fs.mkdirs(new Path("d1"));
fs.createNewFile(new Path("d1", "f1"));
fs.createNewFile(new Path("d1", "f1.1"));
fs.createNewFile(new Path("d1", "f2"));
fs.mkdirs(new Path("d2"));
fs.create(new Path("d2","f3"));
}
@AfterEach
public void cleanup() throws Exception {
fs.delete(testDir, true);
fs.close();
}
@Test
@Timeout(value = 30)
public void testWithDirStringAndConf() throws Exception {
String dirString = "d1";
PathData item = new PathData(dirString, conf);
checkPathData(dirString, item);
// properly implementing symlink support in various commands will require
// trailing slashes to be retained
dirString = "d1/";
item = new PathData(dirString, conf);
checkPathData(dirString, item);
}
@Test
@Timeout(value = 30)
public void testUnqualifiedUriContents() throws Exception {
String dirString = "d1";
PathData item = new PathData(dirString, conf);
PathData[] items = item.getDirectoryContents();
assertEquals(
sortedString("d1/f1", "d1/f1.1", "d1/f2"),
sortedString(items)
);
}
@Test
@Timeout(value = 30)
public void testQualifiedUriContents() throws Exception {
String dirString = fs.makeQualified(new Path("d1")).toString();
PathData item = new PathData(dirString, conf);
PathData[] items = item.getDirectoryContents();
assertEquals(
sortedString(dirString+"/f1", dirString+"/f1.1", dirString+"/f2"),
sortedString(items)
);
}
@Test
@Timeout(value = 30)
public void testCwdContents() throws Exception {
String dirString = Path.CUR_DIR;
PathData item = new PathData(dirString, conf);
PathData[] items = item.getDirectoryContents();
assertEquals(
sortedString("d1", "d2"),
sortedString(items)
);
}
@Test
@Timeout(value = 30)
public void testToFile() throws Exception {
PathData item = new PathData(".", conf);
assertEquals(new File(testDir.toString()), item.toFile());
item = new PathData("d1/f1", conf);
assertEquals(new File(testDir + "/d1/f1"), item.toFile());
item = new PathData(testDir + "/d1/f1", conf);
assertEquals(new File(testDir + "/d1/f1"), item.toFile());
}
@Test
@Timeout(value = 5)
public void testToFileRawWindowsPaths() throws Exception {
assumeWindows();
// Can we handle raw Windows paths? The files need not exist for
// these tests to succeed.
String[] winPaths = {
"n:\\",
"N:\\",
"N:\\foo",
"N:\\foo\\bar",
"N:/",
"N:/foo",
"N:/foo/bar"
};
PathData item;
for (String path : winPaths) {
item = new PathData(path, conf);
assertEquals(new File(path), item.toFile());
}
item = new PathData("foo\\bar", conf);
assertEquals(new File(testDir + "\\foo\\bar"), item.toFile());
}
@Test
@Timeout(value = 5)
public void testInvalidWindowsPath() throws Exception {
assumeWindows();
// Verify that the following invalid paths are rejected.
String [] winPaths = {
"N:\\foo/bar"
};
for (String path : winPaths) {
try {
PathData item = new PathData(path, conf);
fail("Did not throw for invalid path " + path);
} catch (IOException ioe) {
}
}
}
@Test
@Timeout(value = 30)
public void testAbsoluteGlob() throws Exception {
PathData[] items = PathData.expandAsGlob(testDir+"/d1/f1*", conf);
assertEquals(
sortedString(testDir+"/d1/f1", testDir+"/d1/f1.1"),
sortedString(items)
);
String absolutePathNoDriveLetter = testDir+"/d1/f1";
if (Shell.WINDOWS) {
// testDir is an absolute path with a drive letter on Windows, i.e.
// c:/some/path
// and for the test we want something like the following
// /some/path
absolutePathNoDriveLetter = absolutePathNoDriveLetter.substring(2);
}
items = PathData.expandAsGlob(absolutePathNoDriveLetter, conf);
assertEquals(
sortedString(absolutePathNoDriveLetter),
sortedString(items)
);
items = PathData.expandAsGlob(".", conf);
assertEquals(
sortedString("."),
sortedString(items)
);
}
@Test
@Timeout(value = 30)
public void testRelativeGlob() throws Exception {
PathData[] items = PathData.expandAsGlob("d1/f1*", conf);
assertEquals(
sortedString("d1/f1", "d1/f1.1"),
sortedString(items)
);
}
@Test
@Timeout(value = 30)
public void testRelativeGlobBack() throws Exception {
fs.setWorkingDirectory(new Path("d1"));
PathData[] items = PathData.expandAsGlob("../d2/*", conf);
assertEquals(
sortedString("../d2/f3"),
sortedString(items)
);
}
@Test
public void testGlobThrowsExceptionForUnreadableDir() throws Exception {
Path obscuredDir = new Path("foo");
Path subDir = new Path(obscuredDir, "bar"); //so foo is non-empty
fs.mkdirs(subDir);
fs.setPermission(obscuredDir, new FsPermission((short)0)); //no access
try {
PathData.expandAsGlob("foo/*", conf);
fail("Should throw IOException");
} catch (IOException ioe) {
// expected
} finally {
// make sure the test directory can be deleted
fs.setPermission(obscuredDir, new FsPermission((short)0755)); //default
}
}
@Test
@Timeout(value = 30)
public void testWithStringAndConfForBuggyPath() throws Exception {
String dirString = "file:///tmp";
Path tmpDir = new Path(dirString);
PathData item = new PathData(dirString, conf);
// this may fail some day if Path is fixed to not crunch the uri
// if the authority is null, however we need to test that the PathData
// toString() returns the given string, while Path toString() does
// the crunching
assertEquals("file:/tmp", tmpDir.toString());
checkPathData(dirString, item);
}
public void checkPathData(String dirString, PathData item) throws Exception {
assertEquals(fs, item.fs, "checking fs");
assertEquals(dirString, item.toString(), "checking string");
assertEquals(fs.makeQualified(new Path(item.toString())), item.path, "checking path");
assertTrue(item.stat != null, "checking exist");
assertTrue(item.stat.isDirectory(), "checking isDir");
}
/* junit does a lousy job of comparing arrays
* if the array lengths differ, it just says that w/o showing contents
* this sorts the paths, and builds a string of "i:<value>, ..." suitable
* for a string compare
*/
private static String sortedString(Object ... list) {
String[] strings = new String[list.length];
for (int i=0; i < list.length; i++) {
strings[i] = String.valueOf(list[i]);
}
Arrays.sort(strings);
StringBuilder result = new StringBuilder();
for (int i=0; i < strings.length; i++) {
if (result.length() > 0) {
result.append(", ");
}
result.append(i+":<"+strings[i]+">");
}
return result.toString();
}
private static String sortedString(PathData ... items) {
return sortedString((Object[])items);
}
}
| TestPathData |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopIntAggregator.java | {
"start": 3918,
"end": 4948
} | class ____ implements AggregatorState {
private final GroupingState internalState;
private SingleState(BigArrays bigArrays, int limit, boolean ascending) {
this.internalState = new GroupingState(bigArrays, limit, ascending);
}
public void add(int value) {
internalState.add(0, value);
}
@Override
public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) {
try (var intValues = driverContext.blockFactory().newConstantIntVector(0, 1)) {
internalState.toIntermediate(blocks, offset, intValues, driverContext);
}
}
Block toBlock(BlockFactory blockFactory) {
try (var intValues = blockFactory.newConstantIntVector(0, 1)) {
return internalState.toBlock(blockFactory, intValues);
}
}
@Override
public void close() {
Releasables.closeExpectNoException(internalState);
}
}
}
| SingleState |
java | apache__kafka | trogdor/src/main/java/org/apache/kafka/trogdor/workload/ConnectionStressSpec.java | {
"start": 1303,
"end": 1627
} | class ____ extends TaskSpec {
private final List<String> clientNodes;
private final String bootstrapServers;
private final Map<String, String> commonClientConf;
private final int targetConnectionsPerSec;
private final int numThreads;
private final ConnectionStressAction action;
| ConnectionStressSpec |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/util/RecyclerPool.java | {
"start": 1400,
"end": 5015
} | interface ____<P extends WithPool<P>> {
/**
* Method to call to add link from pooled item back to pool
* that handles it
*
* @param pool Pool that "owns" pooled item
*
* @return This item (for call chaining)
*/
P withPool(RecyclerPool<P> pool);
/**
* Method called when this item is to be released back to the
* pool that owns it (if any)
*/
void releaseToPool();
}
/**
* Method called to acquire a Pooled value from this pool
* AND make sure it is linked back to this
* {@link RecyclerPool} as necessary for it to be
* released (see {@link #releasePooled}) later after usage ends.
* Actual acquisition is done by a call to {@link #acquirePooled()}.
*<p>
* Default implementation calls {@link #acquirePooled()} followed by
* a call to {@link WithPool#withPool}.
*
* @return Pooled instance for caller to use; caller expected
* to call {@link #releasePooled} after it is done using instance.
*/
default P acquireAndLinkPooled() {
return acquirePooled().withPool(this);
}
/**
* Method for sub-classes to implement for actual acquire logic; called
* by {@link #acquireAndLinkPooled()}.
*
* @return Instance acquired (pooled or just constructed)
*/
P acquirePooled();
/**
* Method that should be called when previously acquired (see {@link #acquireAndLinkPooled})
* pooled value that is no longer needed; this lets pool to take ownership
* for possible reuse.
*
* @param pooled Pooled instance to release back to pool
*/
void releasePooled(P pooled);
/**
* Optional method that may allow dropping of all pooled Objects; mostly
* useful for unbounded pool implementations that may retain significant
* memory and that may then be cleared regularly.
*
* @since 2.17
*
* @return {@code true} If pool supports operation and dropped all pooled
* Objects; {@code false} otherwise.
*/
default boolean clear() {
return false;
}
/**
* Diagnostic method for obtaining an estimate of number of pooled items
* this pool contains, available for recycling.
* Note that in addition to this information possibly not being available
* (denoted by return value of {@code -1}) even when available this may be
* just an approximation.
*<p>
* Default method implementation simply returns {@code -1} and is meant to be
* overridden by concrete sub-classes.
*
* @return Number of pooled entries available from this pool, if available;
* {@code -1} if not.
*
* @since 2.18
*/
default int pooledCount() {
return -1;
}
/*
/**********************************************************************
/* Partial/base RecyclerPool implementations
/**********************************************************************
*/
/**
* Default {@link RecyclerPool} implementation that uses
* {@link ThreadLocal} for recycling instances.
* Instances are stored using {@link java.lang.ref.SoftReference}s so that
* they may be Garbage Collected as needed by JVM.
*<p>
* Note that this implementation may not work well on platforms where
* {@link java.lang.ref.SoftReference}s are not well supported (like
* Android), or on platforms where {@link java.lang.Thread}s are not
* long-living or reused (like Project Loom).
*/
abstract | WithPool |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FilterByFilterAggregator.java | {
"start": 6149,
"end": 12939
} | class ____ implements CheckedFunction<AggregatorFactories, FilterByFilterAggregator, IOException> {
private FilterByFilterAggregator agg;
@Override
public FilterByFilterAggregator apply(AggregatorFactories subAggregators) throws IOException {
agg = new FilterByFilterAggregator(
name,
subAggregators,
filters,
keyed,
keyedBucket,
aggCtx,
parent,
cardinality,
metadata
);
return agg;
}
}
AdapterBuild adapterBuild = new AdapterBuild();
T result = adapt(adapterBuild);
if (adapterBuild.agg.scoreMode().needsScores()) {
/*
* Filter by filter won't produce the correct results if the
* sub-aggregators need scores because we're not careful with how
* we merge filters. Right now we have to build the whole
* aggregation in order to know if it'll need scores or not.
* This means we'll build the *sub-aggs* too. Oh well.
*/
return null;
}
return result;
}
}
/**
* Count of segments with "live" docs. This is both deleted docs and
* docs covered by field level security.
*/
private int segmentsWithDeletedDocs;
/**
* Count of segments with documents have consult the {@code doc_count}
* field.
*/
private int segmentsWithDocCountField;
/**
* Count of segments this aggregator performed a document by document
* collection for. We have to collect when there are sub-aggregations
* and it disables some optimizations we can make while just counting.
*/
private int segmentsCollected;
/**
* Count of segments this aggregator counted. We can count when there
* aren't any sub-aggregators and we have some counting optimizations
* that don't apply to document by document collections.
* <p>
* But the "fallback" for counting when we don't have a fancy optimization
* is to perform document by document collection and increment a counter
* on each document. This fallback does not increment the
* {@link #segmentsCollected} counter and <strong>does</strong> increment
* the {@link #segmentsCounted} counter because those counters are to
* signal which operation we were allowed to perform. The filters
* themselves will have debugging counters measuring if they could
* perform the count from metadata or had to fall back.
*/
private int segmentsCounted;
/**
* Build the aggregation. Private to force callers to go through the
* {@link AdapterBuilder} which centralizes the logic to decide if this
* aggregator would be faster than the native implementation.
*/
private FilterByFilterAggregator(
String name,
AggregatorFactories factories,
List<QueryToFilterAdapter> filters,
boolean keyed,
boolean keyedBucket,
AggregationContext aggCtx,
Aggregator parent,
CardinalityUpperBound cardinality,
Map<String, Object> metadata
) throws IOException {
super(name, factories, filters, keyed, keyedBucket, null, aggCtx, parent, cardinality, metadata);
}
/**
* Instead of returning a {@link LeafBucketCollector} we do the
* collection ourselves by running the filters directly. This is safe
* because we only use this aggregator if there isn't a {@code parent}
* which would change how we collect buckets and because we take the
* top level query into account when building the filters.
*/
@Override
protected LeafBucketCollector getLeafCollector(AggregationExecutionContext aggCtx, LeafBucketCollector sub) throws IOException {
assert scoreMode().needsScores() == false;
if (QueryToFilterAdapter.matchesNoDocs(filters())) {
return LeafBucketCollector.NO_OP_COLLECTOR;
}
Bits live = aggCtx.getLeafReaderContext().reader().getLiveDocs();
if (live != null) {
segmentsWithDeletedDocs++;
}
if (false == docCountProvider.alwaysOne()) {
segmentsWithDocCountField++;
}
if (subAggregators.length == 0) {
// TOOD we'd be better off if we could do sub.isNoop() or something.
/*
* Without sub.isNoop we always end up in the `collectXXX` modes even if
* the sub-aggregators opt out of traditional collection.
*/
segmentsCounted++;
collectCount(aggCtx.getLeafReaderContext(), live);
} else {
segmentsCollected++;
collectSubs(aggCtx, live, sub);
}
return LeafBucketCollector.NO_OP_COLLECTOR;
}
/**
* Gather a count of the number of documents that match each filter
* without sending any documents to a sub-aggregator. This yields
* the correct response when there aren't any sub-aggregators or they
* all opt out of needing any sort of collection.
*/
private void collectCount(LeafReaderContext ctx, Bits live) throws IOException {
Counter counter = new Counter(docCountProvider);
for (int filterOrd = 0; filterOrd < filters().size(); filterOrd++) {
incrementBucketDocCount(filterOrd, filters().get(filterOrd).count(ctx, counter, live, this::checkCancelled));
}
}
/**
* Collect all documents that match all filters and send them to
* the sub-aggregators. This method is only required when there are
* sub-aggregators that haven't opted out of being collected.
* <p>
* This collects each filter one at a time, resetting the
* sub-aggregators between each filter as though they were hitting
* a fresh segment.
* <p>
* It's <strong>very</strong> tempting to try and collect the
* filters into blocks of matches and then reply the whole block
* into ascending order without the resetting. That'd probably
* work better if the disk was very, very slow and we didn't have
* any kind of disk caching. But with disk caching its about twice
* as fast to collect each filter one by one like this. And it uses
* less memory because there isn't a need to buffer a block of matches.
* And its a hell of a lot less code.
*/
private void collectSubs(AggregationExecutionContext aggCtx, Bits live, LeafBucketCollector sub) throws IOException {
| AdapterBuild |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/inject/lifecycle/beanwithprivatepostconstruct/B.java | {
"start": 793,
"end": 1216
} | class ____ {
boolean setupComplete = false;
boolean injectedFirst = false;
@Inject
protected A another;
private A a;
@Inject
public void setA(A a ) {
this.a = a;
}
public A getA() {
return a;
}
@PostConstruct
private void setup() {
if(a != null && another != null) {
injectedFirst = true;
}
setupComplete = true;
}
}
| B |
java | apache__camel | components/camel-servlet/src/test/java/org/apache/camel/component/servlet/rest/RestServletQueryParamUriTest.java | {
"start": 1183,
"end": 3064
} | class ____ extends ServletCamelRouterTestSupport {
@BindToRegistry("myBinding")
private ServletRestHttpBinding restHttpBinding = new ServletRestHttpBinding();
@Test
public void testQueryTrue() throws Exception {
WebRequest req = new GetMethodWebRequest(contextUrl + "/services/users/");
req.setParameter("auth", "secret");
WebResponse response = query(req, false);
assertEquals(200, response.getResponseCode());
assertEquals("secret;Donald Duck", response.getText());
}
@Test
public void testQueryFalse() throws Exception {
WebRequest req = new GetMethodWebRequest(contextUrl + "/services/users/");
WebResponse response = query(req, false);
// we do not know if the query was required, so we cannot validate this
assertEquals(200, response.getResponseCode());
assertEquals("null;Donald Duck", response.getText());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// configure to use servlet on localhost
restConfiguration().component("servlet").host("localhost").endpointProperty("httpBinding", "#myBinding")
.clientRequestValidation(true);
// use the rest DSL to define the rest services
rest()
.get("/users/?auth={myAuth}").to("direct:auth");
from("direct:auth")
.to("mock:input").process(exchange -> {
String auth = exchange.getIn().getHeader("auth", String.class);
exchange.getMessage().setBody(auth + ";Donald Duck");
});
}
};
}
}
| RestServletQueryParamUriTest |
java | apache__camel | components/camel-xmlsecurity/src/main/java/org/apache/camel/component/xmlsecurity/processor/XmlSignatureProcessor.java | {
"start": 1733,
"end": 6508
} | class ____ implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(XmlSignatureProcessor.class);
static {
try {
SantuarioUtil.initializeSantuario();
SantuarioUtil.addSantuarioJSR105Provider();
} catch (Exception t) {
// provider not in classpath, ignore and fall back to jre default
LOG.info("Cannot add the SantuarioJSR105Provider due to {0}, fall back to JRE default.", t);
}
}
protected final CamelContext context;
public XmlSignatureProcessor(CamelContext context) {
this.context = context;
}
public CamelContext getCamelContext() {
return context;
}
public abstract XmlSignatureConfiguration getConfiguration();
void setUriDereferencerAndBaseUri(XMLCryptoContext context) {
setUriDereferencer(context);
setBaseUri(context);
}
private void setUriDereferencer(XMLCryptoContext context) {
if (getConfiguration().getUriDereferencer() != null) {
context.setURIDereferencer(getConfiguration().getUriDereferencer());
LOG.debug("URI dereferencer set");
}
}
private void setBaseUri(XMLCryptoContext context) {
if (getConfiguration().getBaseUri() != null) {
context.setBaseURI(getConfiguration().getBaseUri());
LOG.debug("Base URI {} set", context.getBaseURI());
}
}
protected void setCryptoContextProperties(XMLCryptoContext cryptoContext) {
Map<String, ? extends Object> props = getConfiguration().getCryptoContextProperties();
if (props == null) {
return;
}
for (Map.Entry<String, ?> prop : props.entrySet()) {
Object val = prop.getValue();
cryptoContext.setProperty(prop.getKey(), val);
LOG.debug("Context property {} set to value {}", prop, val);
}
}
protected void clearMessageHeaders(Message message) {
if (getConfiguration().getClearHeaders() != null && getConfiguration().getClearHeaders()) {
Map<String, Object> headers = message.getHeaders();
for (Field f : XmlSignatureConstants.class.getFields()) {
String key = ObjectHelper.lookupConstantFieldValue(XmlSignatureConstants.class, f.getName());
if (!XmlSignatureConstants.CHARSET_NAME.equals(key)) {
// keep charset header
headers.remove(key);
}
}
}
}
protected Schema getSchema(Message message) throws SAXException, XmlSignatureException, IOException {
String schemaResourceUri = getSchemaResourceUri(message);
if (schemaResourceUri == null || schemaResourceUri.isEmpty()) {
return null;
}
InputStream is = ResourceHelper.resolveResourceAsInputStream(getCamelContext(),
schemaResourceUri);
if (is == null) {
throw new XmlSignatureException(
"XML Signature component is wrongly configured: No XML schema found for specified schema resource URI "
+ schemaResourceUri);
}
byte[] bytes;
try {
bytes = message.getExchange().getContext().getTypeConverter().convertTo(byte[].class, is);
} finally {
// and make sure to close the input stream after the schema has been loaded
IOHelper.close(is);
}
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
schemaFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
LOG.debug("Configuring SchemaFactory to not allow access to external DTD/Schema");
schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
schemaFactory.setResourceResolver(new DefaultLSResourceResolver(
getCamelContext(), getConfiguration()
.getSchemaResourceUri()));
LOG.debug("Instantiating schema for validation");
return schemaFactory.newSchema(new BytesSource(bytes));
}
protected String getSchemaResourceUri(Message message) {
String schemaResourceUri = message.getHeader(XmlSignatureConstants.HEADER_SCHEMA_RESOURCE_URI, String.class);
if (schemaResourceUri == null) {
schemaResourceUri = getConfiguration().getSchemaResourceUri();
}
LOG.debug("schema resource URI: {}", getConfiguration().getSchemaResourceUri());
return schemaResourceUri;
}
}
| XmlSignatureProcessor |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/lookup/TableKeyedAsyncWaitOperatorTest.java | {
"start": 23113,
"end": 25470
} | class ____ implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
StreamRecord<Integer> sr0 = (StreamRecord<Integer>) o1;
StreamRecord<Integer> sr1 = (StreamRecord<Integer>) o2;
if (sr0.getTimestamp() != sr1.getTimestamp()) {
return (int) (sr0.getTimestamp() - sr1.getTimestamp());
}
int comparison = sr0.getValue().compareTo(sr1.getValue());
if (comparison != 0) {
return comparison;
} else {
return sr0.getValue() - sr1.getValue();
}
}
}
private static <T> void assertWatermarkEquals(
String message, Queue<T> expected, Queue<T> actual) {
List<T> expectedList = new ArrayList<>(expected);
List<T> actualList = new ArrayList<>(actual);
Function<List<T>, Map<Integer, Watermark>> extractWatermarks =
list ->
IntStream.range(0, list.size())
.boxed()
.filter(i -> list.get(i) instanceof Watermark)
.collect(Collectors.toMap(i -> i, i -> (Watermark) list.get(i)));
Map<Integer, Watermark> expectedWatermarks = extractWatermarks.apply(expectedList);
Map<Integer, Watermark> actualWatermarks = extractWatermarks.apply(actualList);
assertThat(actualWatermarks).as(message).isEqualTo(expectedWatermarks);
}
private EpochManager<Integer> unwrapEpochManager(
KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Integer> testHarness) {
TableKeyedAsyncWaitOperator<Integer, Integer, Integer> operator =
(TableKeyedAsyncWaitOperator<Integer, Integer, Integer>) testHarness.getOperator();
TableAsyncExecutionController<Integer, Integer, Integer> asyncExecutionController =
operator.getAsyncExecutionController();
return asyncExecutionController.getEpochManager();
}
private Optional<Epoch<Integer>> unwrapEpoch(
KeyedOneInputStreamOperatorTestHarness<Integer, Integer, Integer> testHarness,
long targetEpochWatermark) {
return unwrapEpochManager(testHarness).getProperEpoch(new Watermark(targetEpochWatermark));
}
}
| StreamRecordComparator |
java | apache__hadoop | hadoop-common-project/hadoop-auth/src/main/java/org/apache/hadoop/security/authentication/client/AuthenticatedURL.java | {
"start": 8995,
"end": 9139
} | class ____ use when an {@link AuthenticatedURL} instance
* is created without specifying an authenticator.
*
* @return the authenticator | to |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoBuilderTest.java | {
"start": 5151,
"end": 6646
} | interface ____ {
MyAnnotationAllBuilder value(String x);
MyAnnotationAllBuilder id(int x);
MyAnnotationAllBuilder truthiness(Truthiness x);
MyAnnotation build();
}
static MyAnnotationAllBuilder myAnnotationAllBuilder() {
return new AutoBuilder_AutoBuilderTest_MyAnnotationAllBuilder();
}
@Test
public void simpleAutoAnnotation() {
// We haven't supplied a value for `truthiness`, so AutoBuilder should use the default one in
// the annotation.
MyAnnotation annotation1 = myAnnotationBuilder().value("foo").build();
assertThat(annotation1.value()).isEqualTo("foo");
assertThat(annotation1.id()).isEqualTo(MyAnnotation.DEFAULT_ID);
assertThat(annotation1.truthiness()).isEqualTo(MyAnnotation.DEFAULT_TRUTHINESS);
MyAnnotation annotation2 =
myAnnotationBuilder().value("bar").truthiness(Truthiness.TRUTHY).build();
assertThat(annotation2.value()).isEqualTo("bar");
assertThat(annotation2.id()).isEqualTo(MyAnnotation.DEFAULT_ID);
assertThat(annotation2.truthiness()).isEqualTo(Truthiness.TRUTHY);
MyAnnotation annotation3 = myAnnotationAllBuilder().value("foo").build();
MyAnnotation annotation4 =
myAnnotationAllBuilder()
.value("foo")
.id(MyAnnotation.DEFAULT_ID)
.truthiness(MyAnnotation.DEFAULT_TRUTHINESS)
.build();
assertThat(annotation3).isEqualTo(annotation4);
}
@AutoBuilder(ofClass = MyAnnotation.class)
public | MyAnnotationAllBuilder |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/concurrent/AsyncGet.java | {
"start": 2176,
"end": 2667
} | class ____ {
/**
* Use {@link #get(long, TimeUnit)} timeout parameters to wait.
* @param obj object.
* @param timeout timeout.
* @param unit unit.
* @throws InterruptedException if the thread is interrupted.
*/
public static void wait(Object obj, long timeout, TimeUnit unit)
throws InterruptedException {
if (timeout < 0) {
obj.wait();
} else if (timeout > 0) {
obj.wait(unit.toMillis(timeout));
}
}
}
}
| Util |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/webapp/dao/ContainerLogsInfo.java | {
"start": 1793,
"end": 3437
} | class ____ {
@XmlElement(name = "containerLogInfo")
protected List<ContainerLogFileInfo> containerLogsInfo;
@XmlElement(name = "logAggregationType")
protected String logType;
@XmlElement(name = "containerId")
protected String containerId;
@XmlElement(name = "nodeId")
protected String nodeId;
//JAXB needs this
public ContainerLogsInfo() {}
public ContainerLogsInfo(ContainerLogMeta logMeta,
ContainerLogAggregationType logType) {
this.containerLogsInfo = new ArrayList<>(logMeta.getContainerLogMeta());
this.logType = logType.toString();
this.containerId = logMeta.getContainerId();
this.nodeId = logMeta.getNodeId();
}
@VisibleForTesting
public ContainerLogsInfo(ContainerLogMeta logMeta, String logType) {
this.containerLogsInfo = new ArrayList<>(logMeta.getContainerLogMeta());
this.logType = logType;
this.containerId = logMeta.getContainerId();
this.nodeId = logMeta.getNodeId();
}
public List<ContainerLogFileInfo> getContainerLogsInfo() {
return this.containerLogsInfo;
}
public String getLogType() {
return this.logType;
}
public String getContainerId() {
return this.containerId;
}
public String getNodeId() {
return this.nodeId;
}
public void setContainerLogsInfo(List<ContainerLogFileInfo> containerLogsInfo) {
this.containerLogsInfo = containerLogsInfo;
}
public void setLogType(String logType) {
this.logType = logType;
}
public void setContainerId(String containerId) {
this.containerId = containerId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
}
| ContainerLogsInfo |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/array/AbstractArrayPositionsFunction.java | {
"start": 875,
"end": 1794
} | class ____ extends AbstractSqmSelfRenderingFunctionDescriptor {
public AbstractArrayPositionsFunction(boolean list, TypeConfiguration typeConfiguration) {
super(
"array_positions" + ( list ? "_list" : "" ),
new ArgumentTypesValidator(
StandardArgumentsValidators.composite(
StandardArgumentsValidators.exactly( 2 ),
ArrayAndElementArgumentValidator.DEFAULT_INSTANCE
),
FunctionParameterType.ANY,
FunctionParameterType.ANY
),
StandardFunctionReturnTypeResolvers.invariant(
typeConfiguration.standardBasicTypeForJavaType(
list
? new ParameterizedTypeImpl( List.class, new Type[]{ Integer.class }, null )
: int[].class
)
),
ArrayAndElementArgumentTypeResolver.DEFAULT_INSTANCE
);
}
@Override
public String getArgumentListSignature() {
return "(ARRAY array, OBJECT element)";
}
}
| AbstractArrayPositionsFunction |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ThreadJoinLoopTest.java | {
"start": 16652,
"end": 17763
} | class ____ extends Thread {
public void run() {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(this)
join();
} catch (InterruptedException e) {
// ignore
}
}
public void whileInThread() {
while (isAlive()) {
try {
// BUG: Diagnostic contains: Uninterruptibles.joinUninterruptibly(this)
join();
} catch (InterruptedException e) {
// Ignore.
}
}
}
}
}\
""")
.addOutputLines(
"ThreadJoinLoopPositiveCases_expected.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import com.google.common.util.concurrent.Uninterruptibles;
/**
* @author mariasam@google.com (Maria Sam) on 7/10/17.
*/
| MyThread |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/source/manysourcearguments/Person.java | {
"start": 214,
"end": 1203
} | class ____ {
private String firstName;
private String lastName;
private int height;
private String description;
public Person(String firstName, String lastName, int height, String description) {
this.firstName = firstName;
this.lastName = lastName;
this.height = height;
this.description = description;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| Person |
java | spring-projects__spring-boot | module/spring-boot-micrometer-observation/src/test/java/org/springframework/boot/micrometer/observation/autoconfigure/ObservationAutoConfigurationTests.java | {
"start": 9213,
"end": 9742
} | class ____ {
@Bean
ObservedAspect customObservedAspect(ObservationRegistry observationRegistry) {
return new ObservedAspect(observationRegistry);
}
@Bean
ObservationKeyValueAnnotationHandler customObservationKeyValueAnnotationHandler(BeanFactory beanFactory,
ValueExpressionResolver valueExpressionResolver) {
return new ObservationKeyValueAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver);
}
}
@Configuration(proxyBeanMethods = false)
static | CustomObservedAspectConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/PeriodTimeMathTest.java | {
"start": 1056,
"end": 1955
} | class ____ {
private final CompilationTestHelper helper =
CompilationTestHelper.newInstance(PeriodTimeMath.class, getClass());
@SuppressWarnings("PeriodTimeMath")
@Test
public void failures() {
Period p = Period.ZERO;
assertThrows(DateTimeException.class, () -> p.plus(Duration.ZERO));
assertThrows(DateTimeException.class, () -> p.minus(Duration.ZERO));
assertThrows(DateTimeException.class, () -> p.plus(Duration.ofHours(48)));
assertThrows(DateTimeException.class, () -> p.minus(Duration.ofHours(48)));
assertThrows(DateTimeException.class, () -> p.plus(Duration.ofDays(2)));
}
@Test
public void periodMath() {
helper
.addSourceLines(
"TestClass.java",
"import java.time.Duration;",
"import java.time.Period;",
"import java.time.temporal.TemporalAmount;",
"public | PeriodTimeMathTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest74.java | {
"start": 893,
"end": 1976
} | class ____ extends TestCase {
public void test_false() throws Exception {
WallProvider provider = new MySqlWallProvider();
provider.getConfig().setCommentAllow(true);
final String sql = "select _t0.`ownUser` as _c0, _t0.`showTime` as _c1, _t0.`showType` as _c2, " +
" _t0.`itemId` as _c3, _t0.`queueId` as _c4 " +
"from `itemshow_queue` as _t0 " +
"where ( _t0.`isShowed` = 'F' and _t0.`showTime` <= ? ) " +
" and _t0.`ownUser` in ( " +
" select _t0.`userId` as _c0 from `users_top` as _t0 " +
" where ( 1 = 1 ) " +
" ) " +
"order by _t0.`showTime` asc " +
"limit 1000 offset 8000";
provider.getConfig().setSelectWhereAlwayTrueCheck(true);
assertFalse(provider.checkValid(sql));
assertEquals(2, provider.getTableStats().size());
provider.getConfig().setSelectWhereAlwayTrueCheck(false);
assertFalse(provider.checkValid(sql));
}
}
| MySqlWallTest74 |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpPollEnrichBridgeErrorHandlerIT.java | {
"start": 3754,
"end": 4490
} | class ____ implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (newExchange != null) {
copyResultsPreservePattern(oldExchange, newExchange);
} else {
// if no newExchange then there was no message from the external
// resource
// and therefore we should set an empty body to indicate this
// fact
// but keep headers/attachments as we want to propagate those
oldExchange.getIn().setBody(null);
oldExchange.setOut(null);
}
return oldExchange;
}
}
}
| MyAggregationStrategy |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TruthContainsExactlyElementsInUsageTest.java | {
"start": 10471,
"end": 11033
} | class ____ {
void test() {
assertThat(ImmutableList.of(1)).containsExactly(1);
}
}
""")
.doTest();
}
@Test
public void refactoringTruthContainsExactlyElementsInUsageWithEmptyList() {
refactoringHelper
.addInputLines(
"ExampleClassTest.java",
"""
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
public | ExampleClassTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/ZeroShotClassificationConfigTests.java | {
"start": 640,
"end": 3252
} | class ____ extends InferenceConfigItemTestCase<ZeroShotClassificationConfig> {
public static ZeroShotClassificationConfig mutateForVersion(ZeroShotClassificationConfig instance, TransportVersion version) {
return new ZeroShotClassificationConfig(
instance.getClassificationLabels(),
instance.getVocabularyConfig(),
InferenceConfigTestScaffolding.mutateTokenizationForVersion(instance.getTokenization(), version),
instance.getHypothesisTemplate(),
instance.isMultiLabel(),
instance.getLabels().orElse(null),
instance.getResultsField()
);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
@Override
protected Predicate<String> getRandomFieldsExcludeFilter() {
return field -> field.isEmpty() == false;
}
@Override
protected ZeroShotClassificationConfig doParseInstance(XContentParser parser) throws IOException {
return ZeroShotClassificationConfig.fromXContentLenient(parser);
}
@Override
protected Writeable.Reader<ZeroShotClassificationConfig> instanceReader() {
return ZeroShotClassificationConfig::new;
}
@Override
protected ZeroShotClassificationConfig createTestInstance() {
return createRandom();
}
@Override
protected ZeroShotClassificationConfig mutateInstance(ZeroShotClassificationConfig instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected ZeroShotClassificationConfig mutateInstanceForVersion(ZeroShotClassificationConfig instance, TransportVersion version) {
return mutateForVersion(instance, version);
}
public static ZeroShotClassificationConfig createRandom() {
return new ZeroShotClassificationConfig(
randomFrom(List.of("entailment", "neutral", "contradiction"), List.of("contradiction", "neutral", "entailment")),
randomBoolean() ? null : VocabularyConfigTests.createRandom(),
randomBoolean()
? null
: randomFrom(
BertTokenizationTests.createRandom(),
MPNetTokenizationTests.createRandom(),
RobertaTokenizationTests.createRandom()
),
randomAlphaOfLength(10),
randomBoolean(),
randomBoolean() ? null : randomList(1, 5, () -> randomAlphaOfLength(10)),
randomBoolean() ? null : randomAlphaOfLength(7)
);
}
}
| ZeroShotClassificationConfigTests |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/XORErasureEncoder.java | {
"start": 1396,
"end": 1926
} | class ____ extends ErasureEncoder {
public XORErasureEncoder(ErasureCoderOptions options) {
super(options);
}
@Override
protected ErasureCodingStep prepareEncodingStep(
final ECBlockGroup blockGroup) {
RawErasureEncoder rawEncoder = CodecUtil.createRawEncoder(getConf(),
ErasureCodeConstants.XOR_CODEC_NAME, getOptions());
ECBlock[] inputBlocks = getInputBlocks(blockGroup);
return new ErasureEncodingStep(inputBlocks,
getOutputBlocks(blockGroup), rawEncoder);
}
}
| XORErasureEncoder |
java | apache__maven | compat/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/ArtifactMetadata.java | {
"start": 982,
"end": 1125
} | interface ____ extends org.apache.maven.repository.legacy.metadata.ArtifactMetadata {
void merge(ArtifactMetadata metadata);
}
| ArtifactMetadata |
java | apache__dubbo | dubbo-plugin/dubbo-rest-jaxrs/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/FormParamArgumentResolver.java | {
"start": 1410,
"end": 2294
} | class ____ extends AbstractJaxrsArgumentResolver {
@Override
public Class<Annotation> accept() {
return Annotations.FormParam.type();
}
@Override
protected ParamType getParamType(NamedValueMeta meta) {
return ParamType.Form;
}
@Override
protected Object resolveValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
return CollectionUtils.first(request.formParameterValues(getFullName(meta)));
}
@Override
protected Object resolveCollectionValue(NamedValueMeta meta, HttpRequest request, HttpResponse response) {
return request.formParameterValues(getFullName(meta));
}
private String getFullName(NamedValueMeta meta) {
String prefix = meta.parameter().getPrefix();
return prefix == null ? meta.name() : prefix + '.' + meta.name();
}
}
| FormParamArgumentResolver |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/util/UnmodifiableMultiValueMapTests.java | {
"start": 1265,
"end": 8301
} | class ____ {
@Test
void delegation() {
MultiValueMap<String, String> mock = mock();
UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(mock);
given(mock.size()).willReturn(1);
assertThat(map).hasSize(1);
given(mock.isEmpty()).willReturn(false);
assertThat(map).isNotEmpty();
given(mock.containsKey("foo")).willReturn(true);
assertThat(map.containsKey("foo")).isTrue();
given(mock.containsValue(List.of("bar"))).willReturn(true);
assertThat(map.containsValue(List.of("bar"))).isTrue();
List<String> list = new ArrayList<>();
list.add("bar");
given(mock.get("foo")).willReturn(list);
List<String> result = map.get("foo");
assertThat(result).containsExactly("bar");
assertThatUnsupportedOperationException().isThrownBy(() -> result.add("baz"));
given(mock.getOrDefault("foo", List.of("bar"))).willReturn(List.of("baz"));
assertThat(map.getOrDefault("foo", List.of("bar"))).containsExactly("baz");
given(mock.toSingleValueMap()).willReturn(Map.of("foo", "bar"));
assertThat(map.toSingleValueMap()).containsExactly(entry("foo", "bar"));
}
@Test
void unsupported() {
UnmodifiableMultiValueMap<String, String> map = new UnmodifiableMultiValueMap<>(new LinkedMultiValueMap<>());
assertThatUnsupportedOperationException().isThrownBy(() -> map.put("foo", List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.putIfAbsent("foo", List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.putAll(Map.of("foo", List.of("bar"))));
assertThatUnsupportedOperationException().isThrownBy(() -> map.remove("foo"));
assertThatUnsupportedOperationException().isThrownBy(() -> map.add("foo", "bar"));
assertThatUnsupportedOperationException().isThrownBy(() -> map.addAll("foo", List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.addAll(new LinkedMultiValueMap<>()));
assertThatUnsupportedOperationException().isThrownBy(() -> map.addIfAbsent("foo", "baz"));
assertThatUnsupportedOperationException().isThrownBy(() -> map.set("foo", "baz"));
assertThatUnsupportedOperationException().isThrownBy(() -> map.setAll(Map.of("foo", "baz")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.replaceAll((s, strings) -> strings));
assertThatUnsupportedOperationException().isThrownBy(() -> map.remove("foo", List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.replace("foo", List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.replace("foo", List.of("bar"), List.of("baz")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.computeIfAbsent("foo", s -> List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(
() -> map.computeIfPresent("foo", (s1, s2) -> List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.compute("foo", (s1, s2) -> List.of("bar")));
assertThatUnsupportedOperationException().isThrownBy(() -> map.merge("foo", List.of("bar"), (s1, s2) -> s1));
assertThatUnsupportedOperationException().isThrownBy(map::clear);
}
@Test
@SuppressWarnings("unchecked")
void entrySetDelegation() {
MultiValueMap<String, String> mockMap = mock();
Set<Map.Entry<String, List<String>>> mockSet = mock();
given(mockMap.entrySet()).willReturn(mockSet);
Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<>(mockMap).entrySet();
given(mockSet.size()).willReturn(1);
assertThat(set).hasSize(1);
given(mockSet.isEmpty()).willReturn(false);
assertThat(set.isEmpty()).isFalse();
Map.Entry<String, List<String>> mockedEntry = mock();
given(mockSet.contains(mockedEntry)).willReturn(true);
assertThat(set.contains(mockedEntry)).isTrue();
List<Map.Entry<String, List<String>>> mockEntries = List.of(mock(Map.Entry.class));
given(mockSet.containsAll(mockEntries)).willReturn(true);
assertThat(set.containsAll(mockEntries)).isTrue();
Iterator<Map.Entry<String, List<String>>> mockIterator = mock();
given(mockSet.iterator()).willReturn(mockIterator);
given(mockIterator.hasNext()).willReturn(false);
assertThat(set.iterator()).isExhausted();
}
@Test
@SuppressWarnings("unchecked")
void entrySetUnsupported() {
Set<Map.Entry<String, List<String>>> set = new UnmodifiableMultiValueMap<String, String>(new LinkedMultiValueMap<>()).entrySet();
assertThatUnsupportedOperationException().isThrownBy(() -> set.add(mock(Map.Entry.class)));
assertThatUnsupportedOperationException().isThrownBy(() -> set.remove(mock(Map.Entry.class)));
assertThatUnsupportedOperationException().isThrownBy(() -> set.removeIf(e -> true));
assertThatUnsupportedOperationException().isThrownBy(() -> set.addAll(mock(List.class)));
assertThatUnsupportedOperationException().isThrownBy(() -> set.retainAll(mock(List.class)));
assertThatUnsupportedOperationException().isThrownBy(() -> set.removeAll(mock(List.class)));
assertThatUnsupportedOperationException().isThrownBy(set::clear);
}
@Test
@SuppressWarnings("unchecked")
void valuesDelegation() {
MultiValueMap<String, String> mockMap = mock();
Collection<List<String>> mockValues = mock();
given(mockMap.values()).willReturn(mockValues);
Collection<List<String>> values = new UnmodifiableMultiValueMap<>(mockMap).values();
given(mockValues.size()).willReturn(1);
assertThat(values).hasSize(1);
given(mockValues.isEmpty()).willReturn(false);
assertThat(values.isEmpty()).isFalse();
given(mockValues.contains(List.of("foo"))).willReturn(true);
assertThat(mockValues.contains(List.of("foo"))).isTrue();
given(mockValues.containsAll(List.of(List.of("foo")))).willReturn(true);
assertThat(mockValues.containsAll(List.of(List.of("foo")))).isTrue();
Iterator<List<String>> mockIterator = mock(Iterator.class);
given(mockValues.iterator()).willReturn(mockIterator);
given(mockIterator.hasNext()).willReturn(false);
assertThat(values.iterator()).isExhausted();
}
@Test
void valuesUnsupported() {
Collection<List<String>> values =
new UnmodifiableMultiValueMap<String, String>(new LinkedMultiValueMap<>()).values();
assertThatUnsupportedOperationException().isThrownBy(() -> values.add(List.of("foo")));
assertThatUnsupportedOperationException().isThrownBy(() -> values.remove(List.of("foo")));
assertThatUnsupportedOperationException().isThrownBy(() -> values.addAll(List.of(List.of("foo"))));
assertThatUnsupportedOperationException().isThrownBy(() -> values.removeAll(List.of(List.of("foo"))));
assertThatUnsupportedOperationException().isThrownBy(() -> values.retainAll(List.of(List.of("foo"))));
assertThatUnsupportedOperationException().isThrownBy(() -> values.removeIf(s -> true));
assertThatUnsupportedOperationException().isThrownBy(values::clear);
}
private static ThrowableTypeAssert<UnsupportedOperationException> assertThatUnsupportedOperationException() {
return assertThatExceptionOfType(UnsupportedOperationException.class);
}
}
| UnmodifiableMultiValueMapTests |
java | redisson__redisson | redisson/src/main/java/org/redisson/cache/AbstractCacheMap.java | {
"start": 12485,
"end": 17731
} | class ____ extends AbstractSet<Map.Entry<K, V>> {
public Iterator<Map.Entry<K, V>> iterator() {
return new MapIterator<Map.Entry<K, V>>() {
@Override
public Map.Entry<K, V> next() {
if (mapEntry == null) {
throw new NoSuchElementException();
}
SimpleEntry<K, V> result = new SimpleEntry<K, V>(mapEntry.getKey(), readValue(mapEntry.getValue()));
mapEntry = null;
return result;
}
@Override
public void remove() {
if (mapEntry == null) {
throw new IllegalStateException();
}
map.remove(mapEntry.getKey(), mapEntry.getValue());
mapEntry = null;
}
};
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
Object key = e.getKey();
V value = get(key);
return value != null && value.equals(e);
}
public boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
Object key = e.getKey();
Object value = e.getValue();
return AbstractCacheMap.this.map.remove(key, value);
}
return false;
}
public int size() {
return AbstractCacheMap.this.size();
}
public void clear() {
AbstractCacheMap.this.clear();
}
}
@Override
public V putIfAbsent(K key, V value) {
CachedValue<K, V> entry = create(key, value, timeToLiveInMillis, maxIdleInMillis);
CachedValue<K, V> prevCachedValue = map.putIfAbsent(key, entry);
if (prevCachedValue != null) {
return prevCachedValue.getValue();
}
if (isFull(key)) {
if (!removeExpiredEntries()) {
onMapFull();
}
}
onValueCreate(entry);
return null;
}
@Override
public boolean remove(Object key, Object value) {
AtomicBoolean result = new AtomicBoolean();
map.computeIfPresent((K) key, (k, entry) -> {
if (entry.getValue().equals(value)
&& !isValueExpired(entry)) {
onValueRemove(entry);
result.set(true);
return null;
}
return entry;
});
return result.get();
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
AtomicBoolean result = new AtomicBoolean();
map.computeIfPresent(key, (k, entry) -> {
if (entry.getValue().equals(oldValue)
&& !isValueExpired(entry)) {
onValueRemove(entry);
result.set(true);
CachedValue<K, V> newEntry = create(key, newValue, timeToLiveInMillis, maxIdleInMillis);
onValueCreate(newEntry);
return newEntry;
}
return entry;
});
return result.get();
}
@Override
public V replace(K key, V value) {
AtomicReference<V> result = new AtomicReference<>();
map.computeIfPresent(key, (k, entry) -> {
if (!isValueExpired(entry)) {
onValueRemove(entry);
result.set(entry.getValue());
CachedValue<K, V> newEntry = create(key, value, timeToLiveInMillis, maxIdleInMillis);
onValueCreate(newEntry);
return newEntry;
}
return entry;
});
return result.get();
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (isFull(key)) {
if (!removeExpiredEntries()) {
onMapFull();
}
}
CachedValue<K, V> v = map.computeIfAbsent(key, k -> {
V value = mappingFunction.apply(k);
if (value == null) {
return null;
}
CachedValue<K, V> entry = create(key, value, timeToLiveInMillis, maxIdleInMillis);
onValueCreate(entry);
return entry;
});
if (v != null) {
return v.getValue();
}
return null;
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
CachedValue<K, V> v = map.computeIfPresent(key, (k, e) -> {
if (!isValueExpired(e)) {
V value = remappingFunction.apply(k, e.getValue());
if (value == null) {
return null;
}
CachedValue<K, V> entry = create(key, value, timeToLiveInMillis, maxIdleInMillis);
onValueCreate(entry);
return entry;
}
return null;
});
if (v != null) {
return v.getValue();
}
return null;
}
} | EntrySet |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionFailAndOkTest.java | {
"start": 1027,
"end": 2999
} | class ____ extends ContextTestSupport {
@Test
public void testOk() throws Exception {
getMockEndpoint("mock:ok").expectedMessageCount(1);
getMockEndpoint("mock:fail").expectedMessageCount(0);
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testFail() throws Exception {
getMockEndpoint("mock:ok").expectedMessageCount(0);
getMockEndpoint("mock:fail").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
try {
template.sendBody("direct:start", "Kaboom");
fail("Should throw exception");
} catch (Exception e) {
// expected
}
assertMockEndpointsSatisfied();
}
@Test
public void testOkAndFail() throws Exception {
getMockEndpoint("mock:ok").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:fail").expectedBodiesReceived("Kaboom");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
template.sendBody("direct:start", "Hello World");
try {
template.sendBody("direct:start", "Kaboom");
fail("Should throw exception");
} catch (Exception e) {
// expected
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.onCompletion().onCompleteOnly().to("log:ok").to("mock:ok").end()
.onCompletion().onFailureOnly().to("log:fail").to("mock:fail").end()
.process(new OnCompletionTest.MyProcessor())
.to("mock:result");
}
};
}
}
| OnCompletionFailAndOkTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/InsensitiveEqualsMapper.java | {
"start": 1249,
"end": 2728
} | class ____ extends ExpressionMapper<InsensitiveEquals> {
private final TriFunction<Source, ExpressionEvaluator.Factory, ExpressionEvaluator.Factory, ExpressionEvaluator.Factory> keywords =
InsensitiveEqualsEvaluator.Factory::new;
@Override
public final ExpressionEvaluator.Factory map(
FoldContext foldCtx,
InsensitiveEquals bc,
Layout layout,
IndexedByShardId<? extends ShardContext> shardContexts
) {
DataType leftType = bc.left().dataType();
DataType rightType = bc.right().dataType();
var leftEval = toEvaluator(foldCtx, bc.left(), layout, shardContexts);
var rightEval = toEvaluator(foldCtx, bc.right(), layout, shardContexts);
if (DataType.isString(leftType)) {
if (bc.right().foldable() && DataType.isString(rightType)) {
BytesRef rightVal = BytesRefs.toBytesRef(bc.right().fold(foldCtx));
Automaton automaton = InsensitiveEquals.automaton(rightVal);
return dvrCtx -> new InsensitiveEqualsConstantEvaluator(
bc.source(),
leftEval.get(dvrCtx),
new ByteRunAutomaton(automaton),
dvrCtx
);
}
return keywords.apply(bc.source(), leftEval, rightEval);
}
throw new EsqlIllegalArgumentException("resolved type for [" + bc + "] but didn't implement mapping");
}
}
| InsensitiveEqualsMapper |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/protocol/CompleteableCommand.java | {
"start": 437,
"end": 1015
} | interface ____<T> {
/**
* Register a command callback for successive command completion that notifies the callback with the command result.
*
* @param action must not be {@code null}.
*/
void onComplete(Consumer<? super T> action);
/**
* Register a command callback for command completion that notifies the callback with the command result or the failure
* resulting from command completion.
*
* @param action must not be {@code null}.
*/
void onComplete(BiConsumer<? super T, Throwable> action);
}
| CompleteableCommand |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/GetConf.java | {
"start": 6699,
"end": 7014
} | class ____ extends CommandHandler {
@Override
public int doWorkInternal(GetConf tool, String []args) throws IOException {
tool.printMap(DFSUtil.getBackupNodeAddresses(tool.getConf()));
return 0;
}
}
/**
* Handler for {@linke Command#JOURNALNODE}.
*/
static | BackupNodesCommandHandler |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/UUIDs.java | {
"start": 773,
"end": 4185
} | class ____ {
private static final AtomicInteger sequenceNumber = new AtomicInteger(SecureRandomHolder.INSTANCE.nextInt());
public static final Supplier<Long> DEFAULT_TIMESTAMP_SUPPLIER = System::currentTimeMillis;
public static final Supplier<Integer> DEFAULT_SEQUENCE_ID_SUPPLIER = sequenceNumber::incrementAndGet;
public static final Supplier<byte[]> DEFAULT_MAC_ADDRESS_SUPPLIER = MacAddressProvider::getSecureMungedAddress;
private static final RandomBasedUUIDGenerator RANDOM_UUID_GENERATOR = new RandomBasedUUIDGenerator();
private static final TimeBasedKOrderedUUIDGenerator TIME_BASED_K_ORDERED_GENERATOR = new TimeBasedKOrderedUUIDGenerator(
DEFAULT_TIMESTAMP_SUPPLIER,
DEFAULT_SEQUENCE_ID_SUPPLIER,
DEFAULT_MAC_ADDRESS_SUPPLIER
);
private static final TimeBasedUUIDGenerator TIME_UUID_GENERATOR = new TimeBasedUUIDGenerator(
DEFAULT_TIMESTAMP_SUPPLIER,
DEFAULT_SEQUENCE_ID_SUPPLIER,
DEFAULT_MAC_ADDRESS_SUPPLIER
);
/**
* The length of a UUID string generated by {@link #base64UUID}.
*/
// A 15-byte time-based UUID is base64-encoded as 5 3-byte chunks (each becoming 4 chars after encoding).
public static final int TIME_BASED_UUID_STRING_LENGTH = 20;
/**
* Generates a time-based UUID (similar to Flake IDs), which is preferred when generating an ID to be indexed into a Lucene index as
* primary key. The id is opaque and the implementation is free to change at any time!
* The resulting string has length {@link #TIME_BASED_UUID_STRING_LENGTH}.
*/
public static String base64UUID() {
return TIME_UUID_GENERATOR.getBase64UUID();
}
public static String base64TimeBasedKOrderedUUIDWithHash(OptionalInt hash) {
return TIME_BASED_K_ORDERED_GENERATOR.getBase64UUID(hash);
}
/**
* The length of a UUID string generated by {@link #randomBase64UUID} and {@link #randomBase64UUIDSecureString}.
*/
// A 16-byte v4 UUID is base64-encoded as 5 3-byte chunks (each becoming 4 chars after encoding) plus another byte (becomes 2 chars).
public static final int RANDOM_BASED_UUID_STRING_LENGTH = 22;
/**
* Returns a Base64 encoded string representing a <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC4122 version 4 UUID</a>, using the
* provided {@code Random} instance.
* The resulting string has length {@link #RANDOM_BASED_UUID_STRING_LENGTH}.
*/
public static String randomBase64UUID(Random random) {
return RandomBasedUUIDGenerator.getBase64UUID(random);
}
/**
* Returns a Base64 encoded string representing a <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC4122 version 4 UUID</a>, using a
* private {@code SecureRandom} instance.
* The resulting string has length {@link #RANDOM_BASED_UUID_STRING_LENGTH}.
*/
public static String randomBase64UUID() {
return RANDOM_UUID_GENERATOR.getBase64UUID();
}
/**
* Returns a Base64 encoded {@link SecureString} representing a <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC4122 version 4
* UUID</a>, using a private {@code SecureRandom} instance.
* The resulting string has length {@link #RANDOM_BASED_UUID_STRING_LENGTH}.
*/
public static SecureString randomBase64UUIDSecureString() {
return RandomBasedUUIDGenerator.getBase64UUIDSecureString();
}
}
| UUIDs |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/pipeline/MinBucketIT.java | {
"start": 804,
"end": 2170
} | class ____ extends BucketMetricsPipeLineAggregationTestCase<InternalBucketMetricValue> {
@Override
protected MinBucketPipelineAggregationBuilder BucketMetricsPipelineAgg(String name, String bucketsPath) {
return minBucket(name, bucketsPath);
}
@Override
protected void assertResult(
IntToDoubleFunction bucketValues,
Function<Integer, String> bucketKeys,
int numBuckets,
InternalBucketMetricValue pipelineBucket
) {
List<String> minKeys = new ArrayList<>();
double minValue = Double.POSITIVE_INFINITY;
for (int i = 0; i < numBuckets; ++i) {
double bucketValue = bucketValues.applyAsDouble(i);
if (bucketValue < minValue) {
minValue = bucketValue;
minKeys = new ArrayList<>();
minKeys.add(bucketKeys.apply(i));
} else if (bucketValue == minValue) {
minKeys.add(bucketKeys.apply(i));
}
}
assertThat(pipelineBucket.value(), equalTo(minValue));
assertThat(pipelineBucket.keys(), equalTo(minKeys.toArray(new String[0])));
}
@Override
protected String nestedMetric() {
return "value";
}
@Override
protected double getNestedMetric(InternalBucketMetricValue bucket) {
return bucket.value();
}
}
| MinBucketIT |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointFailureProcessorTest.java | {
"start": 1170,
"end": 3093
} | class ____ extends ContextTestSupport {
private static String beforeThreadName;
private static String afterThreadName;
@Test
public void testAsyncEndpoint() throws Exception {
getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel");
getMockEndpoint("mock:after").expectedBodiesReceived("MyFailureHandler");
getMockEndpoint("mock:result").expectedMessageCount(0);
String reply = template.requestBody("direct:start", "Hello Camel", String.class);
assertEquals("Bye Camel", reply);
assertMockEndpointsSatisfied();
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
context.addComponent("async", new MyAsyncComponent());
// the onException can be asynchronous as well so we have to
// test for that
onException(IllegalArgumentException.class).handled(true).to("mock:before").to("log:before")
.process(new Processor() {
public void process(Exchange exchange) {
beforeThreadName = Thread.currentThread().getName();
}
}).to("async:MyFailureHandler").process(new Processor() {
public void process(Exchange exchange) {
afterThreadName = Thread.currentThread().getName();
}
}).to("log:after").to("mock:after").transform(constant("Bye Camel"));
from("direct:start").throwException(new IllegalArgumentException("Damn")).to("mock:result");
}
};
}
}
| AsyncEndpointFailureProcessorTest |
java | mybatis__mybatis-3 | src/main/java/org/apache/ibatis/type/SqlTimeTypeHandler.java | {
"start": 873,
"end": 1522
} | class ____ extends BaseTypeHandler<Time> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Time parameter, JdbcType jdbcType) throws SQLException {
ps.setTime(i, parameter);
}
@Override
public Time getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getTime(columnName);
}
@Override
public Time getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getTime(columnIndex);
}
@Override
public Time getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getTime(columnIndex);
}
}
| SqlTimeTypeHandler |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-csi/src/test/java/org/apache/hadoop/yarn/csi/adaptor/MockCsiAdaptor.java | {
"start": 1673,
"end": 1931
} | class ____ used by {@link TestCsiAdaptorService} for testing.
* It gives some dummy implementation for a adaptor plugin, and used to
* verify the plugin can be properly loaded by NM and execution logic is
* as expected.
*
* This is created as a separated | is |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/client/BootstrapperImpl.java | {
"start": 12327,
"end": 12827
} | enum ____ implements FileReader {
INSTANCE;
@Override
public String readFile(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
}
}
private static <T> T checkForNull(T value, String fieldName) throws XdsInitializationException {
if (value == null) {
throw new XdsInitializationException(
"Invalid bootstrap: '" + fieldName + "' does not exist.");
}
return value;
}
}
| LocalFileReader |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/MappedSuperclassAndGenericsTest.java | {
"start": 1710,
"end": 1985
} | class ____ extends ParameterizedParent<Long> {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
}
| LongEntity |
java | hibernate__hibernate-orm | hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionNumberPropertyName.java | {
"start": 393,
"end": 572
} | class ____ implements PropertyNameGetter {
@Override
public String get(Configuration configuration) {
return configuration.getRevisionNumberPath();
}
}
| RevisionNumberPropertyName |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Issue62.java | {
"start": 195,
"end": 603
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
A a = new A();
a.setA("aaaaaaaaaa".getBytes());
a.setB(1);
a.setC("aaaa");
String jsonData = JSON.toJSONString(a, SerializerFeature.UseSingleQuotes);
Assert.assertEquals("{'a':'YWFhYWFhYWFhYQ==','b':1,'c':'aaaa'}", jsonData);
JSON.parse(jsonData);
}
static | Issue62 |
java | spring-projects__spring-boot | module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/ServiceLevelObjectiveBoundaryTests.java | {
"start": 1150,
"end": 3343
} | class ____ {
@Test
void getValueForTimerWhenFromLongShouldReturnMsToNanosValue() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf(123L);
assertThat(slo.getValue(Type.TIMER)).isEqualTo(123000000);
}
@Test
void getValueForTimerWhenFromNumberStringShouldMsToNanosValue() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123");
assertThat(slo.getValue(Type.TIMER)).isEqualTo(123000000);
}
@Test
void getValueForTimerWhenFromMillisecondDurationStringShouldReturnDurationNanos() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123ms");
assertThat(slo.getValue(Type.TIMER)).isEqualTo(123000000);
}
@Test
void getValueForTimerWhenFromDaysDurationStringShouldReturnDurationNanos() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("1d");
assertThat(slo.getValue(Type.TIMER)).isEqualTo(Duration.ofDays(1).toNanos());
}
@Test
void getValueForDistributionSummaryWhenFromDoubleShouldReturnDoubleValue() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf(123.42);
assertThat(slo.getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(123.42);
}
@Test
void getValueForDistributionSummaryWhenFromStringShouldReturnDoubleValue() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123.42");
assertThat(slo.getValue(Type.DISTRIBUTION_SUMMARY)).isEqualTo(123.42);
}
@Test
void getValueForDistributionSummaryWhenFromDurationShouldReturnNull() {
ServiceLevelObjectiveBoundary slo = ServiceLevelObjectiveBoundary.valueOf("123ms");
assertThat(slo.getValue(Type.DISTRIBUTION_SUMMARY)).isNull();
}
@Test
void shouldRegisterRuntimeHints() {
RuntimeHints runtimeHints = new RuntimeHints();
new ServiceLevelObjectiveBoundary.ServiceLevelObjectiveBoundaryHints().registerHints(runtimeHints,
getClass().getClassLoader());
ReflectionUtils.doWithLocalMethods(ServiceLevelObjectiveBoundary.class, (method) -> {
if ("valueOf".equals(method.getName())) {
assertThat(RuntimeHintsPredicates.reflection().onMethodInvocation(method)).accepts(runtimeHints);
}
});
}
}
| ServiceLevelObjectiveBoundaryTests |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/openai/OpenAiServiceTests.java | {
"start": 6615,
"end": 54953
} | class ____ extends AbstractInferenceServiceTests {
private static final TimeValue TIMEOUT = new TimeValue(30, TimeUnit.SECONDS);
private static final String MODEL = "model";
private static final String URL = "http://www.elastic.co";
private static final String ORGANIZATION = "org";
private static final int MAX_INPUT_TOKENS = 123;
private static final SimilarityMeasure SIMILARITY = SimilarityMeasure.DOT_PRODUCT;
private static final int DIMENSIONS = 100;
private static final boolean DIMENSIONS_SET_BY_USER = true;
private static final String USER = "user";
private static final String HEADER_KEY = "header_key";
private static final String HEADER_VALUE = "header_value";
private static final Map<String, String> HEADERS = Map.of(HEADER_KEY, HEADER_VALUE);
private static final String SECRET = "secret";
private static final String INFERENCE_ID = "id";
private final MockWebServer webServer = new MockWebServer();
private ThreadPool threadPool;
private HttpClientManager clientManager;
@Before
public void init() throws Exception {
webServer.start();
threadPool = createThreadPool(inferenceUtilityExecutors());
clientManager = HttpClientManager.create(Settings.EMPTY, threadPool, mockClusterServiceEmpty(), mock(ThrottlerManager.class));
}
@After
public void shutdown() throws IOException {
clientManager.close();
terminate(threadPool);
webServer.close();
}
public OpenAiServiceTests() {
super(createTestConfiguration());
}
public static TestConfiguration createTestConfiguration() {
return new TestConfiguration.Builder(
new CommonConfig(
TaskType.TEXT_EMBEDDING,
TaskType.RERANK,
EnumSet.of(TaskType.TEXT_EMBEDDING, TaskType.COMPLETION, TaskType.CHAT_COMPLETION)
) {
@Override
protected SenderService createService(ThreadPool threadPool, HttpClientManager clientManager) {
return OpenAiServiceTests.createService(threadPool, clientManager);
}
@Override
protected Map<String, Object> createServiceSettingsMap(TaskType taskType) {
return createServiceSettingsMap(taskType, ConfigurationParseContext.REQUEST);
}
@Override
protected Map<String, Object> createServiceSettingsMap(TaskType taskType, ConfigurationParseContext parseContext) {
return OpenAiServiceTests.createServiceSettingsMap(taskType, parseContext);
}
@Override
protected Map<String, Object> createTaskSettingsMap() {
return OpenAiServiceTests.createTaskSettingsMap();
}
@Override
protected Map<String, Object> createSecretSettingsMap() {
return getSecretSettingsMap(SECRET);
}
@Override
protected void assertModel(Model model, TaskType taskType, boolean modelIncludesSecrets) {
OpenAiServiceTests.assertModel(model, taskType, modelIncludesSecrets);
}
@Override
protected EnumSet<TaskType> supportedStreamingTasks() {
return EnumSet.of(TaskType.CHAT_COMPLETION, TaskType.COMPLETION);
}
}
).enableUpdateModelTests(new UpdateModelConfiguration() {
@Override
protected OpenAiEmbeddingsModel createEmbeddingModel(SimilarityMeasure similarityMeasure) {
return createInternalEmbeddingModel(similarityMeasure, null);
}
}).build();
}
private static Map<String, Object> createServiceSettingsMap(TaskType taskType, ConfigurationParseContext parseContext) {
var settingsMap = new HashMap<String, Object>(
Map.of(
ServiceFields.MODEL_ID,
MODEL,
ServiceFields.URL,
URL,
OpenAiServiceFields.ORGANIZATION,
ORGANIZATION,
ServiceFields.MAX_INPUT_TOKENS,
MAX_INPUT_TOKENS
)
);
if (taskType == TaskType.TEXT_EMBEDDING) {
settingsMap.putAll(Map.of(ServiceFields.SIMILARITY, SIMILARITY.toString(), ServiceFields.DIMENSIONS, DIMENSIONS));
if (parseContext == ConfigurationParseContext.PERSISTENT) {
settingsMap.put(OpenAiEmbeddingsServiceSettings.DIMENSIONS_SET_BY_USER, DIMENSIONS_SET_BY_USER);
}
}
return settingsMap;
}
private static Map<String, Object> createTaskSettingsMap() {
return new HashMap<>(Map.of(OpenAiServiceFields.USER, USER, OpenAiServiceFields.HEADERS, HEADERS));
}
private static void assertModel(Model model, TaskType taskType, boolean modelIncludesSecrets) {
switch (taskType) {
case TEXT_EMBEDDING -> assertTextEmbeddingModel(model, modelIncludesSecrets);
case COMPLETION, CHAT_COMPLETION -> assertCompletionModel(model, modelIncludesSecrets);
default -> fail("unexpected task type: " + taskType);
}
}
private static void assertTextEmbeddingModel(Model model, boolean modelIncludesSecrets) {
assertThat(model, instanceOf(OpenAiEmbeddingsModel.class));
var embeddingsModel = (OpenAiEmbeddingsModel) model;
assertThat(
embeddingsModel.getServiceSettings(),
is(
new OpenAiEmbeddingsServiceSettings(
MODEL,
URI.create(URL),
ORGANIZATION,
SIMILARITY,
DIMENSIONS,
MAX_INPUT_TOKENS,
DIMENSIONS_SET_BY_USER,
OpenAiEmbeddingsServiceSettings.DEFAULT_RATE_LIMIT_SETTINGS
)
)
);
assertThat(embeddingsModel.getTaskSettings(), is(new OpenAiEmbeddingsTaskSettings(USER, HEADERS)));
if (modelIncludesSecrets) {
assertThat(embeddingsModel.getSecretSettings().apiKey().toString(), is(SECRET));
} else {
assertNull(embeddingsModel.getSecretSettings());
}
}
private static void assertCompletionModel(Model model, boolean modelIncludesSecrets) {
assertThat(model, instanceOf(OpenAiChatCompletionModel.class));
var completionModel = (OpenAiChatCompletionModel) model;
assertThat(
completionModel.getServiceSettings(),
is(
new OpenAiChatCompletionServiceSettings(
MODEL,
URI.create(URL),
ORGANIZATION,
MAX_INPUT_TOKENS,
OpenAiChatCompletionServiceSettings.DEFAULT_RATE_LIMIT_SETTINGS
)
)
);
assertThat(completionModel.getTaskSettings(), is(new OpenAiChatCompletionTaskSettings(USER, HEADERS)));
assertSecrets(completionModel.getSecretSettings(), modelIncludesSecrets);
}
private static void assertSecrets(DefaultSecretSettings secretSettings, boolean modelIncludesSecrets) {
if (modelIncludesSecrets) {
assertThat(secretSettings.apiKey().toString(), is(SECRET));
}
}
private static OpenAiEmbeddingsModel createInternalEmbeddingModel(
SimilarityMeasure similarityMeasure,
@Nullable ChunkingSettings chunkingSettings
) {
return createInternalEmbeddingModel(similarityMeasure, URL, chunkingSettings);
}
private static OpenAiEmbeddingsModel createInternalEmbeddingModel(
SimilarityMeasure similarityMeasure,
@Nullable String url,
@Nullable ChunkingSettings chunkingSettings
) {
return new OpenAiEmbeddingsModel(
INFERENCE_ID,
TaskType.TEXT_EMBEDDING,
"service",
new OpenAiEmbeddingsServiceSettings(
MODEL,
url == null ? null : URI.create(url),
ORGANIZATION,
similarityMeasure,
DIMENSIONS,
DIMENSIONS,
false,
null
),
new OpenAiEmbeddingsTaskSettings(USER, HEADERS),
chunkingSettings,
new DefaultSecretSettings(new SecureString(SECRET.toCharArray()))
);
}
public void testParseRequestConfig_MovesModel() throws IOException {
try (var service = createOpenAiService()) {
ActionListener<Model> modelVerificationListener = ActionListener.wrap(model -> {
assertThat(model, instanceOf(OpenAiEmbeddingsModel.class));
var embeddingsModel = (OpenAiEmbeddingsModel) model;
assertThat(embeddingsModel.getServiceSettings().uri().toString(), is("url"));
assertThat(embeddingsModel.getServiceSettings().organizationId(), is("org"));
assertThat(embeddingsModel.getServiceSettings().modelId(), is("model"));
assertThat(embeddingsModel.getTaskSettings().user(), is("user"));
assertThat(embeddingsModel.getSecretSettings().apiKey().toString(), is("secret"));
}, exception -> fail("Unexpected exception: " + exception));
service.parseRequestConfig(
"id",
TaskType.TEXT_EMBEDDING,
getRequestConfigMap(
getServiceSettingsMap("model", "url", "org"),
getOpenAiTaskSettingsMap("user"),
getSecretSettingsMap("secret")
),
modelVerificationListener
);
}
}
public void testInfer_ThrowsErrorWhenModelIsNotOpenAiModel() throws IOException {
var sender = createMockSender();
var factory = mock(HttpRequestSender.Factory.class);
when(factory.createSender()).thenReturn(sender);
var mockModel = getInvalidModel("model_id", "service_name");
try (var service = new OpenAiService(factory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
mockModel,
null,
null,
null,
List.of(""),
false,
new HashMap<>(),
InputType.INTERNAL_SEARCH,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT));
assertThat(
thrownException.getMessage(),
is("The internal model was invalid, please delete the service [service_name] with id [model_id] and add it again.")
);
verify(factory, times(1)).createSender();
verify(sender, times(1)).startAsynchronously(any());
}
verify(sender, times(1)).close();
verifyNoMoreInteractions(factory);
verifyNoMoreInteractions(sender);
}
public void testInfer_ThrowsErrorWhenInputTypeIsSpecified() throws IOException {
var sender = createMockSender();
var factory = mock(HttpRequestSender.Factory.class);
when(factory.createSender()).thenReturn(sender);
var model = OpenAiEmbeddingsModelTests.createModel(getUrl(webServer), "org", "secret", "model", "user");
try (var service = new OpenAiService(factory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
model,
null,
null,
null,
List.of(""),
false,
new HashMap<>(),
InputType.INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ValidationException.class, () -> listener.actionGet(TIMEOUT));
assertThat(
thrownException.getMessage(),
is("Validation Failed: 1: Invalid input_type [ingest]. The input_type option is not supported by this service;")
);
verify(factory, times(1)).createSender();
verify(sender, times(1)).startAsynchronously(any());
}
verify(sender, times(1)).close();
verifyNoMoreInteractions(factory);
verifyNoMoreInteractions(sender);
}
public void testInfer_ThrowsErrorWhenTaskTypeIsNotValid() throws IOException {
var sender = createMockSender();
var factory = mock(HttpRequestSender.Factory.class);
when(factory.createSender()).thenReturn(sender);
var mockModel = getInvalidModel("model_id", "service_name", TaskType.SPARSE_EMBEDDING);
try (var service = new OpenAiService(factory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
mockModel,
null,
null,
null,
List.of(""),
false,
new HashMap<>(),
InputType.INTERNAL_INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT));
assertThat(
thrownException.getMessage(),
is(
"Inference entity [model_id] does not support task type [sparse_embedding] "
+ "for inference, the task type must be one of [text_embedding, completion]."
)
);
verify(factory, times(1)).createSender();
verify(sender, times(1)).startAsynchronously(any());
}
verify(sender, times(1)).close();
verifyNoMoreInteractions(factory);
verifyNoMoreInteractions(sender);
}
public void testInfer_ThrowsErrorWhenTaskTypeIsNotValid_ChatCompletion() throws IOException {
var sender = createMockSender();
var factory = mock(HttpRequestSender.Factory.class);
when(factory.createSender()).thenReturn(sender);
var mockModel = getInvalidModel("model_id", "service_name", TaskType.CHAT_COMPLETION);
try (var service = new OpenAiService(factory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
mockModel,
null,
null,
null,
List.of(""),
false,
new HashMap<>(),
InputType.INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var thrownException = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT));
assertThat(
thrownException.getMessage(),
is(
"Inference entity [model_id] does not support task type [chat_completion] "
+ "for inference, the task type must be one of [text_embedding, completion]. "
+ "The task type for the inference entity is chat_completion, "
+ "please use the _inference/chat_completion/model_id/_stream URL."
)
);
verify(factory, times(1)).createSender();
verify(sender, times(1)).startAsynchronously(any());
}
verify(sender, times(1)).close();
verifyNoMoreInteractions(factory);
verifyNoMoreInteractions(sender);
}
public void testInfer_SendsRequest() throws IOException {
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
String responseJson = """
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": [
0.0123,
-0.0123
]
}
],
"model": "text-embedding-ada-002-v2",
"usage": {
"prompt_tokens": 8,
"total_tokens": 8
}
}
""";
webServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseJson));
var model = OpenAiEmbeddingsModelTests.createModel(getUrl(webServer), "org", "secret", "model", "user");
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
model,
null,
null,
null,
List.of("abc"),
false,
new HashMap<>(),
InputType.INTERNAL_INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var result = listener.actionGet(TIMEOUT);
assertThat(result.asMap(), Matchers.is(buildExpectationFloat(List.of(new float[] { 0.0123F, -0.0123F }))));
assertThat(webServer.requests(), hasSize(1));
assertNull(webServer.requests().get(0).getUri().getQuery());
assertThat(webServer.requests().get(0).getHeader(HttpHeaders.CONTENT_TYPE), equalTo(XContentType.JSON.mediaType()));
assertThat(webServer.requests().get(0).getHeader(HttpHeaders.AUTHORIZATION), equalTo("Bearer secret"));
assertThat(webServer.requests().get(0).getHeader(ORGANIZATION_HEADER), equalTo("org"));
var requestMap = entityAsMap(webServer.requests().get(0).getBody());
assertThat(requestMap.size(), Matchers.is(3));
assertThat(requestMap.get("input"), Matchers.is(List.of("abc")));
assertThat(requestMap.get("model"), Matchers.is("model"));
assertThat(requestMap.get("user"), Matchers.is("user"));
}
}
public void testUnifiedCompletionInfer() throws Exception {
// The escapes are because the streaming response must be on a single line
String responseJson = """
data: {\
"id":"12345",\
"object":"chat.completion.chunk",\
"created":123456789,\
"model":"gpt-4o-mini",\
"system_fingerprint": "123456789",\
"choices":[\
{\
"index":0,\
"delta":{\
"content":"hello, world"\
},\
"logprobs":null,\
"finish_reason":"stop"\
}\
],\
"usage":{\
"prompt_tokens": 16,\
"completion_tokens": 28,\
"total_tokens": 44,\
"prompt_tokens_details": {\
"cached_tokens": 0,\
"audio_tokens": 0\
},\
"completion_tokens_details": {\
"reasoning_tokens": 0,\
"audio_tokens": 0,\
"accepted_prediction_tokens": 0,\
"rejected_prediction_tokens": 0\
}\
}\
}
""";
webServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseJson));
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
var model = OpenAiChatCompletionModelTests.createChatCompletionModel(getUrl(webServer), "org", "secret", "model", "user");
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.unifiedCompletionInfer(
model,
UnifiedCompletionRequest.of(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "user", null, null))
),
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var result = listener.actionGet(TIMEOUT);
InferenceEventsAssertion.assertThat(result).hasFinishedStream().hasNoErrors().hasEvent("""
{"id":"12345","choices":[{"delta":{"content":"hello, world"},"finish_reason":"stop","index":0}],""" + """
"model":"gpt-4o-mini","object":"chat.completion.chunk",""" + """
"usage":{"completion_tokens":28,"prompt_tokens":16,"total_tokens":44,""" + """
"prompt_tokens_details":{"cached_tokens":0}}}""");
}
}
public void testUnifiedCompletionError() throws Exception {
String responseJson = """
{
"error": {
"message": "The model `gpt-4awero` does not exist or you do not have access to it.",
"type": "invalid_request_error",
"param": null,
"code": "model_not_found"
}
}""";
webServer.enqueue(new MockResponse().setResponseCode(404).setBody(responseJson));
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
var model = OpenAiChatCompletionModelTests.createChatCompletionModel(getUrl(webServer), "org", "secret", "model", "user");
var latch = new CountDownLatch(1);
service.unifiedCompletionInfer(
model,
UnifiedCompletionRequest.of(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "user", null, null))
),
InferenceAction.Request.DEFAULT_TIMEOUT,
ActionListener.runAfter(ActionTestUtils.assertNoSuccessListener(e -> {
try (var builder = XContentFactory.jsonBuilder()) {
var t = unwrapCause(e);
assertThat(t, isA(UnifiedChatCompletionException.class));
((UnifiedChatCompletionException) t).toXContentChunked(EMPTY_PARAMS).forEachRemaining(xContent -> {
try {
xContent.toXContent(builder, EMPTY_PARAMS);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
var json = XContentHelper.convertToJson(BytesReference.bytes(builder), false, builder.contentType());
assertThat(json, is(String.format(Locale.ROOT, """
{\
"error":{\
"code":"model_not_found",\
"message":"Resource not found at [%s] for request from inference entity id [id] status \
[404]. Error message: [The model `gpt-4awero` does not exist or you do not have access to it.]",\
"type":"invalid_request_error"\
}}""", getUrl(webServer))));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}), latch::countDown)
);
assertTrue(latch.await(30, TimeUnit.SECONDS));
}
}
public void testMidStreamUnifiedCompletionError() throws Exception {
String responseJson = """
event: error
data: { "error": { "message": "Timed out waiting for more data", "type": "timeout" } }
""";
webServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseJson));
testStreamError("""
{\
"error":{\
"message":"Received an error response for request from inference entity id [id]. Error message: \
[Timed out waiting for more data]",\
"type":"timeout"\
}}""");
}
private void testStreamError(String expectedResponse) throws Exception {
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
var model = OpenAiChatCompletionModelTests.createChatCompletionModel(getUrl(webServer), "org", "secret", "model", "user");
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.unifiedCompletionInfer(
model,
UnifiedCompletionRequest.of(
List.of(new UnifiedCompletionRequest.Message(new UnifiedCompletionRequest.ContentString("hello"), "user", null, null))
),
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var result = listener.actionGet(TIMEOUT);
InferenceEventsAssertion.assertThat(result).hasFinishedStream().hasNoEvents().hasErrorMatching(e -> {
e = unwrapCause(e);
assertThat(e, isA(UnifiedChatCompletionException.class));
try (var builder = XContentFactory.jsonBuilder()) {
((UnifiedChatCompletionException) e).toXContentChunked(EMPTY_PARAMS).forEachRemaining(xContent -> {
try {
xContent.toXContent(builder, EMPTY_PARAMS);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
var json = XContentHelper.convertToJson(BytesReference.bytes(builder), false, builder.contentType());
assertThat(json, is(expectedResponse));
}
});
}
}
public void testUnifiedCompletionMalformedError() throws Exception {
String responseJson = """
data: { invalid json }
""";
webServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseJson));
testStreamError("""
{\
"error":{\
"code":"bad_request",\
"message":"[1:3] Unexpected character ('i' (code 105)): was expecting double-quote to start field name\\n\
at [Source: (String)\\"{ invalid json }\\"; line: 1, column: 3]",\
"type":"x_content_parse_exception"\
}}""");
}
public void testInfer_StreamRequest() throws Exception {
String responseJson = """
data: {\
"id":"12345",\
"object":"chat.completion.chunk",\
"created":123456789,\
"model":"gpt-4o-mini",\
"system_fingerprint": "123456789",\
"choices":[\
{\
"index":0,\
"delta":{\
"content":"hello, world"\
},\
"logprobs":null,\
"finish_reason":null\
}\
]\
}
""";
webServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseJson));
streamCompletion().hasNoErrors().hasEvent("""
{"completion":[{"delta":"hello, world"}]}""");
}
private InferenceEventsAssertion streamCompletion() throws Exception {
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
var model = OpenAiChatCompletionModelTests.createCompletionModel(getUrl(webServer), "org", "secret", "model", "user");
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
model,
null,
null,
null,
List.of("abc"),
true,
new HashMap<>(),
InputType.INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
return InferenceEventsAssertion.assertThat(listener.actionGet(TIMEOUT)).hasFinishedStream();
}
}
public void testInfer_StreamRequest_ErrorResponse() throws Exception {
String responseJson = """
{
"error": {
"message": "You didn't provide an API key...",
"type": "invalid_request_error",
"param": null,
"code": null
}
}""";
webServer.enqueue(new MockResponse().setResponseCode(401).setBody(responseJson));
var e = assertThrows(ElasticsearchStatusException.class, this::streamCompletion);
assertThat(e.status(), equalTo(RestStatus.UNAUTHORIZED));
assertThat(
e.getMessage(),
equalTo(
"Received an authentication error status code for request from inference entity id [id] status [401]. "
+ "Error message: [You didn't provide an API key...]"
)
);
}
public void testInfer_StreamRequestRetry() throws Exception {
webServer.enqueue(new MockResponse().setResponseCode(503).setBody("""
{
"error": {
"message": "server busy",
"type": "server_busy"
}
}"""));
webServer.enqueue(new MockResponse().setResponseCode(200).setBody("""
data: {\
"id":"12345",\
"object":"chat.completion.chunk",\
"created":123456789,\
"model":"gpt-4o-mini",\
"system_fingerprint": "123456789",\
"choices":[\
{\
"index":0,\
"delta":{\
"content":"hello, world"\
},\
"logprobs":null,\
"finish_reason":null\
}\
]\
}
"""));
streamCompletion().hasNoErrors().hasEvent("""
{"completion":[{"delta":"hello, world"}]}""");
}
public void testSupportsStreaming() throws IOException {
try (var service = new OpenAiService(mock(), createWithEmptySettings(mock()), mockClusterServiceEmpty())) {
assertThat(service.supportedStreamingTasks(), is(EnumSet.of(TaskType.COMPLETION, TaskType.CHAT_COMPLETION)));
assertFalse(service.canStream(TaskType.ANY));
}
}
public void testUpdateModelWithEmbeddingDetails_InvalidModelProvided() throws IOException {
try (var service = createOpenAiService()) {
var model = createCompletionModel(
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10)
);
assertThrows(
ElasticsearchStatusException.class,
() -> { service.updateModelWithEmbeddingDetails(model, randomNonNegativeInt()); }
);
}
}
public void testUpdateModelWithEmbeddingDetails_NullSimilarityInOriginalModel() throws IOException {
testUpdateModelWithEmbeddingDetails_Successful(null);
}
public void testUpdateModelWithEmbeddingDetails_NonNullSimilarityInOriginalModel() throws IOException {
testUpdateModelWithEmbeddingDetails_Successful(randomFrom(SimilarityMeasure.values()));
}
private void testUpdateModelWithEmbeddingDetails_Successful(SimilarityMeasure similarityMeasure) throws IOException {
try (var service = createOpenAiService()) {
var embeddingSize = randomNonNegativeInt();
var model = OpenAiEmbeddingsModelTests.createModel(
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
randomAlphaOfLength(10),
similarityMeasure,
randomNonNegativeInt(),
randomNonNegativeInt(),
randomBoolean()
);
Model updatedModel = service.updateModelWithEmbeddingDetails(model, embeddingSize);
SimilarityMeasure expectedSimilarityMeasure = similarityMeasure == null ? SimilarityMeasure.DOT_PRODUCT : similarityMeasure;
assertEquals(expectedSimilarityMeasure, updatedModel.getServiceSettings().similarity());
assertEquals(embeddingSize, updatedModel.getServiceSettings().dimensions().intValue());
}
}
public void testInfer_UnauthorisedResponse() throws IOException {
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
String responseJson = """
{
"error": {
"message": "Incorrect API key provided:",
"type": "invalid_request_error",
"param": null,
"code": "invalid_api_key"
}
}
""";
webServer.enqueue(new MockResponse().setResponseCode(401).setBody(responseJson));
var model = OpenAiEmbeddingsModelTests.createModel(getUrl(webServer), "org", "secret", "model", "user");
PlainActionFuture<InferenceServiceResults> listener = new PlainActionFuture<>();
service.infer(
model,
null,
null,
null,
List.of("abc"),
false,
new HashMap<>(),
InputType.INTERNAL_INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var error = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(error.getMessage(), containsString("Received an authentication error status code for request"));
assertThat(error.getMessage(), containsString("Error message: [Incorrect API key provided:]"));
assertThat(webServer.requests(), hasSize(1));
}
}
public void testMoveModelFromTaskToServiceSettings() {
var taskSettings = new HashMap<String, Object>();
taskSettings.put(ServiceFields.MODEL_ID, "model");
var serviceSettings = new HashMap<String, Object>();
OpenAiService.moveModelFromTaskToServiceSettings(taskSettings, serviceSettings);
assertThat(taskSettings.keySet(), empty());
assertEquals("model", serviceSettings.get(ServiceFields.MODEL_ID));
}
public void testMoveModelFromTaskToServiceSettings_OldID() {
var taskSettings = new HashMap<String, Object>();
taskSettings.put("model", "model");
var serviceSettings = new HashMap<String, Object>();
OpenAiService.moveModelFromTaskToServiceSettings(taskSettings, serviceSettings);
assertThat(taskSettings.keySet(), empty());
assertEquals("model", serviceSettings.get(ServiceFields.MODEL_ID));
}
public void testMoveModelFromTaskToServiceSettings_AlreadyMoved() {
var taskSettings = new HashMap<String, Object>();
var serviceSettings = new HashMap<String, Object>();
taskSettings.put(ServiceFields.MODEL_ID, "model");
OpenAiService.moveModelFromTaskToServiceSettings(taskSettings, serviceSettings);
assertThat(taskSettings.keySet(), empty());
assertEquals("model", serviceSettings.get(ServiceFields.MODEL_ID));
}
public void testChunkedInfer_ChunkingSettingsSet() throws IOException {
var model = OpenAiEmbeddingsModelTests.createModel(
getUrl(webServer),
"org",
"secret",
"model",
"user",
ChunkingSettingsTests.createRandomChunkingSettings()
);
testChunkedInfer(model);
}
public void testChunkedInfer_ChunkingSettingsNotSet() throws IOException {
var model = OpenAiEmbeddingsModelTests.createModel(getUrl(webServer), "org", "secret", "model", "user", (ChunkingSettings) null);
testChunkedInfer(model);
}
private void testChunkedInfer(OpenAiEmbeddingsModel model) throws IOException {
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
try (var service = new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty())) {
// response with 2 embeddings
String responseJson = """
{
"object": "list",
"data": [
{
"object": "embedding",
"index": 0,
"embedding": [
0.123,
-0.123
]
},
{
"object": "embedding",
"index": 1,
"embedding": [
0.223,
-0.223
]
}
],
"model": "text-embedding-ada-002-v2",
"usage": {
"prompt_tokens": 8,
"total_tokens": 8
}
}
""";
webServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseJson));
PlainActionFuture<List<ChunkedInference>> listener = new PlainActionFuture<>();
service.chunkedInfer(
model,
null,
List.of(new ChunkInferenceInput("a"), new ChunkInferenceInput("bb")),
new HashMap<>(),
InputType.INTERNAL_INGEST,
InferenceAction.Request.DEFAULT_TIMEOUT,
listener
);
var results = listener.actionGet(TIMEOUT);
assertThat(results, hasSize(2));
{
assertThat(results.get(0), CoreMatchers.instanceOf(ChunkedInferenceEmbedding.class));
var floatResult = (ChunkedInferenceEmbedding) results.get(0);
assertThat(floatResult.chunks(), hasSize(1));
assertEquals(new ChunkedInference.TextOffset(0, 1), floatResult.chunks().get(0).offset());
assertThat(floatResult.chunks().get(0).embedding(), Matchers.instanceOf(DenseEmbeddingFloatResults.Embedding.class));
assertTrue(
Arrays.equals(
new float[] { 0.123f, -0.123f },
((DenseEmbeddingFloatResults.Embedding) floatResult.chunks().get(0).embedding()).values()
)
);
}
{
assertThat(results.get(1), CoreMatchers.instanceOf(ChunkedInferenceEmbedding.class));
var floatResult = (ChunkedInferenceEmbedding) results.get(1);
assertThat(floatResult.chunks(), hasSize(1));
assertEquals(new ChunkedInference.TextOffset(0, 2), floatResult.chunks().get(0).offset());
assertThat(floatResult.chunks().get(0).embedding(), Matchers.instanceOf(DenseEmbeddingFloatResults.Embedding.class));
assertTrue(
Arrays.equals(
new float[] { 0.223f, -0.223f },
((DenseEmbeddingFloatResults.Embedding) floatResult.chunks().get(0).embedding()).values()
)
);
}
assertThat(webServer.requests(), hasSize(1));
assertNull(webServer.requests().get(0).getUri().getQuery());
assertThat(webServer.requests().get(0).getHeader(HttpHeaders.CONTENT_TYPE), equalTo(XContentType.JSON.mediaType()));
assertThat(webServer.requests().get(0).getHeader(HttpHeaders.AUTHORIZATION), equalTo("Bearer secret"));
assertThat(webServer.requests().get(0).getHeader(ORGANIZATION_HEADER), equalTo("org"));
var requestMap = entityAsMap(webServer.requests().get(0).getBody());
assertThat(requestMap.size(), Matchers.is(3));
assertThat(requestMap.get("input"), Matchers.is(List.of("a", "bb")));
assertThat(requestMap.get("model"), Matchers.is("model"));
assertThat(requestMap.get("user"), Matchers.is("user"));
}
}
@SuppressWarnings("checkstyle:LineLength")
public void testGetConfiguration() throws Exception {
try (var service = createOpenAiService()) {
String content = XContentHelper.stripWhitespace(
"""
{
"service": "openai",
"name": "OpenAI",
"task_types": ["text_embedding", "completion", "chat_completion"],
"configurations": {
"api_key": {
"description": "The OpenAI API authentication key. For more details about generating OpenAI API keys, refer to the https://platform.openai.com/account/api-keys.",
"label": "API Key",
"required": true,
"sensitive": true,
"updatable": true,
"type": "str",
"supported_task_types": ["text_embedding", "completion", "chat_completion"]
},
"url": {
"description": "The absolute URL of the external service to send requests to.",
"label": "URL",
"required": false,
"sensitive": false,
"updatable": false,
"type": "str",
"supported_task_types": ["text_embedding", "completion", "chat_completion"]
},
"dimensions": {
"description": "The number of dimensions the resulting embeddings should have. For more information refer to https://platform.openai.com/docs/api-reference/embeddings/create#embeddings-create-dimensions.",
"label": "Dimensions",
"required": false,
"sensitive": false,
"updatable": false,
"type": "int",
"supported_task_types": ["text_embedding"]
},
"organization_id": {
"description": "The unique identifier of your organization.",
"label": "Organization ID",
"required": false,
"sensitive": false,
"updatable": false,
"type": "str",
"supported_task_types": ["text_embedding", "completion", "chat_completion"]
},
"rate_limit.requests_per_minute": {
"description": "Default number of requests allowed per minute. For text_embedding is 3000. For completion is 500.",
"label": "Rate Limit",
"required": false,
"sensitive": false,
"updatable": false,
"type": "int",
"supported_task_types": ["text_embedding", "completion", "chat_completion"]
},
"model_id": {
"description": "The name of the model to use for the inference task.",
"label": "Model ID",
"required": true,
"sensitive": false,
"updatable": false,
"type": "str",
"supported_task_types": ["text_embedding", "completion", "chat_completion"]
},
"headers": {
"description": "Custom headers to include in the requests to OpenAI.",
"label": "Custom Headers",
"required": false,
"sensitive": false,
"updatable": true,
"type": "map",
"supported_task_types": ["text_embedding", "completion", "chat_completion"]
}
}
}
"""
);
InferenceServiceConfiguration configuration = InferenceServiceConfiguration.fromXContentBytes(
new BytesArray(content),
XContentType.JSON
);
boolean humanReadable = true;
BytesReference originalBytes = toShuffledXContent(configuration, XContentType.JSON, ToXContent.EMPTY_PARAMS, humanReadable);
InferenceServiceConfiguration serviceConfiguration = service.getConfiguration();
assertToXContentEquivalent(
originalBytes,
toXContent(serviceConfiguration, XContentType.JSON, humanReadable),
XContentType.JSON
);
}
}
private static OpenAiService createService(ThreadPool threadPool, HttpClientManager clientManager) {
var senderFactory = HttpRequestSenderTests.createSenderFactory(threadPool, clientManager);
return new OpenAiService(senderFactory, createWithEmptySettings(threadPool), mockClusterServiceEmpty());
}
private OpenAiService createOpenAiService() {
return new OpenAiService(mock(HttpRequestSender.Factory.class), createWithEmptySettings(threadPool), mockClusterServiceEmpty());
}
@Override
public InferenceService createInferenceService() {
return createOpenAiService();
}
}
| OpenAiServiceTests |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCallback.java | {
"start": 844,
"end": 1320
} | interface ____ code that operates on a JDBC Statement.
* Allows to execute any number of operations on a single Statement,
* for example a single {@code executeUpdate} call or repeated
* {@code executeUpdate} calls with varying SQL.
*
* <p>Used internally by JdbcTemplate, but also useful for application code.
*
* @author Juergen Hoeller
* @since 16.03.2004
* @param <T> the result type
* @see JdbcTemplate#execute(StatementCallback)
*/
@FunctionalInterface
public | for |
java | netty__netty | codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConstant.java | {
"start": 687,
"end": 1163
} | class ____ {
private MqttConstant() {
}
/**
* Default max bytes in message
*/
public static final int DEFAULT_MAX_BYTES_IN_MESSAGE = 8092;
/**
* min client id length
*/
public static final int MIN_CLIENT_ID_LENGTH = 1;
/**
* Default max client id length,In the mqtt3.1 protocol,
* the default maximum Client Identifier length is 23
*/
public static final int DEFAULT_MAX_CLIENT_ID_LENGTH = 23;
}
| MqttConstant |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson/SimpleSaml2ResponseAssertionAccessorMixin.java | {
"start": 1193,
"end": 1652
} | class ____ in serialize/deserialize {@link Saml2ResponseAssertion}.
*
* @author Sebastien Deleuze
* @author Josh Cummings
* @since 7.0
* @see Saml2JacksonModule
* @see SecurityJacksonModules
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties({ "authenticated" })
| helps |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/awt/FontTest.java | {
"start": 159,
"end": 551
} | class ____ extends TestCase {
public void test_color() throws Exception {
Font[] fonts = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (Font font : fonts) {
String text = JSON.toJSONString(font);
Font font2 = JSON.parseObject(text, Font.class);
Assert.assertEquals(font, font2);
}
}
}
| FontTest |
java | apache__hadoop | hadoop-tools/hadoop-gridmix/src/test/java/org/apache/hadoop/mapred/gridmix/TestLoadJob.java | {
"start": 1260,
"end": 2582
} | class ____ extends CommonJobTest {
public static final Logger LOG = getLogger(Gridmix.class);
static {
GenericTestUtils.setLogLevel(
getLogger("org.apache.hadoop.mapred.gridmix"), Level.DEBUG);
GenericTestUtils.setLogLevel(
getLogger(StressJobFactory.class), Level.DEBUG);
}
@BeforeAll
public static void init() throws IOException {
GridmixTestUtils.initCluster(TestLoadJob.class);
}
@AfterAll
public static void shutDown() throws IOException {
GridmixTestUtils.shutdownCluster();
}
/*
* test serial policy with LoadJob. Task should execute without exceptions
*/
@Test
@Timeout(value = 500)
public void testSerialSubmit() throws Exception {
policy = GridmixJobSubmissionPolicy.SERIAL;
LOG.info("Serial started at " + System.currentTimeMillis());
doSubmission(JobCreator.LOADJOB.name(), false);
LOG.info("Serial ended at " + System.currentTimeMillis());
}
/*
* test reply policy with LoadJob
*/
@Test
@Timeout(value = 500)
public void testReplaySubmit() throws Exception {
policy = GridmixJobSubmissionPolicy.REPLAY;
LOG.info(" Replay started at " + System.currentTimeMillis());
doSubmission(JobCreator.LOADJOB.name(), false);
LOG.info(" Replay ended at " + System.currentTimeMillis());
}
}
| TestLoadJob |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/DataTypeExtractorTest.java | {
"start": 41892,
"end": 42392
} | class ____ {
public Integer intField;
public boolean primitiveBooleanField;
public int primitiveIntField;
private String stringField;
public String getStringField() {
return stringField;
}
}
// --------------------------------------------------------------------------------------------
/** {@code getStringField()} is missing. */
@SuppressWarnings({"FieldCanBeLocal", "unused"})
public static | SimplePojoWithMissingSetter |
java | apache__flink | flink-core-api/src/main/java/org/apache/flink/api/common/state/AppendingState.java | {
"start": 915,
"end": 1719
} | interface ____ partitioned state that supports adding elements and inspecting the current
* state. Elements can either be kept in a buffer (list-like) or aggregated into one value.
*
* <p>The state is accessed and modified by user functions, and checkpointed consistently by the
* system as part of the distributed snapshots.
*
* <p>The state is only accessible by functions applied on a {@code KeyedStream}. The key is
* automatically supplied by the system, so the function always sees the value mapped to the key of
* the current element. That way, the system can handle stream and state partitioning consistently
* together.
*
* @param <IN> Type of the value that can be added to the state.
* @param <OUT> Type of the value that can be retrieved from the state.
*/
@PublicEvolving
public | for |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/core/ComparableVersion.java | {
"start": 2581,
"end": 2888
} | class ____ implements Comparable<ComparableVersion> {
private static final int MAX_INT_ITEM_LENGTH = 9;
private static final int MAX_LONG_ITEM_LENGTH = 18;
private String value;
@SuppressWarnings("NullAway.Init")
private @Nullable String canonical;
private ListItem items;
private | ComparableVersion |
java | apache__camel | components/camel-ssh/src/generated/java/org/apache/camel/component/ssh/SshEndpointUriFactory.java | {
"start": 513,
"end": 3894
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":host:port";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(41);
props.add("backoffErrorThreshold");
props.add("backoffIdleThreshold");
props.add("backoffMultiplier");
props.add("bridgeErrorHandler");
props.add("certResource");
props.add("certResourcePassword");
props.add("channelType");
props.add("ciphers");
props.add("clientBuilder");
props.add("compressions");
props.add("delay");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("failOnUnknownHost");
props.add("greedy");
props.add("host");
props.add("initialDelay");
props.add("kex");
props.add("keyPairProvider");
props.add("keyType");
props.add("knownHostsResource");
props.add("lazyStartProducer");
props.add("macs");
props.add("password");
props.add("pollCommand");
props.add("pollStrategy");
props.add("port");
props.add("repeatCount");
props.add("runLoggingLevel");
props.add("scheduledExecutorService");
props.add("scheduler");
props.add("schedulerProperties");
props.add("sendEmptyMessageWhenIdle");
props.add("shellPrompt");
props.add("signatures");
props.add("sleepForShellPrompt");
props.add("startScheduler");
props.add("timeUnit");
props.add("timeout");
props.add("useFixedDelay");
props.add("username");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(3);
secretProps.add("certResourcePassword");
secretProps.add("password");
secretProps.add("username");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
Map<String, String> prefixes = new HashMap<>(1);
prefixes.put("schedulerProperties", "scheduler.");
MULTI_VALUE_PREFIXES = Collections.unmodifiableMap(prefixes);
}
@Override
public boolean isEnabled(String scheme) {
return "ssh".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "host", null, true, copy);
uri = buildPathParameter(syntax, uri, "port", 22, false, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| SshEndpointUriFactory |
java | spring-projects__spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilter.java | {
"start": 5358,
"end": 15067
} | class ____ implements WebFilter {
private final ReactiveAuthenticationManager authenticationManager;
private final ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
private ServerAuthenticationSuccessHandler authenticationSuccessHandler;
private ServerAuthenticationConverter authenticationConverter;
private boolean defaultAuthenticationConverter;
private ServerAuthenticationFailureHandler authenticationFailureHandler;
private ServerWebExchangeMatcher requiresAuthenticationMatcher;
private ServerRequestCache requestCache = new WebSessionServerRequestCache();
private AnonymousAuthenticationToken anonymousToken = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
public OAuth2AuthorizationCodeGrantWebFilter(ReactiveAuthenticationManager authenticationManager,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.authenticationManager = authenticationManager;
this.authorizedClientRepository = authorizedClientRepository;
this.requiresAuthenticationMatcher = this::matchesAuthorizationResponse;
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter authenticationConverter = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
clientRegistrationRepository);
authenticationConverter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
this.authenticationConverter = authenticationConverter;
this.defaultAuthenticationConverter = true;
RedirectServerAuthenticationSuccessHandler authenticationSuccessHandler = new RedirectServerAuthenticationSuccessHandler();
authenticationSuccessHandler.setRequestCache(this.requestCache);
this.authenticationSuccessHandler = authenticationSuccessHandler;
this.authenticationFailureHandler = (webFilterExchange, exception) -> Mono.error(exception);
}
public OAuth2AuthorizationCodeGrantWebFilter(ReactiveAuthenticationManager authenticationManager,
ServerAuthenticationConverter authenticationConverter,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.authenticationManager = authenticationManager;
this.authorizedClientRepository = authorizedClientRepository;
this.requiresAuthenticationMatcher = this::matchesAuthorizationResponse;
this.authenticationConverter = authenticationConverter;
RedirectServerAuthenticationSuccessHandler authenticationSuccessHandler = new RedirectServerAuthenticationSuccessHandler();
authenticationSuccessHandler.setRequestCache(this.requestCache);
this.authenticationSuccessHandler = authenticationSuccessHandler;
this.authenticationFailureHandler = (webFilterExchange, exception) -> Mono.error(exception);
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s. The
* default is {@link WebSessionOAuth2ServerAuthorizationRequestRepository}.
* @param authorizationRequestRepository the repository used for storing
* {@link OAuth2AuthorizationRequest}'s
* @since 5.2
*/
public final void setAuthorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
updateDefaultAuthenticationConverter();
}
private void updateDefaultAuthenticationConverter() {
if (this.defaultAuthenticationConverter) {
((ServerOAuth2AuthorizationCodeAuthenticationTokenConverter) this.authenticationConverter)
.setAuthorizationRequestRepository(this.authorizationRequestRepository);
}
}
/**
* Sets the {@link ServerRequestCache} used for loading a previously saved request (if
* available) and replaying it after completing the processing of the OAuth 2.0
* Authorization Response.
* @param requestCache the cache used for loading a previously saved request (if
* available)
* @since 5.4
*/
public final void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
updateDefaultAuthenticationSuccessHandler();
}
private void updateDefaultAuthenticationSuccessHandler() {
((RedirectServerAuthenticationSuccessHandler) this.authenticationSuccessHandler)
.setRequestCache(this.requestCache);
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// @formatter:off
return this.requiresAuthenticationMatcher.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.flatMap((matchResult) -> this.authenticationConverter.convert(exchange)
.onErrorMap(OAuth2AuthorizationException.class,
(ex) -> new OAuth2AuthenticationException(ex.getError(), ex.getError().toString())
)
)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap((token) -> authenticate(exchange, chain, token))
.onErrorResume(AuthenticationException.class, (e) ->
this.authenticationFailureHandler.onAuthenticationFailure(new WebFilterExchange(exchange, chain), e)
);
// @formatter:on
}
private Mono<Void> authenticate(ServerWebExchange exchange, WebFilterChain chain, Authentication token) {
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
return this.authenticationManager.authenticate(token)
.onErrorMap(OAuth2AuthorizationException.class,
(ex) -> new OAuth2AuthenticationException(ex.getError(), ex.getError().toString()))
.switchIfEmpty(Mono
.defer(() -> Mono.error(new IllegalStateException("No provider found for " + token.getClass()))))
.flatMap((authentication) -> onAuthenticationSuccess(authentication, webFilterExchange))
.onErrorResume(AuthenticationException.class,
(e) -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
}
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), authenticationResult.getName(),
authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
// @formatter:off
return this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication)
.then(ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.defaultIfEmpty(this.anonymousToken)
.flatMap((principal) -> this.authorizedClientRepository
.saveAuthorizedClient(authorizedClient, principal, webFilterExchange.getExchange())
)
);
// @formatter:on
}
private Mono<ServerWebExchangeMatcher.MatchResult> matchesAuthorizationResponse(ServerWebExchange exchange) {
// @formatter:off
return Mono.just(exchange)
.filter((exch) ->
OAuth2AuthorizationResponseUtils.isAuthorizationResponse(exch.getRequest().getQueryParams())
)
.flatMap((exch) -> this.authorizationRequestRepository.loadAuthorizationRequest(exchange)
.flatMap((authorizationRequest) -> matchesRedirectUri(exch.getRequest().getURI(),
authorizationRequest.getRedirectUri()))
)
.switchIfEmpty(ServerWebExchangeMatcher.MatchResult.notMatch());
// @formatter:on
}
private static Mono<ServerWebExchangeMatcher.MatchResult> matchesRedirectUri(URI authorizationResponseUri,
String authorizationRequestRedirectUri) {
UriComponents requestUri = UriComponentsBuilder.fromUri(authorizationResponseUri).build();
UriComponents redirectUri = UriComponentsBuilder.fromUriString(authorizationRequestRedirectUri).build();
Set<Map.Entry<String, List<String>>> requestUriParameters = new LinkedHashSet<>(
requestUri.getQueryParams().entrySet());
Set<Map.Entry<String, List<String>>> redirectUriParameters = new LinkedHashSet<>(
redirectUri.getQueryParams().entrySet());
// Remove the additional request parameters (if any) from the authorization
// response (request)
// before doing an exact comparison with the authorizationRequest.getRedirectUri()
// parameters (if any)
requestUriParameters.retainAll(redirectUriParameters);
if (Objects.equals(requestUri.getScheme(), redirectUri.getScheme())
&& Objects.equals(requestUri.getUserInfo(), redirectUri.getUserInfo())
&& Objects.equals(requestUri.getHost(), redirectUri.getHost())
&& Objects.equals(requestUri.getPort(), redirectUri.getPort())
&& Objects.equals(requestUri.getPath(), redirectUri.getPath())
&& Objects.equals(requestUriParameters.toString(), redirectUriParameters.toString())) {
return ServerWebExchangeMatcher.MatchResult.match();
}
return ServerWebExchangeMatcher.MatchResult.notMatch();
}
}
| OAuth2AuthorizationCodeGrantWebFilter |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/AnonymousAWSCredentialsProvider.java | {
"start": 1790,
"end": 2178
} | class ____ implements AwsCredentialsProvider {
public static final String NAME
= "org.apache.hadoop.fs.s3a.AnonymousAWSCredentialsProvider";
public AwsCredentials resolveCredentials() {
return AnonymousCredentialsProvider.create().resolveCredentials();
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| AnonymousAWSCredentialsProvider |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/http/TestHttpFileSystem.java | {
"start": 1505,
"end": 3396
} | class ____ {
private final Configuration conf = new Configuration(false);
@BeforeEach
public void setUp() {
conf.set("fs.http.impl", HttpFileSystem.class.getCanonicalName());
}
@Test
public void testHttpFileSystem() throws IOException, URISyntaxException,
InterruptedException {
final String data = "foo";
try (MockWebServer server = new MockWebServer()) {
final MockResponse response = new MockResponse.Builder().body(data).build();
IntStream.rangeClosed(1, 3).forEach(i -> server.enqueue(response));
server.start();
URI uri = URI.create(String.format("http://%s:%d", server.getHostName(),
server.getPort()));
FileSystem fs = FileSystem.get(uri, conf);
assertSameData(fs, new Path(new URL(uri.toURL(), "/foo").toURI()), data);
assertSameData(fs, new Path("/foo"), data);
assertSameData(fs, new Path("foo"), data);
RecordedRequest req = server.takeRequest();
assertEquals("/foo", req.getUrl().encodedPath());
}
}
@Test
public void testHttpFileStatus() throws IOException, URISyntaxException, InterruptedException {
URI uri = new URI("http://www.example.com");
FileSystem fs = FileSystem.get(uri, conf);
URI expectedUri = uri.resolve("/foo");
assertEquals(fs.getFileStatus(new Path(new Path(uri), "/foo")).getPath().toUri(), expectedUri);
assertEquals(fs.getFileStatus(new Path("/foo")).getPath().toUri(), expectedUri);
assertEquals(fs.getFileStatus(new Path("foo")).getPath().toUri(), expectedUri);
}
private void assertSameData(FileSystem fs, Path path, String data) throws IOException {
try (InputStream is = fs.open(
path,
4096)) {
byte[] buf = new byte[data.length()];
IOUtils.readFully(is, buf, 0, buf.length);
assertEquals(data, new String(buf, StandardCharsets.UTF_8));
}
}
}
| TestHttpFileSystem |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/method/SingleConstructorMethodConfig.java | {
"start": 1114,
"end": 1521
} | class ____ {
private String name;
private boolean flag;
private final Object myService;
public Foo(Object myService) {
this.myService = myService;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFlag() {
return this.flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
}
| Foo |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/ConnectorConfig.java | {
"start": 40488,
"end": 43257
} | class ____
}
}
};
newDef.define(versionConfig, Type.STRING, defaultVersion, versionValidator, Importance.HIGH,
"Version of the '" + alias + "' " + aliasKind.toLowerCase(Locale.ENGLISH) + ".", group, orderInGroup++, Width.LONG,
baseClass.getSimpleName() + " version for " + alias,
List.of(), versionRecommender(typeConfig));
final ConfigDef configDef = populateConfigDef(typeConfig, versionConfig, plugins);
if (configDef == null) continue;
newDef.embed(prefix, group, orderInGroup, configDef);
}
}
/** Subclasses can add extra validation of the {@link #props}. */
protected void validateProps(String prefix) {
}
/**
* Populates the ConfigDef according to the configs returned from {@code configs()} method of class
* named in the {@code ...type} parameter of the {@code props}.
*/
protected ConfigDef populateConfigDef(String typeConfig, String versionConfig, Plugins plugins) {
final ConfigDef configDef = initialConfigDef();
try {
configDefsForClass(typeConfig, versionConfig, plugins)
.forEach(entry -> configDef.define(entry.getValue()));
} catch (ConfigException e) {
if (requireFullConfig) {
throw e;
} else {
return null;
}
}
return configDef;
}
/**
* Return a stream of configs provided by the {@code configs()} method of class
* named in the {@code ...type} parameter of the {@code props}.
*/
protected Stream<Map.Entry<String, ConfigDef.ConfigKey>> configDefsForClass(String typeConfig, String versionConfig, Plugins plugins) {
if (props.get(typeConfig) == null) {
throw new ConfigException(typeConfig, null, "Not a " + baseClass.getSimpleName());
}
return getConfigDefFromPlugin(typeConfig, props.get(typeConfig), props.get(versionConfig), plugins)
.configKeys().entrySet().stream();
}
/** Get an initial ConfigDef */
protected ConfigDef initialConfigDef() {
return new ConfigDef();
}
@SuppressWarnings("unchecked")
ConfigDef getConfigDefFromPlugin(String key, String pluginClass, String version, Plugins plugins) {
String connectorClass = props.get(CONNECTOR_CLASS_CONFIG);
if (pluginClass == null || connectorClass == null) {
// if transformation | configuration |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/DialectChecks.java | {
"start": 9388,
"end": 9620
} | class ____ implements DialectCheck {
public boolean isMatch(Dialect dialect) {
// TiDB db does not support subqueries for ON condition
return !( dialect instanceof TiDBDialect );
}
}
public static | SupportsSubqueryInOnClause |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/CheckReturnValue.java | {
"start": 14608,
"end": 17917
} | interface ____ enum).
*/
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
ImmutableList<String> presentAnnotations = presentCrvRelevantAnnotations(getSymbol(tree));
if (presentAnnotations.size() > 1) {
return buildDescription(tree)
.setMessage(conflictingAnnotations(presentAnnotations, "class"))
.build();
}
return Description.NO_MATCH;
}
private Description describeInvocationResultIgnored(
ExpressionTree invocationTree, String shortCall, MethodSymbol symbol, VisitorState state) {
String assignmentToUnused = "var unused = ...";
String message =
invocationResultIgnored(shortCall, assignmentToUnused, apiTrailer(symbol, state));
return buildDescription(invocationTree)
.addFix(fixAtDeclarationSite(symbol, state))
.addAllFixes(fixesAtCallSite(invocationTree, state))
.setMessage(message)
.build();
}
@Override
protected Description describeReturnValueIgnored(MethodInvocationTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
String shortCall = symbol.name + (tree.getArguments().isEmpty() ? "()" : "(...)");
return describeInvocationResultIgnored(tree, shortCall, symbol, state);
}
@Override
protected Description describeReturnValueIgnored(NewClassTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
String shortCall =
"new "
+ state.getSourceForNode(tree.getIdentifier())
+ (tree.getArguments().isEmpty() ? "()" : "(...)");
return describeInvocationResultIgnored(tree, shortCall, symbol, state);
}
@Override
protected Description describeReturnValueIgnored(MemberReferenceTree tree, VisitorState state) {
MethodSymbol symbol = getSymbol(tree);
Type type = state.getTypes().memberType(getType(tree.getQualifierExpression()), symbol);
String parensAndMaybeEllipsis = type.getParameterTypes().isEmpty() ? "()" : "(...)";
String shortCall =
(tree.getMode() == ReferenceMode.NEW
? "new " + state.getSourceForNode(tree.getQualifierExpression())
: tree.getName())
+ parensAndMaybeEllipsis;
String implementedMethod =
getType(tree).asElement().getSimpleName()
+ "."
+ state.getTypes().findDescriptorSymbol(getType(tree).asElement()).getSimpleName();
String methodReference = state.getSourceForNode(tree);
String assignmentLambda = parensAndMaybeEllipsis + " -> { var unused = ...; }";
String message =
methodReferenceIgnoresResult(
shortCall,
methodReference,
implementedMethod,
assignmentLambda,
apiTrailer(symbol, state));
return buildDescription(tree)
.setMessage(message)
.addFix(fixAtDeclarationSite(symbol, state))
.build();
}
private String apiTrailer(MethodSymbol symbol, VisitorState state) {
/*
* (isDirectlyOrIndirectlyLocal returns true for both local classes and anonymous classes.
* That's good for us.)
*/
if (enclosingClass(symbol).isDirectlyOrIndirectlyLocal()) {
/*
* We don't have a defined format for members of local and anonymous classes. After all, their
* generated | or |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/DelegationTokenRenewer.java | {
"start": 42575,
"end": 43275
} | class ____ {
private DelegationTokenRenewerEvent evt;
private Future<?> future;
DelegationTokenRenewerFuture(DelegationTokenRenewerEvent evt,
Future<?> future) {
this.future = future;
this.evt = evt;
}
public DelegationTokenRenewerEvent getEvt() {
return evt;
}
public void setEvt(DelegationTokenRenewerEvent evt) {
this.evt = evt;
}
public Future<?> getFuture() {
return future;
}
public void setFuture(Future<?> future) {
this.future = future;
}
}
// only for testing
protected ConcurrentMap<Token<?>, DelegationTokenToRenew> getAllTokens() {
return allTokens;
}
}
| DelegationTokenRenewerFuture |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/unit/DataSize.java | {
"start": 930,
"end": 1050
} | class ____ data size in terms of
* bytes and is immutable and thread-safe.
*
* <p>The terms and units used in this | models |
java | hibernate__hibernate-orm | hibernate-agroal/src/test/java/org/hibernate/test/agroal/AgroalSkipAutoCommitTest.java | {
"start": 1119,
"end": 3100
} | class ____ {
private static final PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider();
private static final SettingProvider.Provider<PreparedStatementSpyConnectionProvider> connectionProviderProvider = () -> connectionProvider;
@Test
@ServiceRegistry(
settings = {
@Setting( name = CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT, value = "true" ),
@Setting( name = AUTOCOMMIT, value = "false" )
},
settingProviders = @SettingProvider(settingName = CONNECTION_PROVIDER, provider = ConnectionProviderProvider.class)
)
@DomainModel( annotatedClasses = City.class )
@SessionFactory
public void test(SessionFactoryScope factoryScope) {
factoryScope.getSessionFactory();
connectionProvider.clear();
factoryScope.inTransaction( (session) -> {
City city = new City();
city.setId( 1L );
city.setName( "Cluj-Napoca" );
session.persist( city );
assertThat( connectionProvider.getAcquiredConnections().isEmpty() ).isTrue();
assertThat( connectionProvider.getReleasedConnections().isEmpty() ).isTrue();
} );
verifyConnections();
connectionProvider.clear();
factoryScope.inTransaction( (session) -> {
City city = session.find( City.class, 1L );
assertThat( city.getName() ).isEqualTo( "Cluj-Napoca" );
} );
verifyConnections();
}
private void verifyConnections() {
assertTrue( connectionProvider.getAcquiredConnections().isEmpty() );
List<Connection> connections = connectionProvider.getReleasedConnections();
assertEquals( 1, connections.size() );
try {
List<Object[]> setAutoCommitCalls = connectionProvider.spyContext.getCalls(
Connection.class.getMethod( "setAutoCommit", boolean.class ),
connections.get( 0 )
);
assertTrue( setAutoCommitCalls.isEmpty(), "setAutoCommit should never be called" );
}
catch (NoSuchMethodException e) {
throw new RuntimeException( e );
}
}
@Entity(name = "City" )
public static | AgroalSkipAutoCommitTest |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/file/FileProps.java | {
"start": 682,
"end": 1340
} | interface ____ {
/**
* The date the file was created
*/
long creationTime();
/**
* The date the file was last accessed
*/
long lastAccessTime();
/**
* The date the file was last modified
*/
long lastModifiedTime();
/**
* Is the file a directory?
*/
boolean isDirectory();
/**
* Is the file some other type? (I.e. not a directory, regular file or symbolic link)
*/
boolean isOther();
/**
* Is the file a regular file?
*/
boolean isRegularFile();
/**
* Is the file a symbolic link?
*/
boolean isSymbolicLink();
/**
* The size of the file, in bytes
*/
long size();
}
| FileProps |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/engine/LuceneChangesSnapshot.java | {
"start": 1635,
"end": 14630
} | class ____ extends SearchBasedChangesSnapshot {
private long lastSeenSeqNo;
private int skippedOperations;
private final boolean singleConsumer;
private int docIndex = 0;
private int maxDocIndex;
private final ParallelArray parallelArray;
private int storedFieldsReaderOrd = -1;
private StoredFieldsReader storedFieldsReader = null;
private final SyntheticVectorsLoader syntheticVectorPatchLoader;
private SyntheticVectorsLoader.Leaf syntheticVectorPatchLoaderLeaf;
private final Thread creationThread; // for assertion
/**
* Creates a new "translog" snapshot from Lucene for reading operations whose seq# in the specified range.
*
* @param mapperService the mapper service for this index
* @param engineSearcher the internal engine searcher which will be taken over if the snapshot is opened successfully
* @param searchBatchSize the number of documents should be returned by each search
* @param fromSeqNo the min requesting seq# - inclusive
* @param toSeqNo the maximum requesting seq# - inclusive
* @param requiredFullRange if true, the snapshot will strictly check for the existence of operations between fromSeqNo and toSeqNo
* @param singleConsumer true if the snapshot is accessed by a single thread that creates the snapshot
* @param accessStats true if the stats of the snapshot can be accessed via {@link #totalOperations()}
* @param indexVersionCreated the version on which this index was created
*/
public LuceneChangesSnapshot(
MapperService mapperService,
Engine.Searcher engineSearcher,
int searchBatchSize,
long fromSeqNo,
long toSeqNo,
boolean requiredFullRange,
boolean singleConsumer,
boolean accessStats,
IndexVersion indexVersionCreated
) throws IOException {
super(mapperService, engineSearcher, searchBatchSize, fromSeqNo, toSeqNo, requiredFullRange, accessStats, indexVersionCreated);
this.creationThread = Assertions.ENABLED ? Thread.currentThread() : null;
this.singleConsumer = singleConsumer;
this.parallelArray = new ParallelArray(this.searchBatchSize);
this.lastSeenSeqNo = fromSeqNo - 1;
final TopDocs topDocs = nextTopDocs();
this.maxDocIndex = topDocs.scoreDocs.length;
this.syntheticVectorPatchLoader = mapperService.mappingLookup().getMapping().syntheticVectorsLoader(null);
fillParallelArray(topDocs.scoreDocs, parallelArray);
}
@Override
public void close() throws IOException {
assert assertAccessingThread();
super.close();
}
@Override
public int totalOperations() {
assert assertAccessingThread();
return super.totalOperations();
}
@Override
public int skippedOperations() {
assert assertAccessingThread();
return skippedOperations;
}
@Override
protected Translog.Operation nextOperation() throws IOException {
assert assertAccessingThread();
Translog.Operation op = null;
for (int idx = nextDocIndex(); idx != -1; idx = nextDocIndex()) {
op = readDocAsOp(idx);
if (op != null) {
break;
}
}
return op;
}
private boolean assertAccessingThread() {
assert singleConsumer == false || creationThread == Thread.currentThread()
: "created by [" + creationThread + "] != current thread [" + Thread.currentThread() + "]";
assert Transports.assertNotTransportThread("reading changes snapshot may involve slow IO");
return true;
}
private int nextDocIndex() throws IOException {
// we have processed all docs in the current search - fetch the next batch
if (docIndex == maxDocIndex && docIndex > 0) {
var scoreDocs = nextTopDocs().scoreDocs;
fillParallelArray(scoreDocs, parallelArray);
docIndex = 0;
maxDocIndex = scoreDocs.length;
}
if (docIndex < maxDocIndex) {
int idx = docIndex;
docIndex++;
return idx;
}
return -1;
}
private void fillParallelArray(ScoreDoc[] scoreDocs, ParallelArray parallelArray) throws IOException {
if (scoreDocs.length > 0) {
for (int i = 0; i < scoreDocs.length; i++) {
scoreDocs[i].shardIndex = i;
}
parallelArray.useSequentialStoredFieldsReader = singleConsumer && scoreDocs.length >= 10 && hasSequentialAccess(scoreDocs);
if (parallelArray.useSequentialStoredFieldsReader == false) {
storedFieldsReaderOrd = -1;
storedFieldsReader = null;
}
// for better loading performance we sort the array by docID and
// then visit all leaves in order.
if (parallelArray.useSequentialStoredFieldsReader == false) {
ArrayUtil.introSort(scoreDocs, Comparator.comparingInt(i -> i.doc));
}
int docBase = -1;
int maxDoc = 0;
int readerIndex = 0;
CombinedDocValues combinedDocValues = null;
LeafReaderContext leaf = null;
for (ScoreDoc scoreDoc : scoreDocs) {
if (scoreDoc.doc >= docBase + maxDoc) {
do {
leaf = leaves().get(readerIndex++);
docBase = leaf.docBase;
maxDoc = leaf.reader().maxDoc();
} while (scoreDoc.doc >= docBase + maxDoc);
combinedDocValues = new CombinedDocValues(leaf.reader());
}
final int segmentDocID = scoreDoc.doc - docBase;
final int index = scoreDoc.shardIndex;
parallelArray.leafReaderContexts[index] = leaf;
parallelArray.docID[index] = scoreDoc.doc;
parallelArray.seqNo[index] = combinedDocValues.docSeqNo(segmentDocID);
parallelArray.primaryTerm[index] = combinedDocValues.docPrimaryTerm(segmentDocID);
parallelArray.version[index] = combinedDocValues.docVersion(segmentDocID);
parallelArray.isTombStone[index] = combinedDocValues.isTombstone(segmentDocID);
parallelArray.hasRecoverySource[index] = combinedDocValues.hasRecoverySource(segmentDocID);
}
// now sort back based on the shardIndex. we use this to store the previous index
if (parallelArray.useSequentialStoredFieldsReader == false) {
ArrayUtil.introSort(scoreDocs, Comparator.comparingInt(i -> i.shardIndex));
}
}
}
private static boolean hasSequentialAccess(ScoreDoc[] scoreDocs) {
for (int i = 0; i < scoreDocs.length - 1; i++) {
if (scoreDocs[i].doc + 1 != scoreDocs[i + 1].doc) {
return false;
}
}
return true;
}
static int countOperations(Engine.Searcher engineSearcher, IndexSettings indexSettings, long fromSeqNo, long toSeqNo)
throws IOException {
if (fromSeqNo < 0 || toSeqNo < 0 || fromSeqNo > toSeqNo) {
throw new IllegalArgumentException("Invalid range; from_seqno [" + fromSeqNo + "], to_seqno [" + toSeqNo + "]");
}
return newIndexSearcher(engineSearcher).count(rangeQuery(indexSettings, fromSeqNo, toSeqNo));
}
private Translog.Operation readDocAsOp(int docIndex) throws IOException {
final LeafReaderContext leaf = parallelArray.leafReaderContexts[docIndex];
final int segmentDocID = parallelArray.docID[docIndex] - leaf.docBase;
final long primaryTerm = parallelArray.primaryTerm[docIndex];
assert primaryTerm > 0 : "nested child document must be excluded";
final long seqNo = parallelArray.seqNo[docIndex];
// Only pick the first seen seq#
if (seqNo == lastSeenSeqNo) {
skippedOperations++;
return null;
}
final long version = parallelArray.version[docIndex];
final String sourceField = parallelArray.hasRecoverySource[docIndex]
? SourceFieldMapper.RECOVERY_SOURCE_NAME
: SourceFieldMapper.NAME;
final FieldsVisitor fields = new FieldsVisitor(true, sourceField);
if (parallelArray.useSequentialStoredFieldsReader) {
if (storedFieldsReaderOrd != leaf.ord) {
if (leaf.reader() instanceof SequentialStoredFieldsLeafReader) {
storedFieldsReader = ((SequentialStoredFieldsLeafReader) leaf.reader()).getSequentialStoredFieldsReader();
storedFieldsReaderOrd = leaf.ord;
setNextSyntheticFieldsReader(leaf);
} else {
storedFieldsReader = null;
storedFieldsReaderOrd = -1;
}
}
}
if (storedFieldsReader != null) {
assert singleConsumer : "Sequential access optimization must not be enabled for multiple consumers";
assert parallelArray.useSequentialStoredFieldsReader;
assert storedFieldsReaderOrd == leaf.ord : storedFieldsReaderOrd + " != " + leaf.ord;
storedFieldsReader.document(segmentDocID, fields);
} else {
setNextSyntheticFieldsReader(leaf);
leaf.reader().storedFields().document(segmentDocID, fields);
}
final BytesReference source = fields.source() != null && fields.source().length() > 0
? addSyntheticFields(Source.fromBytes(fields.source()), segmentDocID).internalSourceRef()
: fields.source();
final Translog.Operation op;
final boolean isTombstone = parallelArray.isTombStone[docIndex];
if (isTombstone && fields.id() == null) {
op = new Translog.NoOp(seqNo, primaryTerm, fields.source().utf8ToString());
assert version == 1L : "Noop tombstone should have version 1L; actual version [" + version + "]";
assert assertDocSoftDeleted(leaf.reader(), segmentDocID) : "Noop but soft_deletes field is not set [" + op + "]";
} else {
final String id = fields.id();
if (isTombstone) {
op = new Translog.Delete(id, seqNo, primaryTerm, version);
assert assertDocSoftDeleted(leaf.reader(), segmentDocID) : "Delete op but soft_deletes field is not set [" + op + "]";
} else {
if (source == null) {
// TODO: Callers should ask for the range that source should be retained. Thus we should always
// check for the existence source once we make peer-recovery to send ops after the local checkpoint.
if (requiredFullRange) {
throw new MissingHistoryOperationsException(
"source not found for seqno=" + seqNo + " from_seqno=" + fromSeqNo + " to_seqno=" + toSeqNo
);
} else {
skippedOperations++;
return null;
}
}
// TODO: pass the latest timestamp from engine.
final long autoGeneratedIdTimestamp = -1;
op = new Translog.Index(id, seqNo, primaryTerm, version, source, fields.routing(), autoGeneratedIdTimestamp);
}
}
assert fromSeqNo <= op.seqNo() && op.seqNo() <= toSeqNo && lastSeenSeqNo < op.seqNo()
: "Unexpected operation; "
+ "last_seen_seqno ["
+ lastSeenSeqNo
+ "], from_seqno ["
+ fromSeqNo
+ "], to_seqno ["
+ toSeqNo
+ "], op ["
+ op
+ "]";
lastSeenSeqNo = op.seqNo();
return op;
}
@Override
protected void setNextSyntheticFieldsReader(LeafReaderContext context) throws IOException {
super.setNextSyntheticFieldsReader(context);
if (syntheticVectorPatchLoader != null) {
syntheticVectorPatchLoaderLeaf = syntheticVectorPatchLoader.leaf(context);
}
}
@Override
protected Source addSyntheticFields(Source source, int segmentDocID) throws IOException {
if (syntheticVectorPatchLoaderLeaf == null) {
return super.addSyntheticFields(source, segmentDocID);
}
List<SourceLoader.SyntheticVectorPatch> patches = new ArrayList<>();
syntheticVectorPatchLoaderLeaf.load(segmentDocID, patches);
if (patches.size() == 0) {
return super.addSyntheticFields(source, segmentDocID);
}
var newSource = SourceLoader.applySyntheticVectors(source, patches);
return super.addSyntheticFields(newSource, segmentDocID);
}
private static final | LuceneChangesSnapshot |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/components/dynamic/OneToOneEntity.java | {
"start": 219,
"end": 1293
} | class ____ {
private Long id;
private String note;
public OneToOneEntity() {
}
public OneToOneEntity(Long id, String note) {
this.id = id;
this.note = note;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !( o instanceof OneToOneEntity ) ) {
return false;
}
OneToOneEntity that = (OneToOneEntity) o;
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
if ( note != null ? !note.equals( that.note ) : that.note != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + ( note != null ? note.hashCode() : 0 );
return result;
}
@Override
public String toString() {
return "OneToOneEntity{" +
"id=" + id +
", note='" + note + '\'' +
'}';
}
}
| OneToOneEntity |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/FloatCastTest.java | {
"start": 1673,
"end": 2437
} | class ____ {
{
int x = (int) 0.9f + 42;
float y = (int) 0.9f - 0.9f;
x = ((int) 0.9f) * 42;
y = (int) (0.9f * 0.9f);
String s = (int) 0.9f + "";
boolean b = (int) 0.9f > 1;
long c = (long) Math.ceil(10.0d / 2) * 2;
long f = (long) Math.floor(10.0d / 2) * 2;
long g = (long) Math.signum(10.0d / 2) * 2;
long r = (long) Math.rint(10.0d / 2) * 2;
}
}
""")
.doTest();
}
@Test
public void pow() {
CompilationTestHelper.newInstance(FloatCast.class, getClass())
.addSourceLines(
"Test.java",
"""
| Test |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/data/AggregateMetricDoubleArrayBlock.java | {
"start": 728,
"end": 12487
} | class ____ extends AbstractNonThreadSafeRefCounted implements AggregateMetricDoubleBlock {
public static final TransportVersion WRITE_TYPED_BLOCK = TransportVersion.fromName("aggregate_metric_double_typed_block");
private final DoubleBlock minBlock;
private final DoubleBlock maxBlock;
private final DoubleBlock sumBlock;
private final IntBlock countBlock;
private final int positionCount;
public AggregateMetricDoubleArrayBlock(DoubleBlock minBlock, DoubleBlock maxBlock, DoubleBlock sumBlock, IntBlock countBlock) {
this.minBlock = minBlock;
this.maxBlock = maxBlock;
this.sumBlock = sumBlock;
this.countBlock = countBlock;
this.positionCount = minBlock.getPositionCount();
for (Block b : List.of(minBlock, maxBlock, sumBlock, countBlock)) {
if (b.getPositionCount() != positionCount) {
assert false : "expected positionCount=" + positionCount + " but was " + b;
throw new IllegalArgumentException("expected positionCount=" + positionCount + " but was " + b);
}
if (b.isReleased()) {
assert false : "can't build aggregate_metric_double block out of released blocks but [" + b + "] was released";
throw new IllegalArgumentException(
"can't build aggregate_metric_double block out of released blocks but [" + b + "] was released"
);
}
}
}
public static AggregateMetricDoubleArrayBlock fromCompositeBlock(CompositeBlock block) {
assert block.getBlockCount() == 4
: "Can't make AggregateMetricDoubleBlock out of CompositeBlock with " + block.getBlockCount() + " blocks";
DoubleBlock min = block.getBlock(AggregateMetricDoubleBlockBuilder.Metric.MIN.getIndex());
DoubleBlock max = block.getBlock(AggregateMetricDoubleBlockBuilder.Metric.MAX.getIndex());
DoubleBlock sum = block.getBlock(AggregateMetricDoubleBlockBuilder.Metric.SUM.getIndex());
IntBlock count = block.getBlock(AggregateMetricDoubleBlockBuilder.Metric.COUNT.getIndex());
return new AggregateMetricDoubleArrayBlock(min, max, sum, count);
}
public CompositeBlock asCompositeBlock() {
final Block[] blocks = new Block[4];
blocks[AggregateMetricDoubleBlockBuilder.Metric.MIN.getIndex()] = minBlock;
blocks[AggregateMetricDoubleBlockBuilder.Metric.MAX.getIndex()] = maxBlock;
blocks[AggregateMetricDoubleBlockBuilder.Metric.SUM.getIndex()] = sumBlock;
blocks[AggregateMetricDoubleBlockBuilder.Metric.COUNT.getIndex()] = countBlock;
return new CompositeBlock(blocks);
}
@Override
protected void closeInternal() {
Releasables.close(minBlock, maxBlock, sumBlock, countBlock);
}
@Override
public Vector asVector() {
return null;
}
@Override
public int getTotalValueCount() {
int totalValueCount = 0;
for (Block b : List.of(minBlock, maxBlock, sumBlock, countBlock)) {
totalValueCount += b.getTotalValueCount();
}
return totalValueCount;
}
@Override
public int getPositionCount() {
return positionCount;
}
@Override
public int getFirstValueIndex(int position) {
return minBlock.getFirstValueIndex(position);
}
@Override
public int getValueCount(int position) {
int max = 0;
for (Block b : List.of(minBlock, maxBlock, sumBlock, countBlock)) {
max = Math.max(max, b.getValueCount(position));
}
return max;
}
@Override
public ElementType elementType() {
return ElementType.AGGREGATE_METRIC_DOUBLE;
}
@Override
public BlockFactory blockFactory() {
return minBlock.blockFactory();
}
@Override
public void allowPassingToDifferentDriver() {
for (Block block : List.of(minBlock, maxBlock, sumBlock, countBlock)) {
block.allowPassingToDifferentDriver();
}
}
@Override
public boolean isNull(int position) {
for (Block block : List.of(minBlock, maxBlock, sumBlock, countBlock)) {
if (block.isNull(position) == false) {
return false;
}
}
return true;
}
@Override
public boolean mayHaveNulls() {
return Stream.of(minBlock, maxBlock, sumBlock, countBlock).anyMatch(Block::mayHaveNulls);
}
@Override
public boolean areAllValuesNull() {
return Stream.of(minBlock, maxBlock, sumBlock, countBlock).allMatch(Block::areAllValuesNull);
}
@Override
public boolean mayHaveMultivaluedFields() {
return Stream.of(minBlock, maxBlock, sumBlock, countBlock).anyMatch(Block::mayHaveMultivaluedFields);
}
@Override
public boolean doesHaveMultivaluedFields() {
if (Stream.of(minBlock, maxBlock, sumBlock, countBlock).noneMatch(Block::mayHaveMultivaluedFields)) {
return false;
}
return Stream.of(minBlock, maxBlock, sumBlock, countBlock).anyMatch(Block::doesHaveMultivaluedFields);
}
@Override
public AggregateMetricDoubleBlock filter(int... positions) {
AggregateMetricDoubleArrayBlock result = null;
DoubleBlock newMinBlock = null;
DoubleBlock newMaxBlock = null;
DoubleBlock newSumBlock = null;
IntBlock newCountBlock = null;
try {
newMinBlock = minBlock.filter(positions);
newMaxBlock = maxBlock.filter(positions);
newSumBlock = sumBlock.filter(positions);
newCountBlock = countBlock.filter(positions);
result = new AggregateMetricDoubleArrayBlock(newMinBlock, newMaxBlock, newSumBlock, newCountBlock);
return result;
} finally {
if (result == null) {
Releasables.close(newMinBlock, newMaxBlock, newSumBlock, newCountBlock);
}
}
}
@Override
public AggregateMetricDoubleBlock keepMask(BooleanVector mask) {
AggregateMetricDoubleArrayBlock result = null;
DoubleBlock newMinBlock = null;
DoubleBlock newMaxBlock = null;
DoubleBlock newSumBlock = null;
IntBlock newCountBlock = null;
try {
newMinBlock = minBlock.keepMask(mask);
newMaxBlock = maxBlock.keepMask(mask);
newSumBlock = sumBlock.keepMask(mask);
newCountBlock = countBlock.keepMask(mask);
result = new AggregateMetricDoubleArrayBlock(newMinBlock, newMaxBlock, newSumBlock, newCountBlock);
return result;
} finally {
if (result == null) {
Releasables.close(newMinBlock, newMaxBlock, newSumBlock, newCountBlock);
}
}
}
@Override
public Block deepCopy(BlockFactory blockFactory) {
AggregateMetricDoubleArrayBlock result = null;
DoubleBlock newMinBlock = null;
DoubleBlock newMaxBlock = null;
DoubleBlock newSumBlock = null;
IntBlock newCountBlock = null;
try {
newMinBlock = minBlock.deepCopy(blockFactory);
newMaxBlock = maxBlock.deepCopy(blockFactory);
newSumBlock = sumBlock.deepCopy(blockFactory);
newCountBlock = countBlock.deepCopy(blockFactory);
result = new AggregateMetricDoubleArrayBlock(newMinBlock, newMaxBlock, newSumBlock, newCountBlock);
return result;
} finally {
if (result == null) {
Releasables.close(newMinBlock, newMaxBlock, newSumBlock, newCountBlock);
}
}
}
@Override
public ReleasableIterator<? extends AggregateMetricDoubleBlock> lookup(IntBlock positions, ByteSizeValue targetBlockSize) {
// TODO: support
throw new UnsupportedOperationException("can't lookup values from AggregateMetricDoubleBlock");
}
@Override
public MvOrdering mvOrdering() {
// TODO: determine based on sub-blocks
return MvOrdering.UNORDERED;
}
@Override
public AggregateMetricDoubleBlock expand() {
this.incRef();
return this;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
for (Block block : List.of(minBlock, maxBlock, sumBlock, countBlock)) {
if (out.getTransportVersion().supports(WRITE_TYPED_BLOCK)) {
Block.writeTypedBlock(block, out);
} else {
block.writeTo(out);
}
}
}
public static Block readFrom(StreamInput in) throws IOException {
boolean success = false;
DoubleBlock minBlock = null;
DoubleBlock maxBlock = null;
DoubleBlock sumBlock = null;
IntBlock countBlock = null;
BlockStreamInput blockStreamInput = (BlockStreamInput) in;
try {
if (in.getTransportVersion().supports(WRITE_TYPED_BLOCK)) {
minBlock = (DoubleBlock) Block.readTypedBlock(blockStreamInput);
maxBlock = (DoubleBlock) Block.readTypedBlock(blockStreamInput);
sumBlock = (DoubleBlock) Block.readTypedBlock(blockStreamInput);
countBlock = (IntBlock) Block.readTypedBlock(blockStreamInput);
} else {
minBlock = DoubleBlock.readFrom(blockStreamInput);
maxBlock = DoubleBlock.readFrom(blockStreamInput);
sumBlock = DoubleBlock.readFrom(blockStreamInput);
countBlock = IntBlock.readFrom(blockStreamInput);
}
AggregateMetricDoubleArrayBlock result = new AggregateMetricDoubleArrayBlock(minBlock, maxBlock, sumBlock, countBlock);
success = true;
return result;
} finally {
if (success == false) {
Releasables.close(minBlock, maxBlock, sumBlock, countBlock);
}
}
}
@Override
public long ramBytesUsed() {
return minBlock.ramBytesUsed() + maxBlock.ramBytesUsed() + sumBlock.ramBytesUsed() + countBlock.ramBytesUsed();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AggregateMetricDoubleBlock that) {
return AggregateMetricDoubleBlock.equals(this, that);
}
return false;
}
@Override
public int hashCode() {
return AggregateMetricDoubleBlock.hash(this);
}
public DoubleBlock minBlock() {
return minBlock;
}
public DoubleBlock maxBlock() {
return maxBlock;
}
public DoubleBlock sumBlock() {
return sumBlock;
}
public IntBlock countBlock() {
return countBlock;
}
public Block getMetricBlock(int index) {
if (index == AggregateMetricDoubleBlockBuilder.Metric.MIN.getIndex()) {
return minBlock;
}
if (index == AggregateMetricDoubleBlockBuilder.Metric.MAX.getIndex()) {
return maxBlock;
}
if (index == AggregateMetricDoubleBlockBuilder.Metric.SUM.getIndex()) {
return sumBlock;
}
if (index == AggregateMetricDoubleBlockBuilder.Metric.COUNT.getIndex()) {
return countBlock;
}
throw new UnsupportedOperationException("Received an index (" + index + ") outside of range for AggregateMetricDoubleBlock.");
}
@Override
public String toString() {
String valuesString = Stream.of(AggregateMetricDoubleBlockBuilder.Metric.values())
.map(metric -> metric.getLabel() + "=" + getMetricBlock(metric.getIndex()))
.collect(Collectors.joining(", ", "[", "]"));
return getClass().getSimpleName() + valuesString;
}
}
| AggregateMetricDoubleArrayBlock |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/embeddedid/withoutinheritance/XmlPerson.java | {
"start": 207,
"end": 274
} | class ____ {
private PersonId id;
private String address;
}
| XmlPerson |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelBeanDump.java | {
"start": 8713,
"end": 8834
} | class ____ {
String name;
String type;
Object value;
String configValue;
}
}
| PropertyRow |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/character/CharacterAssert_isLessThanOrEqualTo_char_Test.java | {
"start": 912,
"end": 1274
} | class ____ extends CharacterAssertBaseTest {
@Override
protected CharacterAssert invoke_api_method() {
return assertions.isLessThanOrEqualTo('b');
}
@Override
protected void verify_internal_effects() {
verify(characters).assertLessThanOrEqualTo(getInfo(assertions), getActual(assertions), 'b');
}
}
| CharacterAssert_isLessThanOrEqualTo_char_Test |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java | {
"start": 146177,
"end": 148255
} | class ____ implements WebSession {
private final WebSession session;
OidcSessionRegistryWebSession(WebSession session) {
this.session = session;
}
@Override
public String getId() {
return this.session.getId();
}
@Override
public Map<String, Object> getAttributes() {
return this.session.getAttributes();
}
@Override
public void start() {
this.session.start();
}
@Override
public boolean isStarted() {
return this.session.isStarted();
}
@Override
public Mono<Void> changeSessionId() {
String currentId = this.session.getId();
return this.session.changeSessionId()
.then(Mono.defer(() -> OidcSessionRegistryWebFilter.this.oidcSessionRegistry
.removeSessionInformation(currentId)
.flatMap((information) -> {
information = information.withSessionId(this.session.getId());
return OidcSessionRegistryWebFilter.this.oidcSessionRegistry
.saveSessionInformation(information);
})));
}
@Override
public Mono<Void> invalidate() {
String currentId = this.session.getId();
return this.session.invalidate()
.then(Mono.defer(() -> OidcSessionRegistryWebFilter.this.oidcSessionRegistry
.removeSessionInformation(currentId)
.then(Mono.empty())));
}
@Override
public Mono<Void> save() {
return this.session.save();
}
@Override
public boolean isExpired() {
return this.session.isExpired();
}
@Override
public Instant getCreationTime() {
return this.session.getCreationTime();
}
@Override
public Instant getLastAccessTime() {
return this.session.getLastAccessTime();
}
@Override
public void setMaxIdleTime(Duration maxIdleTime) {
this.session.setMaxIdleTime(maxIdleTime);
}
@Override
public Duration getMaxIdleTime() {
return this.session.getMaxIdleTime();
}
}
}
}
static final | OidcSessionRegistryWebSession |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/util/accessor/ElementAccessor.java | {
"start": 576,
"end": 2055
} | class ____ implements Accessor {
private final Element element;
private final String name;
private final AccessorType accessorType;
private final TypeMirror accessedType;
public ElementAccessor(VariableElement variableElement, TypeMirror accessedType) {
this( variableElement, accessedType, AccessorType.FIELD );
}
public ElementAccessor(Element element, TypeMirror accessedType, String name) {
this.element = element;
this.name = name;
this.accessedType = accessedType;
this.accessorType = AccessorType.PARAMETER;
}
public ElementAccessor(Element element, TypeMirror accessedType, AccessorType accessorType) {
this.element = element;
this.accessedType = accessedType;
this.accessorType = accessorType;
this.name = null;
}
@Override
public TypeMirror getAccessedType() {
return accessedType != null ? accessedType : element.asType();
}
@Override
public String getSimpleName() {
return name != null ? name : element.getSimpleName().toString();
}
@Override
public Set<Modifier> getModifiers() {
return element.getModifiers();
}
@Override
public Element getElement() {
return element;
}
@Override
public String toString() {
return element.toString();
}
@Override
public AccessorType getAccessorType() {
return accessorType;
}
}
| ElementAccessor |
java | google__guava | android/guava-testlib/src/com/google/common/testing/TearDownStack.java | {
"start": 1248,
"end": 1355
} | class ____ thread-safe.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@GwtCompatible
@NullMarked
public | is |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/associations/JoinFormulaTest.java | {
"start": 3381,
"end": 4189
} | class ____ {
@Id
private Integer id;
private String name;
//Getters and setters, equals and hashCode methods omitted for brevity
//end::associations-JoinFormula-example[]
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof Country) ) {
return false;
}
Country country = (Country) o;
return Objects.equals( getId(), country.getId() );
}
@Override
public int hashCode() {
return Objects.hash( getId() );
}
//tag::associations-JoinFormula-example[]
}
//end::associations-JoinFormula-example[]
}
| Country |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/typeinfo/TypeHint.java | {
"start": 1089,
"end": 1529
} | class ____ describing generic types. It can be used to obtain a type information via:
*
* <pre>{@code
* TypeInformation<Tuple2<String, Long>> info = TypeInformation.of(new TypeHint<Tuple2<String, Long>>(){});
* }</pre>
*
* <p>or
*
* <pre>{@code
* TypeInformation<Tuple2<String, Long>> info = new TypeHint<Tuple2<String, Long>>(){}.getTypeInfo();
* }</pre>
*
* @param <T> The type information to hint.
*/
@Public
public abstract | for |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/windowing/sessionwindows/SessionGeneratorConfiguration.java | {
"start": 1123,
"end": 2224
} | class ____<K, E> {
private final SessionConfiguration<K, E> sessionConfiguration;
private final GeneratorConfiguration generatorConfiguration;
public SessionGeneratorConfiguration(
SessionConfiguration<K, E> sessionConfiguration,
GeneratorConfiguration generatorConfiguration) {
Preconditions.checkNotNull(sessionConfiguration);
Preconditions.checkNotNull(generatorConfiguration);
this.sessionConfiguration = sessionConfiguration;
this.generatorConfiguration = generatorConfiguration;
}
public SessionConfiguration<K, E> getSessionConfiguration() {
return sessionConfiguration;
}
public GeneratorConfiguration getGeneratorConfiguration() {
return generatorConfiguration;
}
@Override
public String toString() {
return "SessionGeneratorConfiguration{"
+ "sessionConfiguration="
+ sessionConfiguration
+ ", generatorConfiguration="
+ generatorConfiguration
+ '}';
}
}
| SessionGeneratorConfiguration |
java | alibaba__nacos | istio/src/main/java/com/alibaba/nacos/istio/api/ApiConstants.java | {
"start": 692,
"end": 2194
} | class ____ {
/**
* Default api prefix of any type of google protocol buffer.
*/
public static final String API_TYPE_PREFIX = "type.googleapis.com/";
/**
* Istio crd type url for mcp over xds
* TODO Support other Istio crd, such as gateway, vs, dr and so on.
*/
public static final String SERVICE_ENTRY_PROTO_PACKAGE = "networking.istio.io/v1alpha3/ServiceEntry";
public static final String MESH_CONFIG_PROTO_PACKAGE = "core/v1alpha1/MeshConfig";
/**
* Istio crd type url for mcp
*/
public static final String MCP_PREFIX = "istio/";
public static final String SERVICE_ENTRY_COLLECTION = MCP_PREFIX + "networking/v1alpha3/serviceentries";
/**
* Istio crd type url of api.
*/
public static final String MCP_RESOURCE_PROTO = API_TYPE_PREFIX + "istio.mcp.v1alpha1.Resource";
public static final String SERVICE_ENTRY_PROTO = API_TYPE_PREFIX + "istio.networking.v1alpha3.ServiceEntry";
/**
* Standard xds type url
* TODO Support lds, rds and sds
*/
public static final String CLUSTER_TYPE = API_TYPE_PREFIX + "envoy.config.cluster.v3.Cluster";
public static final String ENDPOINT_TYPE = API_TYPE_PREFIX + "envoy.config.endpoint.v3.ClusterLoadAssignment";
public static final String LISTENER_TYPE = API_TYPE_PREFIX + "envoy.config.listener.v3.Listener";
public static final String ROUTE_TYPE = API_TYPE_PREFIX + "envoy.config.route.v3.RouteConfiguration";
}
| ApiConstants |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/support/StaticMessageSource.java | {
"start": 1200,
"end": 3281
} | class ____ extends AbstractMessageSource {
private final Map<String, Map<Locale, MessageHolder>> messageMap = new HashMap<>();
@Override
protected @Nullable String resolveCodeWithoutArguments(String code, Locale locale) {
Map<Locale, MessageHolder> localeMap = this.messageMap.get(code);
if (localeMap == null) {
return null;
}
MessageHolder holder = localeMap.get(locale);
if (holder == null) {
return null;
}
return holder.getMessage();
}
@Override
protected @Nullable MessageFormat resolveCode(String code, Locale locale) {
Map<Locale, MessageHolder> localeMap = this.messageMap.get(code);
if (localeMap == null) {
return null;
}
MessageHolder holder = localeMap.get(locale);
if (holder == null) {
return null;
}
return holder.getMessageFormat();
}
/**
* Associate the given message with the given code.
* @param code the lookup code
* @param locale the locale that the message should be found within
* @param msg the message associated with this lookup code
*/
public void addMessage(String code, Locale locale, String msg) {
Assert.notNull(code, "Code must not be null");
Assert.notNull(locale, "Locale must not be null");
Assert.notNull(msg, "Message must not be null");
this.messageMap.computeIfAbsent(code, key -> new HashMap<>(4)).put(locale, new MessageHolder(msg, locale));
if (logger.isDebugEnabled()) {
logger.debug("Added message [" + msg + "] for code [" + code + "] and Locale [" + locale + "]");
}
}
/**
* Associate the given message values with the given keys as codes.
* @param messages the messages to register, with messages codes
* as keys and message texts as values
* @param locale the locale that the messages should be found within
*/
public void addMessages(Map<String, String> messages, Locale locale) {
Assert.notNull(messages, "Messages Map must not be null");
messages.forEach((code, msg) -> addMessage(code, locale, msg));
}
@Override
public String toString() {
return getClass().getName() + ": " + this.messageMap;
}
private | StaticMessageSource |
java | apache__camel | components/camel-keycloak/src/test/java/org/apache/camel/component/keycloak/security/KeycloakTokenIntrospectionIT.java | {
"start": 3143,
"end": 32679
} | class ____ extends CamelTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(KeycloakTokenIntrospectionIT.class);
@RegisterExtension
static KeycloakService keycloakService = KeycloakServiceFactory.createService();
// Test data - use unique names to avoid conflicts
private static final String TEST_REALM_NAME = "introspection-realm-" + UUID.randomUUID().toString().substring(0, 8);
private static final String TEST_CLIENT_ID = "introspection-client-" + UUID.randomUUID().toString().substring(0, 8);
private static String TEST_CLIENT_SECRET = null; // Will be generated
// Test users
private static final String ADMIN_USER = "admin-user-" + UUID.randomUUID().toString().substring(0, 8);
private static final String ADMIN_PASSWORD = "admin123";
private static final String USER_USER = "test-user-" + UUID.randomUUID().toString().substring(0, 8);
private static final String USER_PASSWORD = "user123";
// Test roles
private static final String ADMIN_ROLE = "admin-role";
private static final String USER_ROLE = "user";
private static Keycloak keycloakAdminClient;
private static RealmResource realmResource;
@BeforeAll
static void setupKeycloakRealm() {
LOG.info("Setting up Keycloak realm for token introspection tests");
// Create Keycloak admin client
keycloakAdminClient = KeycloakBuilder.builder()
.serverUrl(keycloakService.getKeycloakServerUrl())
.realm(keycloakService.getKeycloakRealm())
.username(keycloakService.getKeycloakUsername())
.password(keycloakService.getKeycloakPassword())
.clientId("admin-cli")
.build();
// Create test realm
createTestRealm();
// Get realm resource for further operations
realmResource = keycloakAdminClient.realm(TEST_REALM_NAME);
// Create test client
createTestClient();
// Create test roles
createTestRoles();
// Create test users
createTestUsers();
// Assign roles to users
assignRolesToUsers();
LOG.info("Keycloak realm setup completed: {}", TEST_REALM_NAME);
}
@AfterAll
static void cleanupKeycloakRealm() {
if (keycloakAdminClient != null) {
try {
// Delete the test realm
keycloakAdminClient.realm(TEST_REALM_NAME).remove();
LOG.info("Deleted test realm: {}", TEST_REALM_NAME);
} catch (Exception e) {
LOG.warn("Failed to cleanup test realm: {}", e.getMessage());
} finally {
keycloakAdminClient.close();
}
}
}
private static void createTestRealm() {
RealmRepresentation realm = new RealmRepresentation();
realm.setId(TEST_REALM_NAME);
realm.setRealm(TEST_REALM_NAME);
realm.setDisplayName("Token Introspection Test Realm");
realm.setEnabled(true);
realm.setAccessTokenLifespan(3600); // 1 hour
keycloakAdminClient.realms().create(realm);
LOG.info("Created test realm: {}", TEST_REALM_NAME);
}
private static void createTestClient() {
ClientRepresentation client = new ClientRepresentation();
client.setClientId(TEST_CLIENT_ID);
client.setName("Introspection Test Client");
client.setDescription("Client for token introspection testing");
client.setEnabled(true);
client.setPublicClient(false); // Confidential client with secret (required for introspection)
client.setDirectAccessGrantsEnabled(true);
client.setServiceAccountsEnabled(true); // Enable service account for introspection
client.setStandardFlowEnabled(true);
Response response = realmResource.clients().create(client);
if (response.getStatus() == 201) {
String clientId = extractIdFromLocationHeader(response);
ClientResource clientResource = realmResource.clients().get(clientId);
// Get client secret
TEST_CLIENT_SECRET = clientResource.getSecret().getValue();
LOG.info("Created test client: {} with secret for introspection", TEST_CLIENT_ID);
} else {
throw new RuntimeException("Failed to create client. Status: " + response.getStatus());
}
response.close();
}
private static void createTestRoles() {
// Create admin role
RoleRepresentation adminRole = new RoleRepresentation();
adminRole.setName(ADMIN_ROLE);
adminRole.setDescription("Administrator role for introspection tests");
realmResource.roles().create(adminRole);
// Create user role
RoleRepresentation userRole = new RoleRepresentation();
userRole.setName(USER_ROLE);
userRole.setDescription("User role for introspection tests");
realmResource.roles().create(userRole);
LOG.info("Created test roles: {}, {}", ADMIN_ROLE, USER_ROLE);
}
private static void createTestUsers() {
// Create admin user
createUser(ADMIN_USER, ADMIN_PASSWORD, "Admin", "User", ADMIN_USER + "@test.com");
// Create normal user
createUser(USER_USER, USER_PASSWORD, "Test", "User", USER_USER + "@test.com");
LOG.info("Created test users: {}, {}", ADMIN_USER, USER_USER);
}
private static void createUser(String username, String password, String firstName, String lastName, String email) {
UserRepresentation user = new UserRepresentation();
user.setUsername(username);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setEnabled(true);
user.setEmailVerified(true);
Response response = realmResource.users().create(user);
if (response.getStatus() == 201) {
String userId = extractIdFromLocationHeader(response);
UserResource userResource = realmResource.users().get(userId);
// Set password
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue(password);
credential.setTemporary(false);
userResource.resetPassword(credential);
LOG.info("Created user: {} with password", username);
} else {
throw new RuntimeException("Failed to create user: " + username + ". Status: " + response.getStatus());
}
response.close();
}
private static void assignRolesToUsers() {
// Assign admin role to admin user
assignRoleToUser(ADMIN_USER, ADMIN_ROLE);
// Assign user role to normal user
assignRoleToUser(USER_USER, USER_ROLE);
LOG.info("Assigned roles to users: {} -> {}, {} -> {}", ADMIN_USER, ADMIN_ROLE, USER_USER, USER_ROLE);
}
private static void assignRoleToUser(String username, String roleName) {
List<UserRepresentation> users = realmResource.users().search(username);
if (!users.isEmpty()) {
UserResource userResource = realmResource.users().get(users.get(0).getId());
RoleRepresentation role = realmResource.roles().get(roleName).toRepresentation();
userResource.roles().realmLevel().add(Arrays.asList(role));
LOG.info("Assigned role {} to user {}", roleName, username);
} else {
throw new RuntimeException("User not found: " + username);
}
}
private static String extractIdFromLocationHeader(Response response) {
String location = response.getHeaderString("Location");
return location.substring(location.lastIndexOf('/') + 1);
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// Policy with token introspection enabled
KeycloakSecurityPolicy introspectionPolicy = new KeycloakSecurityPolicy();
introspectionPolicy.setServerUrl(keycloakService.getKeycloakServerUrl());
introspectionPolicy.setRealm(TEST_REALM_NAME);
introspectionPolicy.setClientId(TEST_CLIENT_ID);
introspectionPolicy.setClientSecret(TEST_CLIENT_SECRET);
introspectionPolicy.setRequiredRoles(Arrays.asList(ADMIN_ROLE));
introspectionPolicy.setUseTokenIntrospection(true);
introspectionPolicy.setIntrospectionCacheEnabled(true);
introspectionPolicy.setIntrospectionCacheTtl(60);
from("direct:introspection-protected")
.policy(introspectionPolicy)
.transform().constant("Introspection access granted")
.to("mock:introspection-result");
// Policy with local JWT validation (for comparison)
KeycloakSecurityPolicy localJwtPolicy = new KeycloakSecurityPolicy();
localJwtPolicy.setServerUrl(keycloakService.getKeycloakServerUrl());
localJwtPolicy.setRealm(TEST_REALM_NAME);
localJwtPolicy.setClientId(TEST_CLIENT_ID);
localJwtPolicy.setClientSecret(TEST_CLIENT_SECRET);
localJwtPolicy.setRequiredRoles(Arrays.asList(ADMIN_ROLE));
localJwtPolicy.setUseTokenIntrospection(false); // Use local JWT parsing
from("direct:local-jwt-protected")
.policy(localJwtPolicy)
.transform().constant("Local JWT access granted")
.to("mock:local-jwt-result");
// Policy with introspection but no cache
KeycloakSecurityPolicy noCachePolicy = new KeycloakSecurityPolicy();
noCachePolicy.setServerUrl(keycloakService.getKeycloakServerUrl());
noCachePolicy.setRealm(TEST_REALM_NAME);
noCachePolicy.setClientId(TEST_CLIENT_ID);
noCachePolicy.setClientSecret(TEST_CLIENT_SECRET);
noCachePolicy.setRequiredRoles(Arrays.asList(ADMIN_ROLE));
noCachePolicy.setUseTokenIntrospection(true);
noCachePolicy.setIntrospectionCacheEnabled(false);
from("direct:introspection-no-cache")
.policy(noCachePolicy)
.transform().constant("No cache access granted")
.to("mock:no-cache-result");
// Policy with Caffeine cache
KeycloakSecurityPolicy caffeinePolicy = new KeycloakSecurityPolicy();
caffeinePolicy.setServerUrl(keycloakService.getKeycloakServerUrl());
caffeinePolicy.setRealm(TEST_REALM_NAME);
caffeinePolicy.setClientId(TEST_CLIENT_ID);
caffeinePolicy.setClientSecret(TEST_CLIENT_SECRET);
caffeinePolicy.setRequiredRoles(Arrays.asList(ADMIN_ROLE));
caffeinePolicy.setUseTokenIntrospection(true);
caffeinePolicy.setIntrospectionCacheEnabled(true);
caffeinePolicy.setIntrospectionCacheTtl(60);
// Use Caffeine cache by creating custom cache
TokenCache customCaffeineCache = new CaffeineTokenCache(60, 100, true);
// Store for later retrieval in tests
context.getRegistry().bind("caffeineCache", customCaffeineCache);
from("direct:caffeine-protected")
.policy(caffeinePolicy)
.transform().constant("Caffeine cache access granted")
.to("mock:caffeine-result");
}
};
}
@Test
@Order(1)
void testKeycloakServiceConfiguration() {
// Verify that the test-infra service is properly configured
assertNotNull(keycloakService.getKeycloakServerUrl());
assertNotNull(TEST_CLIENT_SECRET);
LOG.info("Testing Keycloak at: {} with realm: {}", keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME);
}
@Test
@Order(10)
void testTokenIntrospectionWithValidToken() throws Exception {
// Get a valid access token
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
// Create introspector
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
true, 60);
// Introspect the token
KeycloakTokenIntrospector.IntrospectionResult result = introspector.introspect(adminToken);
assertNotNull(result);
assertTrue(result.isActive(), "Token should be active");
assertNotNull(result.getSubject());
assertNotNull(result.getClientId());
assertNotNull(result.getUsername());
LOG.info("Introspection result: active={}, subject={}, username={}",
result.isActive(), result.getSubject(), result.getUsername());
introspector.close();
}
@Test
@Order(11)
void testTokenIntrospectionWithInvalidToken() throws Exception {
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
true, 60);
// Introspect an invalid token
KeycloakTokenIntrospector.IntrospectionResult result = introspector.introspect("invalid-token");
assertNotNull(result);
assertFalse(result.isActive(), "Invalid token should not be active");
introspector.close();
}
@Test
@Order(12)
void testTokenIntrospectionCaching() throws Exception {
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
true, 60);
// First introspection
long start1 = System.currentTimeMillis();
KeycloakTokenIntrospector.IntrospectionResult result1 = introspector.introspect(adminToken);
long duration1 = System.currentTimeMillis() - start1;
// Second introspection (should be cached)
long start2 = System.currentTimeMillis();
KeycloakTokenIntrospector.IntrospectionResult result2 = introspector.introspect(adminToken);
long duration2 = System.currentTimeMillis() - start2;
assertTrue(result1.isActive());
assertTrue(result2.isActive());
// Cached result should be significantly faster
LOG.info("First introspection: {}ms, Cached introspection: {}ms", duration1, duration2);
assertTrue(duration2 <= duration1, "Cached introspection should be faster or equal");
introspector.close();
}
@Test
@Order(20)
void testSecurityPolicyWithIntrospection() {
// Test with valid admin token using introspection
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
String result = template.requestBodyAndHeader("direct:introspection-protected", "test message",
KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, adminToken, String.class);
assertEquals("Introspection access granted", result);
}
@Test
@Order(21)
void testSecurityPolicyWithIntrospectionInvalidToken() {
// Test that invalid tokens are rejected via introspection
CamelExecutionException ex = assertThrows(CamelExecutionException.class, () -> {
template.sendBodyAndHeader("direct:introspection-protected", "test message",
KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, "invalid-token");
});
assertTrue(ex.getCause() instanceof CamelAuthorizationException);
assertTrue(ex.getCause().getMessage().contains("not active") ||
ex.getCause().getMessage().contains("Failed to validate"));
}
@Test
@Order(22)
void testSecurityPolicyIntrospectionVsLocalValidation() {
// Compare introspection-based validation with local JWT parsing
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
// Test introspection-based route
long start1 = System.currentTimeMillis();
String result1 = template.requestBodyAndHeader("direct:introspection-protected", "test message",
KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, adminToken, String.class);
long duration1 = System.currentTimeMillis() - start1;
// Test local JWT parsing route
long start2 = System.currentTimeMillis();
String result2 = template.requestBodyAndHeader("direct:local-jwt-protected", "test message",
KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, adminToken, String.class);
long duration2 = System.currentTimeMillis() - start2;
assertEquals("Introspection access granted", result1);
assertEquals("Local JWT access granted", result2);
LOG.info("Introspection validation: {}ms, Local JWT validation: {}ms", duration1, duration2);
}
@Test
@Order(23)
void testSecurityPolicyIntrospectionWithoutCache() {
// Test introspection without caching
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
String result = template.requestBodyAndHeader("direct:introspection-no-cache", "test message",
KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, adminToken, String.class);
assertEquals("No cache access granted", result);
}
@Test
@Order(24)
void testSecurityPolicyIntrospectionUserWithoutAdminRole() {
// Test that user token without admin role is rejected
String userToken = getAccessToken(USER_USER, USER_PASSWORD);
assertNotNull(userToken);
CamelExecutionException ex = assertThrows(CamelExecutionException.class, () -> {
template.sendBodyAndHeader("direct:introspection-protected", "test message",
KeycloakSecurityConstants.ACCESS_TOKEN_HEADER, userToken);
});
assertTrue(ex.getCause() instanceof CamelAuthorizationException);
}
@Test
@Order(25)
void testRoleExtractionFromIntrospection() throws Exception {
// Test that roles are correctly extracted from introspection result
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
true, 60);
KeycloakTokenIntrospector.IntrospectionResult result = introspector.introspect(adminToken);
Set<String> roles = KeycloakSecurityHelper.extractRolesFromIntrospection(result, TEST_REALM_NAME, TEST_CLIENT_ID);
assertNotNull(roles);
LOG.info("Roles extracted from introspection: {}", roles);
// Verify that admin role is present
assertTrue(roles.contains(ADMIN_ROLE) || roles.size() > 0,
"Should extract roles from introspection result");
introspector.close();
}
@Test
@Order(26)
void testPermissionsExtractionFromIntrospection() throws Exception {
// Test that permissions/scopes are correctly extracted from introspection result
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
true, 60);
KeycloakTokenIntrospector.IntrospectionResult result = introspector.introspect(adminToken);
Set<String> permissions = KeycloakSecurityHelper.extractPermissionsFromIntrospection(result);
assertNotNull(permissions);
LOG.info("Permissions/scopes extracted from introspection: {}", permissions);
introspector.close();
}
@Test
@Order(30)
void testCaffeineCacheWithValidToken() throws Exception {
// Test Caffeine cache implementation with valid token
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
// Create introspector with Caffeine cache
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TokenCacheType.CAFFEINE,
60, // TTL in seconds
100, // max size
true // record stats
);
// First introspection
KeycloakTokenIntrospector.IntrospectionResult result1 = introspector.introspect(adminToken);
assertTrue(result1.isActive());
// Second introspection (should be cached)
KeycloakTokenIntrospector.IntrospectionResult result2 = introspector.introspect(adminToken);
assertTrue(result2.isActive());
// Verify cache statistics
TokenCache.CacheStats stats = introspector.getCacheStats();
assertNotNull(stats);
assertTrue(stats.getHitCount() >= 1, "Should have at least one cache hit");
LOG.info("Caffeine cache stats: {}", stats.toString());
// Verify cache size
long cacheSize = introspector.getCacheSize();
assertTrue(cacheSize > 0, "Cache should contain at least one entry");
LOG.info("Caffeine cache size: {}", cacheSize);
introspector.close();
}
@Test
@Order(31)
void testCaffeineCachePerformance() throws Exception {
// Test that Caffeine cache improves performance
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TokenCacheType.CAFFEINE,
120, // 2 minute TTL
1000, // max 1000 entries
true // record stats
);
// First introspection - will hit Keycloak
long start1 = System.currentTimeMillis();
KeycloakTokenIntrospector.IntrospectionResult result1 = introspector.introspect(adminToken);
long duration1 = System.currentTimeMillis() - start1;
// Second introspection - should hit cache
long start2 = System.currentTimeMillis();
KeycloakTokenIntrospector.IntrospectionResult result2 = introspector.introspect(adminToken);
long duration2 = System.currentTimeMillis() - start2;
assertTrue(result1.isActive());
assertTrue(result2.isActive());
// Cached result should be faster
LOG.info("First introspection (Keycloak): {}ms, Cached introspection (Caffeine): {}ms", duration1, duration2);
assertTrue(duration2 <= duration1, "Cached introspection should be faster or equal");
// Verify cache statistics
TokenCache.CacheStats stats = introspector.getCacheStats();
assertNotNull(stats);
assertEquals(1, stats.getHitCount(), "Should have exactly one cache hit");
assertEquals(1, stats.getMissCount(), "Should have exactly one cache miss");
assertEquals(0.5, stats.getHitRate(), 0.01, "Hit rate should be 50%");
LOG.info("Caffeine cache performance stats: {}", stats);
introspector.close();
}
@Test
@Order(32)
void testCaffeineCacheEviction() throws Exception {
// Test that Caffeine cache evicts entries based on size
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
// Create cache with very small max size
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TokenCacheType.CAFFEINE,
300, // 5 minute TTL
2, // max 2 entries (small for testing eviction)
true // record stats
);
// Introspect the same token multiple times
for (int i = 0; i < 5; i++) {
introspector.introspect(adminToken);
}
// Verify cache stats
TokenCache.CacheStats stats = introspector.getCacheStats();
assertNotNull(stats);
assertTrue(stats.getHitCount() > 0, "Should have cache hits");
LOG.info("Cache stats after multiple introspections: {}", stats);
// Verify cache size is within limits
long size = introspector.getCacheSize();
assertTrue(size <= 2, "Cache size should not exceed max size of 2");
introspector.close();
}
@Test
@Order(33)
void testCaffeineCacheWithMultipleTokens() throws Exception {
// Test Caffeine cache with multiple different tokens
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
String userToken = getAccessToken(USER_USER, USER_PASSWORD);
assertNotNull(adminToken);
assertNotNull(userToken);
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TokenCacheType.CAFFEINE,
60, // 1 minute TTL
100, // max 100 entries
true // record stats
);
// Introspect both tokens
introspector.introspect(adminToken);
introspector.introspect(userToken);
// Verify both are cached
long cacheSize = introspector.getCacheSize();
assertEquals(2, cacheSize, "Cache should contain both tokens");
// Introspect again (should hit cache)
introspector.introspect(adminToken);
introspector.introspect(userToken);
TokenCache.CacheStats stats = introspector.getCacheStats();
assertNotNull(stats);
assertEquals(2, stats.getHitCount(), "Should have 2 cache hits");
assertEquals(2, stats.getMissCount(), "Should have 2 cache misses");
LOG.info("Cache stats with multiple tokens: {}", stats);
introspector.close();
}
@Test
@Order(34)
void testCaffeineCacheClearOperation() throws Exception {
// Test that cache can be cleared
String adminToken = getAccessToken(ADMIN_USER, ADMIN_PASSWORD);
assertNotNull(adminToken);
KeycloakTokenIntrospector introspector = new KeycloakTokenIntrospector(
keycloakService.getKeycloakServerUrl(), TEST_REALM_NAME, TEST_CLIENT_ID, TEST_CLIENT_SECRET,
TokenCacheType.CAFFEINE,
60, 100, true);
// Introspect and cache
introspector.introspect(adminToken);
assertTrue(introspector.getCacheSize() > 0, "Cache should have entries");
// Clear cache
introspector.clearCache();
assertEquals(0, introspector.getCacheSize(), "Cache should be empty after clear");
// Introspect again (should miss cache)
introspector.introspect(adminToken);
TokenCache.CacheStats stats = introspector.getCacheStats();
assertNotNull(stats);
// After clear, stats should be reset
LOG.info("Cache stats after clear: {}", stats);
introspector.close();
}
/**
* Helper method to obtain access token from Keycloak using resource owner password flow.
*/
private String getAccessToken(String username, String password) {
try (Client client = ClientBuilder.newClient()) {
String tokenUrl = keycloakService.getKeycloakServerUrl() + "/realms/" + TEST_REALM_NAME
+ "/protocol/openid-connect/token";
Form form = new Form()
.param("grant_type", "password")
.param("client_id", TEST_CLIENT_ID)
.param("client_secret", TEST_CLIENT_SECRET)
.param("username", username)
.param("password", password);
try (Response response = client.target(tokenUrl)
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED))) {
if (response.getStatus() == 200) {
@SuppressWarnings("unchecked")
Map<String, Object> tokenResponse = response.readEntity(Map.class);
return (String) tokenResponse.get("access_token");
} else {
throw new RuntimeException("Failed to obtain access token. Status: " + response.getStatus());
}
}
} catch (Exception e) {
throw new RuntimeException("Error obtaining access token", e);
}
}
}
| KeycloakTokenIntrospectionIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.