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 | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/DirectFileRolloverStrategy.java | {
"start": 908,
"end": 1049
} | interface ____ {
String getCurrentFileName(final RollingFileManager manager);
void clearCurrentFileName();
}
| DirectFileRolloverStrategy |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestReplication.java | {
"start": 3330,
"end": 6709
} | class ____ {
private static final long seed = 0xDEADBEEFL;
private static final int blockSize = 8192;
private static final int fileSize = 16384;
private static final String racks[] = new String[] {
"/d1/r1", "/d1/r1", "/d1/r2", "/d1/r2", "/d1/r2", "/d2/r3", "/d2/r3"
};
private static final int numDatanodes = racks.length;
private static final Logger LOG = LoggerFactory.getLogger(
TestReplication.class);
/* check if there are at least two nodes are on the same rack */
private void checkFile(FileSystem fileSys, Path name, int repl)
throws IOException {
Configuration conf = fileSys.getConf();
ClientProtocol namenode = NameNodeProxies.createProxy(conf, fileSys.getUri(),
ClientProtocol.class).getProxy();
waitForBlockReplication(name.toString(), namenode,
Math.min(numDatanodes, repl), -1);
LocatedBlocks locations = namenode.getBlockLocations(name.toString(),0,
Long.MAX_VALUE);
FileStatus stat = fileSys.getFileStatus(name);
BlockLocation[] blockLocations = fileSys.getFileBlockLocations(stat,0L,
Long.MAX_VALUE);
// verify that rack locations match
assertTrue(blockLocations.length == locations.locatedBlockCount());
for (int i = 0; i < blockLocations.length; i++) {
LocatedBlock blk = locations.get(i);
DatanodeInfo[] datanodes = blk.getLocations();
String[] topologyPaths = blockLocations[i].getTopologyPaths();
assertTrue(topologyPaths.length == datanodes.length);
for (int j = 0; j < topologyPaths.length; j++) {
boolean found = false;
for (int k = 0; k < racks.length; k++) {
if (topologyPaths[j].startsWith(racks[k])) {
found = true;
break;
}
}
assertTrue(found);
}
}
boolean isOnSameRack = true, isNotOnSameRack = true;
for (LocatedBlock blk : locations.getLocatedBlocks()) {
DatanodeInfo[] datanodes = blk.getLocations();
if (datanodes.length <= 1) break;
if (datanodes.length == 2) {
isNotOnSameRack = !(datanodes[0].getNetworkLocation().equals(
datanodes[1].getNetworkLocation()));
break;
}
isOnSameRack = false;
isNotOnSameRack = false;
for (int i = 0; i < datanodes.length-1; i++) {
LOG.info("datanode "+ i + ": "+ datanodes[i]);
boolean onRack = false;
for( int j=i+1; j<datanodes.length; j++) {
if( datanodes[i].getNetworkLocation().equals(
datanodes[j].getNetworkLocation()) ) {
onRack = true;
}
}
if (onRack) {
isOnSameRack = true;
}
if (!onRack) {
isNotOnSameRack = true;
}
if (isOnSameRack && isNotOnSameRack) break;
}
if (!isOnSameRack || !isNotOnSameRack) break;
}
assertTrue(isOnSameRack);
assertTrue(isNotOnSameRack);
}
private void cleanupFile(FileSystem fileSys, Path name) throws IOException {
assertTrue(fileSys.exists(name));
fileSys.delete(name, true);
assertTrue(!fileSys.exists(name));
}
private static | TestReplication |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/clientproxy/delegatingmethods/HasSize.java | {
"start": 67,
"end": 177
} | interface ____ extends HasElement {
default void setSize(String size) {
getElement();
}
}
| HasSize |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/beans/visitor/MapperVisitor.java | {
"start": 1430,
"end": 6927
} | class ____ implements TypeElementVisitor<Object, Mapper> {
private ClassElement lastClassElement;
@Override
public Set<String> getSupportedAnnotationNames() {
return Set.of(Mapper.class.getName());
}
@Override
public TypeElementQuery query() {
return TypeElementQuery.onlyMethods();
}
@Override
public void visitClass(ClassElement element, VisitorContext context) {
lastClassElement = element;
}
@Override
public void visitMethod(MethodElement element, VisitorContext context) {
if (element.hasDeclaredAnnotation(Mapper.class)) {
if (!element.isAbstract()) {
throw new ProcessingException(element, "@Mapper can only be declared on abstract methods");
}
ClassElement toType = element.getGenericReturnType();
if (toType.isVoid()) {
throw new ProcessingException(element, "A void return type is not permitted for a mapper");
}
List<AnnotationValue<Mapper.Mapping>> values = element.getAnnotationMetadata().getAnnotationValuesByType(Mapper.Mapping.class);
if (!CollectionUtils.isEmpty(values)) {
validateMappingAnnotations(element, values, toType);
}
if (lastClassElement != null) {
lastClassElement.annotate(Mapper.class);
}
}
}
@SuppressWarnings("java:S1192")
private void validateMappingAnnotations(MethodElement element, List<AnnotationValue<Mapper.Mapping>> values, ClassElement toType) {
@NonNull ParameterElement[] parameters = element.getParameters();
for (int i = 0; i < parameters.length; i++) {
ParameterElement parameter = parameters[i];
ClassElement fromType = parameter.getGenericType();
boolean isMap = fromType.isAssignable(Map.class);
if (isMap) {
List<? extends ClassElement> boundGenerics = fromType.getBoundGenericTypes();
if (boundGenerics.isEmpty() || !boundGenerics.iterator().next().isAssignable(String.class)) {
throw new ProcessingException(element, "@Mapping from parameter that is a Map must have String keys");
}
}
}
Set<String> toDefs = new HashSet<>();
for (AnnotationValue<Mapper.Mapping> value : values) {
value.stringValue("to").ifPresent(to -> {
if (toDefs.contains(to)) {
throw new ProcessingException(element, "Multiple @Mapping definitions map to the same property: " + to);
} else {
toDefs.add(to);
if (!hasPropertyWithName(toType, to)) {
throw new ProcessingException(element, "@Mapping(to=\"" + to + "\") specifies a property that doesn't exist in type " + toType.getName());
}
}
});
value.stringValue("from").ifPresent(from -> {
if (from.contains("#{")) {
return;
}
if (from.contains(".")) {
int index = from.indexOf(".");
String argumentName = from.substring(0, index);
String propertyName = from.substring(index + 1);
boolean anyMatch = false;
for (ParameterElement parameter: parameters) {
if (parameter.getName().equals(argumentName)) {
anyMatch = true;
if (parameter.getType().getName().equals(Map.class.getName())) {
break;
}
if (!hasPropertyWithName(parameter.getGenericType(), propertyName)) {
throw new ProcessingException(element, "@Mapping(from=\"" + from + "\") specifies property " + propertyName + " that doesn't exist in type " + parameter.getGenericType().getName());
}
break;
}
}
if (!anyMatch) {
throw new ProcessingException(element, "@Mapping(from=\"" + from + "\") specifies argument " + argumentName + " that doesn't exist for method");
}
} else {
String propertyName = from.substring(from.indexOf(".") + 1);
for (ParameterElement parameter: parameters) {
if (parameter.getType().getName().equals(Map.class.getName())) {
continue;
}
if (!hasPropertyWithName(parameter.getGenericType(), propertyName)) {
throw new ProcessingException(element, "@Mapping(from=\"" + from + "\") specifies property " + propertyName + " that doesn't exist in type " + parameter.getGenericType().getName());
}
}
}
});
}
}
private boolean hasPropertyWithName(ClassElement element, String propertyName) {
return element.getBeanProperties(PropertyElementQuery.of(element).includes(Collections.singleton(propertyName)))
.stream().anyMatch(v -> !v.isExcluded());
}
@Override
public @NonNull VisitorKind getVisitorKind() {
return VisitorKind.ISOLATING;
}
}
| MapperVisitor |
java | apache__flink | flink-kubernetes/src/main/java/org/apache/flink/kubernetes/kubeclient/decorators/MountSecretsDecorator.java | {
"start": 1569,
"end": 4017
} | class ____ extends AbstractKubernetesStepDecorator {
private final AbstractKubernetesParameters kubernetesComponentConf;
public MountSecretsDecorator(AbstractKubernetesParameters kubernetesComponentConf) {
this.kubernetesComponentConf = checkNotNull(kubernetesComponentConf);
}
@Override
public FlinkPod decorateFlinkPod(FlinkPod flinkPod) {
final Pod podWithMount = decoratePod(flinkPod.getPodWithoutMainContainer());
final Container containerWithMount = decorateMainContainer(flinkPod.getMainContainer());
return new FlinkPod.Builder(flinkPod)
.withPod(podWithMount)
.withMainContainer(containerWithMount)
.build();
}
private Container decorateMainContainer(Container container) {
final VolumeMount[] volumeMounts =
kubernetesComponentConf.getSecretNamesToMountPaths().entrySet().stream()
.map(
secretNameToPath ->
new VolumeMountBuilder()
.withName(
secretVolumeName(secretNameToPath.getKey()))
.withMountPath(secretNameToPath.getValue())
.build())
.toArray(VolumeMount[]::new);
return new ContainerBuilder(container).addToVolumeMounts(volumeMounts).build();
}
private Pod decoratePod(Pod pod) {
final Volume[] volumes =
kubernetesComponentConf.getSecretNamesToMountPaths().keySet().stream()
.map(
secretName ->
new VolumeBuilder()
.withName(secretVolumeName(secretName))
.withNewSecret()
.withSecretName(secretName)
.endSecret()
.build())
.toArray(Volume[]::new);
return new PodBuilder(pod).editOrNewSpec().addToVolumes(volumes).endSpec().build();
}
private String secretVolumeName(String secretName) {
return secretName + "-volume";
}
}
| MountSecretsDecorator |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/persister/entity/mutation/UpdateCoordinatorStandard.java | {
"start": 49970,
"end": 51655
} | class ____ implements AttributeAnalysisImplementor {
private final SingularAttributeMapping attribute;
private final List<ColumnSetAnalysis> columnValueAnalyses;
private final List<ColumnLockingAnalysis> columnLockingAnalyses;
private DirtynessStatus dirty = DirtynessStatus.NOT_DIRTY;
private boolean valueGeneratedInSqlNoWrite;
public IncludedAttributeAnalysis(SingularAttributeMapping attribute) {
this.attribute = attribute;
this.columnValueAnalyses = arrayList( attribute.getJdbcTypeCount() );
this.columnLockingAnalyses = arrayList( attribute.getJdbcTypeCount() );
}
@Override
public SingularAttributeMapping getAttribute() {
return attribute;
}
@Override
public boolean includeInSet() {
return !columnValueAnalyses.isEmpty();
}
@Override
public boolean includeInLocking() {
return !columnLockingAnalyses.isEmpty();
}
@Override
public DirtynessStatus getDirtynessStatus() {
return dirty;
}
@Internal
@Override
public void markDirty(boolean certain) {
if ( certain ) {
this.dirty = DirtynessStatus.DIRTY;
}
else if ( this.dirty == DirtynessStatus.NOT_DIRTY ) {
this.dirty = DirtynessStatus.CONSIDER_LIKE_DIRTY;
}
}
public boolean isValueGeneratedInSqlNoWrite() {
return valueGeneratedInSqlNoWrite;
}
public void setValueGeneratedInSqlNoWrite(boolean valueGeneratedInSqlNoWrite) {
this.valueGeneratedInSqlNoWrite = valueGeneratedInSqlNoWrite;
}
@Override
public String toString() {
return String.format(
Locale.ROOT,
"IncludedAttributeAnalysis(`%s`)",
attribute.getNavigableRole().getFullPath()
);
}
}
private static | IncludedAttributeAnalysis |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/annotation/ComposedRepeatableAnnotationsTests.java | {
"start": 10107,
"end": 10237
} | interface ____ {
String[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@ | ContainerWithArrayValueAttributeButWrongComponentType |
java | quarkusio__quarkus | extensions/redis-client/deployment/src/main/java/io/quarkus/redis/deployment/client/RedisMetricsBuildItem.java | {
"start": 210,
"end": 538
} | class ____ extends SimpleBuildItem {
private final RuntimeValue<ObservableRedisMetrics> metrics;
public RedisMetricsBuildItem(RuntimeValue<ObservableRedisMetrics> metrics) {
this.metrics = metrics;
}
public RuntimeValue<ObservableRedisMetrics> get() {
return metrics;
}
}
| RedisMetricsBuildItem |
java | alibaba__nacos | client-basic/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java | {
"start": 802,
"end": 1452
} | class ____ {
@AfterEach
void tearDown() {
System.clearProperty("acm.namespace");
System.clearProperty("ans.namespace");
}
@Test
void testGetUserTenantForAcm() {
String expect = "test";
System.setProperty("acm.namespace", expect);
String actual = TenantUtil.getUserTenantForAcm();
assertEquals(expect, actual);
}
@Test
void testGetUserTenantForAns() {
String expect = "test";
System.setProperty("ans.namespace", expect);
String actual = TenantUtil.getUserTenantForAns();
assertEquals(expect, actual);
}
}
| TenantUtilTest |
java | apache__camel | components/camel-bonita/src/test/java/org/apache/camel/component/bonita/integration/BonitaProducerManualIT.java | {
"start": 1367,
"end": 2113
} | class ____ extends BonitaIntegrationTestSupport {
@Test
public void testStartCase() {
assertDoesNotThrow(() -> runTest());
}
private void runTest() {
Map<String, Serializable> map = new HashMap<>();
map.put("vacationRequestIdContract", "1");
template.sendBody("direct:startCase", map);
}
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:startCase")
.to("bonita:startCase?hostname={{host}}&port={{port}}&processName={{process}}&username={{username}}&password={{password}}");
}
};
}
}
| BonitaProducerManualIT |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/VariantSemanticTest.java | {
"start": 14728,
"end": 15059
} | class ____ extends ScalarFunction {
public Integer eval(Variant v) {
if (v == null) {
return null;
}
Variant k = v.getField("k");
if (k.isNull()) {
return null;
}
return k.getInt();
}
}
public static | MyUdf |
java | quarkusio__quarkus | test-framework/junit5-component/src/test/java/io/quarkus/test/component/nested/NestedNestedTest.java | {
"start": 1060,
"end": 1354
} | class ____ {
@Test
@TestConfigProperty(key = "foo", value = "RAB")
public void testPing2() {
Mockito.when(charlie.ping()).thenReturn("baz");
assertEquals("baz and RAB", myComponent.ping());
}
}
}
}
| Nested2 |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/filecontroller/TestLogAggregationFileController.java | {
"start": 3995,
"end": 7645
} | class ____ implements ArgumentMatcher<Path> {
private final String expected;
PathContainsString(String expected) {
this.expected = expected;
}
@Override
public boolean matches(Path path) {
return path.getName().contains(expected);
}
@Override
public String toString() {
return "Path with name=" + expected;
}
}
@Test
void testRemoteDirCreationWithCustomUser() throws Exception {
LogAggregationFileController controller = mock(
LogAggregationFileController.class, Mockito.CALLS_REAL_METHODS);
FileSystem fs = mock(FileSystem.class);
setupCustomUserMocks(controller, fs, "/tmp/logs");
controller.initialize(new Configuration(), "TFile");
controller.fsSupportsChmod = false;
controller.verifyAndCreateRemoteLogDir();
assertPermissionFileWasUsedOneTime(fs);
assertTrue(controller.fsSupportsChmod);
doThrow(UnsupportedOperationException.class).when(fs).setPermission(any(), any());
controller.verifyAndCreateRemoteLogDir();
assertPermissionFileWasUsedOneTime(fs); // still once -> cached
assertTrue(controller.fsSupportsChmod);
controller.fsSupportsChmod = false;
controller.verifyAndCreateRemoteLogDir();
assertPermissionFileWasUsedOneTime(fs); // still once -> cached
assertTrue(controller.fsSupportsChmod);
}
@Test
void testRemoteDirCreationWithCustomUserFsChmodNotSupported() throws Exception {
LogAggregationFileController controller = mock(
LogAggregationFileController.class, Mockito.CALLS_REAL_METHODS);
FileSystem fs = mock(FileSystem.class);
setupCustomUserMocks(controller, fs, "/tmp/logs2");
doThrow(UnsupportedOperationException.class).when(fs).setPermission(any(), any());
Configuration conf = new Configuration();
conf.set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR, "/tmp/logs2");
controller.initialize(conf, "TFile");
controller.verifyAndCreateRemoteLogDir();
assertPermissionFileWasUsedOneTime(fs);
assertFalse(controller.fsSupportsChmod);
controller.verifyAndCreateRemoteLogDir();
assertPermissionFileWasUsedOneTime(fs); // still once -> cached
assertFalse(controller.fsSupportsChmod);
controller.fsSupportsChmod = true;
controller.verifyAndCreateRemoteLogDir();
assertPermissionFileWasUsedOneTime(fs); // still once -> cached
assertFalse(controller.fsSupportsChmod);
}
private static void setupCustomUserMocks(LogAggregationFileController controller,
FileSystem fs, String path)
throws URISyntaxException, IOException {
doReturn(new URI("")).when(fs).getUri();
doReturn(new FileStatus(128, false, 0, 64, System.currentTimeMillis(),
System.currentTimeMillis(), new FsPermission(TLDIR_PERMISSIONS),
"not_yarn_user", "yarn_group", new Path(path))).when(fs)
.getFileStatus(any(Path.class));
doReturn(fs).when(controller).getFileSystem(any(Configuration.class));
UserGroupInformation ugi = UserGroupInformation.createUserForTesting(
"yarn_user", new String[]{"yarn_group", "other_group"});
UserGroupInformation.setLoginUser(ugi);
}
private static void assertPermissionFileWasUsedOneTime(FileSystem fs) throws IOException {
verify(fs, times(1))
.createNewFile(argThat(new PathContainsString(".permission_check")));
verify(fs, times(1))
.setPermission(argThat(new PathContainsString(".permission_check")),
eq(new FsPermission(TLDIR_PERMISSIONS)));
verify(fs, times(1))
.delete(argThat(new PathContainsString(".permission_check")), eq(false));
}
}
| PathContainsString |
java | google__dagger | javatests/dagger/internal/codegen/ComponentProcessorTest.java | {
"start": 5820,
"end": 6906
} | interface ____ {",
" OuterClass outerClass();",
"}");
CompilerTests.daggerCompiler(outerClass, componentFile)
.withProcessingOptions(
ImmutableMap.<String, String>builder()
.putAll(compilerMode.processorOptions())
.put("dagger.privateMemberValidation", "WARNING")
.buildOrThrow())
.compile(
subject ->
// Because it is just a warning until it is used, the factory still gets generated
// which has errors from referencing the private class, so there are extra errors.
// Hence we don't assert on the number of errors.
subject.hasErrorContaining(
"Dagger does not support injection into private classes"));
}
@Test
public void simpleComponent() throws Exception {
Source injectableTypeFile = CompilerTests.javaSource("test/SomeInjectableType",
"package test;",
"",
"import javax.inject.Inject;",
"",
"final | BadComponent |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/type/AbstractAnnotationMetadataTests.java | {
"start": 13878,
"end": 14096
} | class ____ {
@MetaAnnotation2
public void direct() {
}
@MetaAnnotationRoot
public void meta() {
}
}
@AnnotationAttributes(name = "test", size = 1)
public static | WithDirectAndMetaAnnotatedMethods |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/function/ByteConsumer.java | {
"start": 935,
"end": 1064
} | interface ____ {@link IntConsumer} but for {@code byte}.
*
* @see IntConsumer
* @since 3.19.0
*/
@FunctionalInterface
public | like |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/scheduler/TestContainerSchedulerOppContainersByResources.java | {
"start": 2605,
"end": 10343
} | class ____
extends BaseContainerSchedulerTest {
public TestContainerSchedulerOppContainersByResources()
throws UnsupportedFileSystemException {
}
@BeforeEach
@Override
public void setup() throws IOException {
conf.set(YarnConfiguration.NM_OPPORTUNISTIC_CONTAINERS_QUEUE_POLICY,
OpportunisticContainersQueuePolicy.BY_RESOURCES.name());
super.setup();
containerManager.start();
}
/**
* Checks if a container is in a running or successfully run state.
* @param containerStatus the container status
* @return true if the container is running or completed
* with a successful state, false if the container has not started or failed
*/
private static boolean isContainerInSuccessfulState(
final ContainerStatus containerStatus) {
final org.apache.hadoop.yarn.api.records.ContainerState state =
containerStatus.getState();
final ContainerSubState subState = containerStatus.getContainerSubState();
switch (subState) {
case RUNNING:
case COMPLETING:
return true;
case DONE:
// If the state is not COMPLETE, then the
// container is a failed container
return state ==
org.apache.hadoop.yarn.api.records.ContainerState.COMPLETE;
default:
return false;
}
}
private void verifyRunAndKilledContainers(
final List<ContainerId> statList,
final int numExpectedContainers, final Set<ContainerId> runContainers,
final Set<ContainerId> killedContainers)
throws TimeoutException, InterruptedException {
GenericTestUtils.waitFor(
() -> {
GetContainerStatusesRequest statRequest =
GetContainerStatusesRequest.newInstance(statList);
final List<ContainerStatus> containerStatuses;
try {
containerStatuses = containerManager
.getContainerStatuses(statRequest).getContainerStatuses();
} catch (final Exception e) {
return false;
}
if (numExpectedContainers != containerStatuses.size()) {
return false;
}
for (final ContainerStatus status : containerStatuses) {
if (runContainers.contains(status.getContainerId())) {
if (!isContainerInSuccessfulState(status)) {
return false;
}
} else if (killedContainers.contains(status.getContainerId())) {
if (!status.getDiagnostics()
.contains("Opportunistic container queue is full")) {
return false;
}
} else {
return false;
}
}
return true;
}, 1000, 10000);
}
/**
* Verifies that nothing is queued at the container scheduler.
*/
private void verifyNothingQueued() {
// Check that nothing is queued
ContainerScheduler containerScheduler =
containerManager.getContainerScheduler();
assertEquals(0,
containerScheduler.getNumQueuedContainers());
assertEquals(0,
containerScheduler.getNumQueuedGuaranteedContainers());
assertEquals(0,
containerScheduler.getNumQueuedOpportunisticContainers());
assertEquals(0,
metrics.getQueuedOpportunisticContainers());
assertEquals(0, metrics.getQueuedGuaranteedContainers());
}
/**
* Tests that newly arrived containers after the resources are filled up
* get killed and never gets run.
*/
@Test
public void testKillOpportunisticWhenNoResourcesAvailable() throws Exception {
List<StartContainerRequest> startContainerRequests = new ArrayList<>();
// GContainer that takes up the whole node
startContainerRequests.add(StartContainerRequest.newInstance(
recordFactory.newRecordInstance(ContainerLaunchContext.class),
createContainerToken(createContainerId(0), DUMMY_RM_IDENTIFIER,
context.getNodeId(),
user, Resources.createResource(2048),
context.getContainerTokenSecretManager(), null,
ExecutionType.GUARANTEED)));
// OContainer that should be killed
startContainerRequests.add(StartContainerRequest.newInstance(
recordFactory.newRecordInstance(ContainerLaunchContext.class),
createContainerToken(createContainerId(1), DUMMY_RM_IDENTIFIER,
context.getNodeId(),
user, Resources.createResource(2048),
context.getContainerTokenSecretManager(), null,
ExecutionType.OPPORTUNISTIC)));
StartContainersRequest allRequests =
StartContainersRequest.newInstance(startContainerRequests);
containerManager.startContainers(allRequests);
BaseContainerManagerTest.waitForNMContainerState(containerManager,
createContainerId(0), ContainerState.RUNNING, 40);
// Wait for the OContainer to get killed
BaseContainerManagerTest.waitForNMContainerState(containerManager,
createContainerId(1), ContainerState.DONE, 40);
// Get container statuses.
// Container 0 should be running and container 1 should be killed
List<ContainerId> statList = ImmutableList.of(createContainerId(0),
createContainerId(1));
verifyRunAndKilledContainers(
statList, 2,
Collections.singleton(createContainerId(0)),
Collections.singleton(createContainerId(1))
);
verifyNothingQueued();
}
/**
* Tests that newly arrived containers after the resources are filled up
* get killed and never gets run.
* This scenario is more granular and runs more small container compared to
* {@link #testKillOpportunisticWhenNoResourcesAvailable()}.
*/
@Test
public void testOpportunisticRunsWhenResourcesAvailable() throws Exception {
List<StartContainerRequest> startContainerRequests = new ArrayList<>();
final int numContainers = 8;
final int numContainersQueued = 4;
final Set<ContainerId> runContainers = new HashSet<>();
final Set<ContainerId> killedContainers = new HashSet<>();
for (int i = 0; i < numContainers; i++) {
// OContainers that should be run
startContainerRequests.add(StartContainerRequest.newInstance(
recordFactory.newRecordInstance(ContainerLaunchContext.class),
createContainerToken(createContainerId(i), DUMMY_RM_IDENTIFIER,
context.getNodeId(),
user, Resources.createResource(512),
context.getContainerTokenSecretManager(), null,
ExecutionType.OPPORTUNISTIC)));
}
StartContainersRequest allRequests =
StartContainersRequest.newInstance(startContainerRequests);
containerManager.startContainers(allRequests);
// Wait for containers to start
for (int i = 0; i < numContainersQueued; i++) {
final ContainerId containerId = createContainerId(i);
BaseContainerManagerTest
.waitForNMContainerState(containerManager, containerId,
ContainerState.RUNNING, 40);
runContainers.add(containerId);
}
// Wait for containers to be killed
for (int i = numContainersQueued; i < numContainers; i++) {
final ContainerId containerId = createContainerId(i);
BaseContainerManagerTest
.waitForNMContainerState(containerManager, createContainerId(i),
ContainerState.DONE, 40);
killedContainers.add(containerId);
}
Thread.sleep(5000);
// Get container statuses.
List<ContainerId> statList = new ArrayList<>();
for (int i = 0; i < numContainers; i++) {
statList.add(createContainerId(i));
}
verifyRunAndKilledContainers(
statList, numContainers, runContainers, killedContainers);
verifyNothingQueued();
}
}
| TestContainerSchedulerOppContainersByResources |
java | apache__camel | components/camel-csv/src/test/java/org/apache/camel/dataformat/csv/CsvUnmarshalTest.java | {
"start": 1475,
"end": 1521
} | class ____ standard unmarshalling
*/
public | tests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/cdi/bcextensions/RegistrationTest.java | {
"start": 3737,
"end": 3898
} | interface ____ {
}
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@InterceptorBinding
public @ | MyQualifier |
java | google__guice | core/test/com/google/inject/DuplicateBindingsTest.java | {
"start": 15446,
"end": 15577
} | class ____ extends AbstractModule {
@Provides
Foo foo() {
return null;
}
}
private static | FailingProviderModule |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/FieldDeserTest.java | {
"start": 1672,
"end": 1800
} | class ____ extends Abstract
{
String value;
public Concrete(String v) { value = v; }
}
static | Concrete |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java | {
"start": 437,
"end": 4418
} | class ____ extends TestBase {
@Mock IMethods mock;
@Test
public void no_invocations() {
assertThat(new InvocationsPrinter().printInvocations(mock))
.isEqualTo("No interactions and stubbings found for mock: mock");
}
@Test
public void prints_invocations() {
mock.simpleMethod(100);
triggerInteraction();
assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock)))
.isEqualTo(
filterLineNo(
"[Mockito] Interactions of: mock\n"
+ " 1. mock.simpleMethod(100);\n"
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n"
+ " 2. mock.otherMethod();\n"
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n"));
}
@Test
public void prints_stubbings() {
triggerStubbing();
assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock)))
.isEqualTo(
filterLineNo(
"[Mockito] Unused stubbings of: mock\n"
+ " 1. mock.simpleMethod(\"a\");\n"
+ " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n"));
}
@Test
public void prints_invocations_and_stubbings() {
triggerStubbing();
mock.simpleMethod("a");
triggerInteraction();
assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock)))
.isEqualTo(
filterLineNo(
"[Mockito] Interactions of: mock\n"
+ " 1. mock.simpleMethod(\"a\");\n"
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n"
+ " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n"
+ " 2. mock.otherMethod();\n"
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n"));
}
@Test
public void prints_invocations_and_unused_stubbings() {
triggerStubbing();
mock.simpleMethod("b");
triggerInteraction();
assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock)))
.isEqualTo(
filterLineNo(
"[Mockito] Interactions of: mock\n"
+ " 1. mock.simpleMethod(\"b\");\n"
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n"
+ " 2. mock.otherMethod();\n"
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n"
+ "[Mockito] Unused stubbings of: mock\n"
+ " 1. mock.simpleMethod(\"a\");\n"
+ " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n"));
}
private void triggerInteraction() {
mock.otherMethod();
}
private void triggerStubbing() {
when(mock.simpleMethod("a")).thenReturn("x");
}
}
| InvocationsPrinterTest |
java | processing__processing4 | java/libraries/io/src/processing/io/PWM.java | {
"start": 1234,
"end": 6848
} | class ____ {
int channel;
String chip;
/**
* Opens a PWM channel
* @param channel PWM channel
* @see list
* @webref PWM
* @webBrief Opens a PWM channel
*/
public PWM(String channel) {
NativeInterface.loadLibrary();
int pos = channel.indexOf("/pwm");
if (pos == -1) {
throw new IllegalArgumentException("Unsupported channel");
}
chip = channel.substring(0, pos);
this.channel = Integer.parseInt(channel.substring(pos+4));
if (NativeInterface.isSimulated()) {
return;
}
// export channel through sysfs
String fn = "/sys/class/pwm/" + chip + "/export";
int ret = NativeInterface.writeFile(fn, Integer.toString(this.channel));
if (ret < 0) {
if (ret == -2) { // ENOENT
System.err.println("Make sure your kernel is compiled with PWM_SYSFS enabled and you have the necessary PWM driver for your platform");
}
// XXX: check
if (ret == -22) { // EINVAL
System.err.println("PWM channel " + channel + " does not seem to be available on your platform");
}
// XXX: check
if (ret != -16) { // EBUSY, returned when the pin is already exported
throw new RuntimeException(fn + ": " + NativeInterface.getError(ret));
}
}
// delay to give udev a chance to change the file permissions behind our back
// there should really be a cleaner way for this
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* Disables the PWM output
*
* @webref PWM
* @webBrief Disables the PWM output
*/
public void clear() {
if (NativeInterface.isSimulated()) {
return;
}
String fn = String.format("/sys/class/pwm/%s/pwm%d/enable", chip, channel);
int ret = NativeInterface.writeFile(fn, "0");
if (ret < 0) {
throw new RuntimeException(NativeInterface.getError(ret));
}
}
/**
* Gives ownership of a channel back to the operating system<br/>
* <br/>
* Without calling this function the channel will remain in the current state
* even after the sketch has been closed.
*
* @webref PWM
* @webBrief Gives ownership of a channel back to the operating system
*/
public void close() {
if (NativeInterface.isSimulated()) {
return;
}
// XXX: implicit clear()?
// XXX: also check GPIO
String fn = "/sys/class/pwm/" + chip + "/unexport";
int ret = NativeInterface.writeFile(fn, Integer.toString(channel));
if (ret < 0) {
if (ret == -2) { // ENOENT
System.err.println("Make sure your kernel is compiled with PWM_SYSFS enabled and you have the necessary PWM driver for your platform");
}
// XXX: check
// EINVAL is also returned when trying to unexport pins that weren't exported to begin with
throw new RuntimeException(NativeInterface.getError(ret));
}
}
/**
* Lists all available PWM channels
* @return String array
* @webref PWM
* @webBrief Lists all available PWM channels
*/
public static String[] list() {
if (NativeInterface.isSimulated()) {
return new String[]{ "pwmchip0/pwm0", "pwmchip0/pwm1" };
}
ArrayList<String> devs = new ArrayList<String>();
File dir = new File("/sys/class/pwm");
File[] chips = dir.listFiles();
if (chips != null) {
for (File chip : chips) {
// get the number of supported channels
try {
Path path = Paths.get("/sys/class/pwm/" + chip.getName() + "/npwm");
String tmp = new String(Files.readAllBytes(path));
int npwm = Integer.parseInt(tmp.trim());
for (int i=0; i < npwm; i++) {
devs.add(chip.getName() + "/pwm" + i);
}
} catch (Exception e) {
}
}
}
// listFiles() does not guarantee ordering
String[] tmp = devs.toArray(new String[devs.size()]);
Arrays.sort(tmp);
return tmp;
}
/**
* Enables the PWM output<br/>
* <br/>
* When no period is specified, a default 1 kHz (1000 Hz) is used.
*
* @param period cycle period in Hz
* @param duty duty cycle, 0.0 (always off) to 1.0 (always on)
* @webref PWM
* @webBrief Enables the PWM output
*/
public void set(int period, float duty) {
if (NativeInterface.isSimulated()) {
return;
}
// set period
String fn = String.format("/sys/class/pwm/%s/pwm%d/period", chip, channel);
// convert to nanoseconds
int ret = NativeInterface.writeFile(fn, String.format("%d", (int)(1000000000 / period)));
if (ret < 0) {
throw new RuntimeException(fn + ": " + NativeInterface.getError(ret));
}
// set duty cycle
fn = String.format("/sys/class/pwm/%s/pwm%d/duty_cycle", chip, channel);
if (duty < 0.0 || 1.0 < duty) {
System.err.println("Duty cycle must be between 0.0 and 1.0.");
throw new IllegalArgumentException("Illegal argument");
}
// convert to nanoseconds
ret = NativeInterface.writeFile(fn, String.format("%d", (int)((1000000000 * duty) / period)));
if (ret < 0) {
throw new RuntimeException(fn + ": " + NativeInterface.getError(ret));
}
// enable output
fn = String.format("/sys/class/pwm/%s/pwm%d/enable", chip, channel);
ret = NativeInterface.writeFile(fn, "1");
if (ret < 0) {
throw new RuntimeException(fn + ": " + NativeInterface.getError(ret));
}
}
/**
* Enables the PWM output with a preset period of 1 kHz
* @nowebref
*/
public void set(float duty) {
set(1000, duty);
}
}
| PWM |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java | {
"start": 13807,
"end": 14716
} | class ____ {
public String s1;
private void doIt(final String s2) {
String s3 = "";
String s4 = "";
new Thread(
new Runnable() {
@Override
public void run() {
String s5 = "";
s5 = "foo";
// BUG: Diagnostic contains: [s5, s3, s2, s1]
String.format(s5 + s3 + s2 + s1);
}
})
.start();
s4 = "foo";
}
}
""")
.doTest();
}
@Test
public void findAllIdentsLambda() {
CompilationTestHelper.newInstance(PrintIdents.class, getClass())
.addSourceLines(
"Test.java",
"""
| Test |
java | apache__spark | common/kvstore/src/main/java/org/apache/spark/util/kvstore/ArrayWrappers.java | {
"start": 1332,
"end": 1474
} | class ____ not efficient and is mostly meant to compare really small arrays, like those
* generally used as indices and keys in a KVStore.
*/
| is |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/StaticMockingExperimentTest.java | {
"start": 12909,
"end": 13021
} | interface ____ {
Object construct(Constructor constructor, Object... args);
}
}
| ConstructorMethodAdapter |
java | apache__rocketmq | proxy/src/main/java/org/apache/rocketmq/proxy/remoting/RemotingProtocolServer.java | {
"start": 11027,
"end": 16816
} | class ____ implements TlsCertificateManager.TlsContextReloadListener {
@Override
public void onTlsContextReload() {
if (defaultRemotingServer instanceof NettyRemotingServer) {
((NettyRemotingServer) defaultRemotingServer).loadSslContext();
log.info("SslContext reloaded for remoting server");
}
}
}
protected void registerRemotingServer(RemotingServer remotingServer) {
remotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendMessageActivity, this.sendMessageExecutor);
remotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendMessageActivity, this.sendMessageExecutor);
remotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendMessageActivity, this.sendMessageExecutor);
remotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendMessageActivity, sendMessageExecutor);
remotingServer.registerProcessor(RequestCode.END_TRANSACTION, transactionActivity, sendMessageExecutor);
remotingServer.registerProcessor(RequestCode.RECALL_MESSAGE, recallMessageActivity, sendMessageExecutor);
remotingServer.registerProcessor(RequestCode.HEART_BEAT, clientManagerActivity, this.heartbeatExecutor);
remotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.PULL_MESSAGE, pullMessageActivity, this.pullMessageExecutor);
remotingServer.registerProcessor(RequestCode.LITE_PULL_MESSAGE, pullMessageActivity, this.pullMessageExecutor);
remotingServer.registerProcessor(RequestCode.POP_MESSAGE, pullMessageActivity, this.pullMessageExecutor);
remotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManagerActivity, this.updateOffsetExecutor);
remotingServer.registerProcessor(RequestCode.ACK_MESSAGE, consumerManagerActivity, this.updateOffsetExecutor);
remotingServer.registerProcessor(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, consumerManagerActivity, this.updateOffsetExecutor);
remotingServer.registerProcessor(RequestCode.GET_CONSUMER_CONNECTION_LIST, consumerManagerActivity, this.updateOffsetExecutor);
remotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.GET_MAX_OFFSET, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.GET_MIN_OFFSET, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.SEARCH_OFFSET_BY_TIMESTAMP, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.LOCK_BATCH_MQ, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.UNLOCK_BATCH_MQ, consumerManagerActivity, this.defaultExecutor);
remotingServer.registerProcessor(RequestCode.GET_ROUTEINFO_BY_TOPIC, getTopicRouteActivity, this.topicRouteExecutor);
}
@Override
public void shutdown() throws Exception {
// Unregister the TLS context reload handler
tlsCertificateManager.unregisterReloadListener(this.tlsReloadHandler);
this.defaultRemotingServer.shutdown();
this.remotingChannelManager.shutdown();
this.sendMessageExecutor.shutdown();
this.pullMessageExecutor.shutdown();
this.heartbeatExecutor.shutdown();
this.updateOffsetExecutor.shutdown();
this.topicRouteExecutor.shutdown();
this.defaultExecutor.shutdown();
}
@Override
public void start() throws Exception {
// Register the TLS context reload handler
tlsCertificateManager.registerReloadListener(this.tlsReloadHandler);
this.remotingChannelManager.start();
this.defaultRemotingServer.start();
}
@Override
public CompletableFuture<RemotingCommand> invokeToClient(Channel channel, RemotingCommand request,
long timeoutMillis) {
CompletableFuture<RemotingCommand> future = new CompletableFuture<>();
try {
this.defaultRemotingServer.invokeAsync(channel, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
}
@Override
public void operationSucceed(RemotingCommand response) {
future.complete(response);
}
@Override
public void operationFail(Throwable throwable) {
future.completeExceptionally(throwable);
}
});
} catch (Throwable t) {
future.completeExceptionally(t);
}
return future;
}
protected RequestPipeline createRequestPipeline(MessagingProcessor messagingProcessor) {
RequestPipeline pipeline = (ctx, request, context) -> {
};
// add pipeline
// the last pipe add will execute at the first
AuthConfig authConfig = ConfigurationManager.getAuthConfig();
if (authConfig != null) {
pipeline = pipeline.pipe(new AuthorizationPipeline(authConfig, messagingProcessor))
.pipe(new AuthenticationPipeline(authConfig, messagingProcessor));
}
return pipeline.pipe(new ContextInitPipeline());
}
protected | RemotingTlsReloadHandler |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/MultisetFeature.java | {
"start": 1272,
"end": 1660
} | enum ____ implements Feature<Multiset> {
/**
* Indicates that elements from {@code Multiset.entrySet()} update to reflect changes in the
* backing multiset.
*/
ENTRIES_ARE_VIEWS;
@Override
public Set<Feature<? super Multiset>> getImpliedFeatures() {
return emptySet();
}
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@TesterAnnotation
public @ | MultisetFeature |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlAlterTableAlterColumn.java | {
"start": 962,
"end": 2080
} | class ____ extends MySqlObjectImpl implements SQLAlterTableItem {
private SQLName column;
private String visibleType;
private boolean dropDefault;
private SQLExpr defaultExpr;
@Override
public void accept0(MySqlASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, column);
acceptChild(visitor, defaultExpr);
}
visitor.endVisit(this);
}
public boolean isDropDefault() {
return dropDefault;
}
public void setDropDefault(boolean dropDefault) {
this.dropDefault = dropDefault;
}
public String getVisibleType() {
return visibleType;
}
public void setVisibleType(String visibleType) {
this.visibleType = visibleType;
}
public SQLExpr getDefaultExpr() {
return defaultExpr;
}
public void setDefaultExpr(SQLExpr defaultExpr) {
this.defaultExpr = defaultExpr;
}
public SQLName getColumn() {
return column;
}
public void setColumn(SQLName column) {
this.column = column;
}
}
| MySqlAlterTableAlterColumn |
java | mapstruct__mapstruct | core/src/main/java/org/mapstruct/MappingConstants.java | {
"start": 2328,
"end": 2577
} | enum ____ strategy that strips a prefix from the source
* enum.
*
* @since 1.4
*/
public static final String STRIP_PREFIX_TRANSFORMATION = "stripPrefix";
/**
* In an {@link EnumMapping} this represent the | transformation |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java | {
"start": 14033,
"end": 14158
} | class ____ {
}
@EnableAutoConfiguration(exclude = SeventhAutoConfiguration.class)
private final | BasicEnableAutoConfiguration |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/exceptionhistory/RootExceptionHistoryEntry.java | {
"start": 1712,
"end": 8530
} | class ____ extends ExceptionHistoryEntry {
private static final long serialVersionUID = -7647332765867297434L;
private final Collection<ExceptionHistoryEntry> concurrentExceptions;
/**
* Creates a {@code RootExceptionHistoryEntry} based on the passed {@link
* FailureHandlingResultSnapshot}.
*
* @param snapshot The reason for the failure.
* @return The {@code RootExceptionHistoryEntry} instance.
* @throws NullPointerException if {@code cause} or {@code failingTaskName} are {@code null}.
* @throws IllegalArgumentException if the {@code timestamp} of the passed {@code
* FailureHandlingResult} is not bigger than {@code 0}.
*/
public static RootExceptionHistoryEntry fromFailureHandlingResultSnapshot(
FailureHandlingResultSnapshot snapshot) {
String failingTaskName = null;
TaskManagerLocation taskManagerLocation = null;
if (snapshot.getRootCauseExecution().isPresent()) {
final Execution rootCauseExecution = snapshot.getRootCauseExecution().get();
failingTaskName = rootCauseExecution.getVertexWithAttempt();
taskManagerLocation = rootCauseExecution.getAssignedResourceLocation();
}
return createRootExceptionHistoryEntry(
snapshot.getRootCause(),
snapshot.getTimestamp(),
snapshot.getFailureLabels(),
failingTaskName,
taskManagerLocation,
snapshot.getConcurrentlyFailedExecution());
}
/**
* Creates a {@code RootExceptionHistoryEntry} representing a global failure from the passed
* {@code Throwable} and timestamp. If any of the passed {@link Execution Executions} failed, it
* will be added to the {@code RootExceptionHistoryEntry}'s concurrently caught failures.
*
* @param cause The reason for the failure.
* @param timestamp The time the failure was caught.
* @param failureLabels Map of string labels associated with the failure.
* @param executions The {@link Execution} instances that shall be analyzed for failures.
* @return The {@code RootExceptionHistoryEntry} instance.
* @throws NullPointerException if {@code failure} is {@code null}.
* @throws IllegalArgumentException if the passed {@code timestamp} is not bigger than {@code
* 0}.
*/
public static RootExceptionHistoryEntry fromGlobalFailure(
Throwable cause,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
Iterable<Execution> executions) {
return createRootExceptionHistoryEntry(
cause, timestamp, failureLabels, null, null, executions);
}
public static RootExceptionHistoryEntry fromExceptionHistoryEntry(
ExceptionHistoryEntry entry, Collection<ExceptionHistoryEntry> entries) {
return new RootExceptionHistoryEntry(
entry.getException(),
entry.getTimestamp(),
entry.getFailureLabelsFuture(),
null,
null,
entries);
}
/**
* Creates a {@code RootExceptionHistoryEntry} based on the passed {@link ErrorInfo}. No
* concurrent failures will be added.
*
* @param errorInfo The failure information that shall be used to initialize the {@code
* RootExceptionHistoryEntry}.
* @return The {@code RootExceptionHistoryEntry} instance.
* @throws NullPointerException if {@code errorInfo} is {@code null} or the passed info does not
* contain a {@code Throwable}.
* @throws IllegalArgumentException if the passed {@code timestamp} is not bigger than {@code
* 0}.
*/
public static RootExceptionHistoryEntry fromGlobalFailure(ErrorInfo errorInfo) {
Preconditions.checkNotNull(errorInfo, "errorInfo");
return fromGlobalFailure(
errorInfo.getException(),
errorInfo.getTimestamp(),
FailureEnricherUtils.EMPTY_FAILURE_LABELS,
Collections.emptyList());
}
private static RootExceptionHistoryEntry createRootExceptionHistoryEntry(
Throwable cause,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
@Nullable String failingTaskName,
@Nullable TaskManagerLocation taskManagerLocation,
Iterable<Execution> executions) {
return new RootExceptionHistoryEntry(
cause,
timestamp,
failureLabels,
failingTaskName,
taskManagerLocation,
createExceptionHistoryEntries(executions));
}
private static Collection<ExceptionHistoryEntry> createExceptionHistoryEntries(
Iterable<Execution> executions) {
return StreamSupport.stream(executions.spliterator(), false)
.filter(execution -> execution.getFailureInfo().isPresent())
.map(
execution ->
ExceptionHistoryEntry.create(
execution,
execution.getVertexWithAttempt(),
FailureEnricherUtils.EMPTY_FAILURE_LABELS))
.collect(Collectors.toList());
}
/**
* Instantiates a {@code RootExceptionHistoryEntry}.
*
* @param cause The reason for the failure.
* @param timestamp The time the failure was caught.
* @param failureLabels labels associated with the failure.
* @param failingTaskName The name of the task that failed.
* @param taskManagerLocation The host the task was running on.
* @throws NullPointerException if {@code cause} is {@code null}.
* @throws IllegalArgumentException if the passed {@code timestamp} is not bigger than {@code
* 0}.
*/
@VisibleForTesting
public RootExceptionHistoryEntry(
Throwable cause,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
@Nullable String failingTaskName,
@Nullable TaskManagerLocation taskManagerLocation,
Collection<ExceptionHistoryEntry> concurrentExceptions) {
super(cause, timestamp, failureLabels, failingTaskName, taskManagerLocation);
this.concurrentExceptions = concurrentExceptions;
}
public void addConcurrentExceptions(Iterable<Execution> concurrentlyExecutions) {
this.concurrentExceptions.addAll(createExceptionHistoryEntries(concurrentlyExecutions));
}
public Iterable<ExceptionHistoryEntry> getConcurrentExceptions() {
return concurrentExceptions;
}
}
| RootExceptionHistoryEntry |
java | apache__camel | components/camel-zookeeper-master/src/main/java/org/apache/camel/component/zookeepermaster/group/internal/DelegateZooKeeperGroup.java | {
"start": 1385,
"end": 4857
} | class ____<T extends NodeState> implements Group<T> {
private final String path;
private final Class<T> clazz;
private final List<GroupListener<T>> listeners;
private Group<T> group;
private T state;
private final AtomicBoolean started = new AtomicBoolean();
public DelegateZooKeeperGroup(String path, Class<T> clazz) {
this.listeners = new ArrayList<>();
this.path = path;
this.clazz = clazz;
}
public void useCurator(CuratorFramework curator) {
Group<T> group = this.group;
if (group != null) {
closeQuietly(group);
}
if (curator != null) {
group = createGroup(curator, path, clazz);
group.update(state);
for (GroupListener<T> listener : listeners) {
group.add(listener);
}
if (started.get()) {
group.start();
}
this.group = group;
}
}
protected Group<T> createGroup(CuratorFramework client, String path, Class<T> clazz) {
return new ZooKeeperGroup<>(client, path, clazz);
}
@Override
public void add(GroupListener<T> listener) {
listeners.add(listener);
Group<T> group = this.group;
if (group != null) {
group.add(listener);
}
}
@Override
public void remove(GroupListener<T> listener) {
listeners.remove(listener);
Group<T> group = this.group;
if (group != null) {
group.remove(listener);
}
}
@Override
public boolean isConnected() {
Group<T> group = this.group;
if (group != null) {
return group.isConnected();
} else {
return false;
}
}
@Override
public void start() {
if (started.compareAndSet(false, true)) {
doStart();
}
}
protected void doStart() {
if (group != null) {
group.start();
}
}
@Override
public void close() throws IOException {
if (started.compareAndSet(true, false)) {
doStop();
}
}
protected void doStop() {
closeQuietly(group);
}
@Override
public void update(T state) {
this.state = state;
Group<T> group = this.group;
if (group != null) {
group.update(state);
}
}
@Override
public Map<String, T> members() {
Group<T> group = this.group;
if (group != null) {
return group.members();
} else {
return Collections.emptyMap();
}
}
@Override
public boolean isMaster() {
Group<T> group = this.group;
if (group != null) {
return group.isMaster();
} else {
return false;
}
}
@Override
public T master() {
Group<T> group = this.group;
if (group != null) {
return group.master();
} else {
return null;
}
}
@Override
public List<T> slaves() {
Group<T> group = this.group;
if (group != null) {
return group.slaves();
} else {
return Collections.emptyList();
}
}
public Group<T> getGroup() {
return group;
}
@Override
public T getLastState() {
return group != null ? group.getLastState() : null;
}
}
| DelegateZooKeeperGroup |
java | apache__camel | core/camel-xml-jaxp/src/main/java/org/apache/camel/support/processor/validation/SchemaReader.java | {
"start": 1834,
"end": 3137
} | class ____ {
/**
* Key of the global option to switch either off or on the access to external DTDs in the XML Validator for
* StreamSources. Only effective, if not a custom schema factory is used.
*/
public static final String ACCESS_EXTERNAL_DTD = "CamelXmlValidatorAccessExternalDTD";
private static final Logger LOG = LoggerFactory.getLogger(SchemaReader.class);
private String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;
// must be volatile because is accessed from different threads see ValidatorEndpoint.clearCachedSchema
private volatile Schema schema;
private final Lock lock = new ReentrantLock();
private Source schemaSource;
// must be volatile because is accessed from different threads see ValidatorEndpoint.clearCachedSchema
private volatile SchemaFactory schemaFactory;
private URL schemaUrl;
private File schemaFile;
private byte[] schemaAsByteArray;
private final String schemaResourceUri;
private LSResourceResolver resourceResolver;
private final CamelContext camelContext;
public SchemaReader() {
this.camelContext = null;
this.schemaResourceUri = null;
}
/**
* Specify a camel context and a schema resource URI in order to read the schema via the | SchemaReader |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/ObjectOfInputTypeStrategyTest.java | {
"start": 7640,
"end": 9315
} | class
____.INT(), // field name (not a string)
DataTypes.INT()) // field value
.calledWithLiteralAt(0, USER_CLASS_PATH)
.calledWithLiteralAt(1, 5)
.expectArgumentTypes(DataTypes.STRING(), DataTypes.INT(), DataTypes.INT())
.expectErrorMessage(
"The field key at position 2 must be a non-nullable character string, but was INT."),
// Invalid test case - repeated field names
TestSpec.forStrategy(
"OBJECT_OF with repeated field names", OBJECT_OF_INPUT_STRATEGY)
.calledWithArgumentTypes(
DataTypes.STRING().notNull(),
DataTypes.STRING().notNull(),
DataTypes.INT(),
DataTypes.STRING().notNull(),
DataTypes.INT())
.calledWithLiteralAt(0, USER_CLASS_PATH)
.calledWithLiteralAt(1, "field1")
.calledWithLiteralAt(3, "field1")
.expectArgumentTypes(
DataTypes.STRING().notNull(),
DataTypes.STRING().notNull(),
DataTypes.INT(),
DataTypes.STRING().notNull(),
DataTypes.INT())
.expectErrorMessage("The field name 'field1' at position 4 is repeated."));
}
}
| DataTypes |
java | quarkusio__quarkus | extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeAuthGraphQLWSHandler.java | {
"start": 1126,
"end": 9144
} | class ____ {
private final GraphQLWebSocketSession session;
private final RoutingContext ctx;
private final SmallRyeGraphQLAbstractHandler handler;
private final Optional<String> authorizationClientInitPayloadName;
private final AtomicReference<Cancellable> authExpiry = new AtomicReference<>();
public SmallRyeAuthGraphQLWSHandler(GraphQLWebSocketSession session,
RoutingContext ctx,
SmallRyeGraphQLAbstractHandler handler,
Optional<String> authorizationClientInitPayloadName) {
this.session = session;
this.ctx = ctx;
this.handler = handler;
this.authorizationClientInitPayloadName = authorizationClientInitPayloadName;
updateIdentityExpiry(ctx);
}
/**
* Takes the payload sent from connection_init, and if quarkus.smallrye-graphql.authorization-client-init-payload-name is
* defined,
* then will take the value from the payload that matches the configured value. The value is treated as an Authorization
* header.
*
* @param payload The connection_init payload
* @param successCallback Will back called once the authentication has completed (or is skipped if not required)
* @param failureHandler Any errors which occur during authentication will be passed to this handler
*/
void handlePayload(Map<String, Object> payload, Runnable successCallback, Consumer<Throwable> failureHandler) {
if (authorizationClientInitPayloadName.isPresent() && payload != null &&
payload.get(authorizationClientInitPayloadName.get()) instanceof JsonString authorizationJson) {
String authorization = authorizationJson.getString();
HttpAuthenticator authenticator = ctx.get(HttpAuthenticator.class.getName());
// Get the existing identity of the RoutingContext
QuarkusHttpUser.getSecurityIdentity(ctx, authenticator.getIdentityProviderManager()).subscribe()
.withSubscriber(new UniSubscriber<SecurityIdentity>() {
@Override
public void onSubscribe(UniSubscription subscription) {
}
@Override
public void onItem(SecurityIdentity previousIdentity) {
if (!previousIdentity.isAnonymous()) {
// Fail if this WebSocket already has an identity assigned to it
onFailure(new SmallRyeAuthSecurityIdentityAlreadyAssignedException(payload));
return;
} else if (ctx.user() == null) {
// Ensure that the identity which we have now got is actually set against the RoutingContext.
QuarkusHttpUser.setIdentity(previousIdentity, ctx);
}
// Treat the Authorization sent in the client init in the same was that it would be if sent in the request header
ctx.request().headers().add("Authorization", authorization);
Uni<SecurityIdentity> potentialUser = authenticator.attemptAuthentication(ctx);
potentialUser
.subscribe().withSubscriber(new UniSubscriber<SecurityIdentity>() {
@Override
public void onSubscribe(UniSubscription subscription) {
}
@Override
public void onItem(SecurityIdentity identity) {
// If identity is null, we've set the anonymous identity above, so we can ignore it
if (!session.isClosed() && identity != null) {
QuarkusHttpUser.setIdentity(identity, ctx);
handler.withIdentity(ctx);
updateIdentityExpiry(ctx);
successCallback.run();
}
}
@Override
public void onFailure(Throwable failure) {
BiConsumer<RoutingContext, Throwable> handler = ctx
.get(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
if (handler != null) {
handler.accept(ctx, failure);
}
failureHandler.accept(failure);
}
});
}
@Override
public void onFailure(Throwable failure) {
BiConsumer<RoutingContext, Throwable> handler = ctx
.get(QuarkusHttpUser.AUTH_FAILURE_HANDLER);
if (handler != null) {
handler.accept(ctx, failure);
}
failureHandler.accept(failure);
}
});
} else {
successCallback.run();
}
}
private void updateIdentityExpiry(RoutingContext ctx) {
Cancellable replacing = authExpiry.getAndSet(createAuthExpiryTask(ctx, session));
if (replacing != null) {
// Should never replace an expiring identity.
// As above, we only permit updating the identity if the session starts with an anonymous identity.
replacing.cancel();
}
}
public void cancelAuthExpiry() {
Cancellable expire = authExpiry.get();
if (expire != null) {
expire.cancel();
}
}
public static Cancellable createAuthExpiryTask(RoutingContext ctx, GraphQLWebSocketSession webSocketSession) {
AtomicLong atomicTaskId = new AtomicLong(-1);
Cancellable sub = QuarkusHttpUser.getSecurityIdentity(ctx, null)
.subscribe()
.with(securityIdentity -> {
QuarkusHttpUser user = (QuarkusHttpUser) ctx.user();
if (user != null) {
//close the connection when the identity expires
Long expire = user.getSecurityIdentity().getAttribute("quarkus.identity.expire-time");
if (expire != null) {
long taskId = ctx.vertx().setTimer((expire * 1000) - System.currentTimeMillis(),
event -> {
if (!webSocketSession.isClosed()) {
webSocketSession.close((short) 1008, "Authentication expired");
}
});
long previousValue = atomicTaskId.getAndSet(taskId);
if (previousValue == -2) {
// If -2 it's been cancelled.
ctx.vertx().cancelTimer(taskId);
}
}
}
});
return () -> {
// If we're still loading the deferred identity, cancel
sub.cancel();
// Set to -2 to indicate it's been cancelled.
long taskId = atomicTaskId.getAndSet(-2);
if (taskId >= 0) {
ctx.vertx().cancelTimer(taskId);
}
};
}
}
| SmallRyeAuthGraphQLWSHandler |
java | elastic__elasticsearch | x-pack/plugin/mapper-constant-keyword/src/test/java/org/elasticsearch/xpack/constantkeyword/mapper/ConstantKeywordFieldTypeTests.java | {
"start": 1019,
"end": 8390
} | class ____ extends ConstantFieldTypeTestCase {
public void testTermQuery() {
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.termQuery("foo", null));
assertEquals(new MatchAllDocsQuery(), ft.termQueryCaseInsensitive("fOo", null));
assertEquals(new MatchNoDocsQuery(), ft.termQuery("bar", null));
assertEquals(new MatchNoDocsQuery(), ft.termQueryCaseInsensitive("bAr", null));
ConstantKeywordFieldType bar = new ConstantKeywordFieldType("f", "bar");
assertEquals(new MatchNoDocsQuery(), bar.termQuery("foo", null));
assertEquals(new MatchNoDocsQuery(), bar.termQueryCaseInsensitive("fOo", null));
}
public void testTermsQuery() {
ConstantKeywordFieldType bar = new ConstantKeywordFieldType("f", "bar");
assertEquals(new MatchNoDocsQuery(), bar.termsQuery(Collections.singletonList("foo"), null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.termsQuery(Collections.singletonList("foo"), null));
assertEquals(new MatchAllDocsQuery(), ft.termsQuery(Arrays.asList("bar", "foo", "quux"), null));
assertEquals(new MatchNoDocsQuery(), ft.termsQuery(Collections.emptyList(), null));
assertEquals(new MatchNoDocsQuery(), ft.termsQuery(Collections.singletonList("bar"), null));
assertEquals(new MatchNoDocsQuery(), ft.termsQuery(Arrays.asList("bar", "quux"), null));
}
public void testWildcardQuery() {
ConstantKeywordFieldType bar = new ConstantKeywordFieldType("f", "bar");
assertEquals(new MatchNoDocsQuery(), bar.wildcardQuery("f*o", null, false, null));
assertEquals(new MatchNoDocsQuery(), bar.wildcardQuery("F*o", null, true, null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.wildcardQuery("f*o", null, false, null));
assertEquals(new MatchAllDocsQuery(), ft.wildcardQuery("F*o", null, true, null));
assertEquals(new MatchNoDocsQuery(), ft.wildcardQuery("b*r", null, false, null));
assertEquals(new MatchNoDocsQuery(), ft.wildcardQuery("B*r", null, true, null));
}
public void testPrefixQuery() {
ConstantKeywordFieldType bar = new ConstantKeywordFieldType("f", "bar");
assertEquals(new MatchNoDocsQuery(), bar.prefixQuery("fo", null, false, null));
assertEquals(new MatchNoDocsQuery(), bar.prefixQuery("fO", null, true, null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.prefixQuery("fo", null, false, null));
assertEquals(new MatchAllDocsQuery(), ft.prefixQuery("fO", null, true, null));
assertEquals(new MatchNoDocsQuery(), ft.prefixQuery("ba", null, false, null));
assertEquals(new MatchNoDocsQuery(), ft.prefixQuery("Ba", null, true, null));
}
public void testExistsQuery() {
ConstantKeywordFieldType none = new ConstantKeywordFieldType("f", null);
assertEquals(new MatchNoDocsQuery(), none.existsQuery(null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.existsQuery(null));
}
public void testRangeQuery() {
ConstantKeywordFieldType none = new ConstantKeywordFieldType("f", null);
assertEquals(new MatchNoDocsQuery(), none.rangeQuery(null, null, randomBoolean(), randomBoolean(), null, null, null, null));
assertEquals(new MatchNoDocsQuery(), none.rangeQuery(null, "foo", randomBoolean(), randomBoolean(), null, null, null, null));
assertEquals(new MatchNoDocsQuery(), none.rangeQuery("foo", null, randomBoolean(), randomBoolean(), null, null, null, null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.rangeQuery(null, null, randomBoolean(), randomBoolean(), null, null, null, null));
assertEquals(new MatchAllDocsQuery(), ft.rangeQuery("foo", null, true, randomBoolean(), null, null, null, null));
assertEquals(new MatchNoDocsQuery(), ft.rangeQuery("foo", null, false, randomBoolean(), null, null, null, null));
assertEquals(new MatchAllDocsQuery(), ft.rangeQuery(null, "foo", randomBoolean(), true, null, null, null, null));
assertEquals(new MatchNoDocsQuery(), ft.rangeQuery(null, "foo", randomBoolean(), false, null, null, null, null));
assertEquals(new MatchAllDocsQuery(), ft.rangeQuery("abc", "xyz", randomBoolean(), randomBoolean(), null, null, null, null));
assertEquals(new MatchNoDocsQuery(), ft.rangeQuery("abc", "def", randomBoolean(), randomBoolean(), null, null, null, null));
assertEquals(new MatchNoDocsQuery(), ft.rangeQuery("mno", "xyz", randomBoolean(), randomBoolean(), null, null, null, null));
}
public void testFuzzyQuery() {
ConstantKeywordFieldType none = new ConstantKeywordFieldType("f", null);
assertEquals(new MatchNoDocsQuery(), none.fuzzyQuery("fooquux", Fuzziness.AUTO, 3, 50, randomBoolean(), null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foobar");
assertEquals(new MatchAllDocsQuery(), ft.fuzzyQuery("foobaz", Fuzziness.AUTO, 3, 50, randomBoolean(), null));
assertEquals(new MatchNoDocsQuery(), ft.fuzzyQuery("fooquux", Fuzziness.AUTO, 3, 50, randomBoolean(), null));
}
public void testRegexpQuery() {
ConstantKeywordFieldType none = new ConstantKeywordFieldType("f", null);
assertEquals(new MatchNoDocsQuery(), none.regexpQuery("f..o", RegExp.ALL, 0, 10, null, null));
ConstantKeywordFieldType ft = new ConstantKeywordFieldType("f", "foo");
assertEquals(new MatchAllDocsQuery(), ft.regexpQuery("f.o", RegExp.ALL, 0, 10, null, null));
assertEquals(new MatchNoDocsQuery(), ft.regexpQuery("f..o", RegExp.ALL, 0, 10, null, null));
}
public void testFetchValue() throws Exception {
MappedFieldType fieldType = new ConstantKeywordFieldMapper.ConstantKeywordFieldType("field", null);
ValueFetcher fetcher = fieldType.valueFetcher(null, null);
Source sourceWithNoFieldValue = Source.fromMap(Map.of("unrelated", "random"), randomFrom(XContentType.values()));
Source sourceWithNullFieldValue = Source.fromMap(Collections.singletonMap("field", null), randomFrom(XContentType.values()));
List<Object> ignoredValues = new ArrayList<>();
assertTrue(fetcher.fetchValues(sourceWithNoFieldValue, -1, ignoredValues).isEmpty());
assertTrue(fetcher.fetchValues(sourceWithNullFieldValue, -1, ignoredValues).isEmpty());
MappedFieldType valued = new ConstantKeywordFieldMapper.ConstantKeywordFieldType("field", "foo");
fetcher = valued.valueFetcher(null, null);
assertEquals(List.of("foo"), fetcher.fetchValues(sourceWithNoFieldValue, -1, ignoredValues));
assertEquals(List.of("foo"), fetcher.fetchValues(sourceWithNullFieldValue, -1, ignoredValues));
}
@Override
public MappedFieldType getMappedFieldType() {
return new ConstantKeywordFieldMapper.ConstantKeywordFieldType(randomAlphaOfLength(5), randomAlphaOfLength(5));
}
}
| ConstantKeywordFieldTypeTests |
java | apache__hadoop | hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/Nfs3Constant.java | {
"start": 1209,
"end": 5244
} | enum ____ {
// the order of the values below are significant.
NULL,
GETATTR,
SETATTR,
LOOKUP,
ACCESS,
READLINK,
READ,
WRITE,
CREATE(false),
MKDIR(false),
SYMLINK(false),
MKNOD(false),
REMOVE(false),
RMDIR(false),
RENAME(false),
LINK(false),
READDIR,
READDIRPLUS,
FSSTAT,
FSINFO,
PATHCONF,
COMMIT;
private final boolean isIdempotent;
private NFSPROC3(boolean isIdempotent) {
this.isIdempotent = isIdempotent;
}
private NFSPROC3() {
this(true);
}
public boolean isIdempotent() {
return isIdempotent;
}
/** @return the int value representing the procedure. */
public int getValue() {
return ordinal();
}
/**
* Convert to NFS procedure.
* @param value specify the index of NFS procedure
* @return the procedure corresponding to the value.
*/
public static NFSPROC3 fromValue(int value) {
if (value < 0 || value >= values().length) {
return null;
}
return values()[value];
}
}
// The maximum size in bytes of the opaque file handle.
public final static int NFS3_FHSIZE = 64;
// The byte size of cookie verifier passed by READDIR and READDIRPLUS.
public final static int NFS3_COOKIEVERFSIZE = 8;
// The size in bytes of the opaque verifier used for exclusive CREATE.
public final static int NFS3_CREATEVERFSIZE = 8;
// The size in bytes of the opaque verifier used for asynchronous WRITE.
public final static int NFS3_WRITEVERFSIZE = 8;
/** Access call request mode */
// File access mode
public static final int ACCESS_MODE_READ = 0x04;
public static final int ACCESS_MODE_WRITE = 0x02;
public static final int ACCESS_MODE_EXECUTE = 0x01;
/** Access call response rights */
// Read data from file or read a directory.
public final static int ACCESS3_READ = 0x0001;
// Look up a name in a directory (no meaning for non-directory objects).
public final static int ACCESS3_LOOKUP = 0x0002;
// Rewrite existing file data or modify existing directory entries.
public final static int ACCESS3_MODIFY = 0x0004;
// Write new data or add directory entries.
public final static int ACCESS3_EXTEND = 0x0008;
// Delete an existing directory entry.
public final static int ACCESS3_DELETE = 0x0010;
// Execute file (no meaning for a directory).
public final static int ACCESS3_EXECUTE = 0x0020;
/** File and directory attribute mode bits */
// Set user ID on execution.
public final static int MODE_S_ISUID = 0x00800;
// Set group ID on execution.
public final static int MODE_S_ISGID = 0x00400;
// Save swapped text (not defined in POSIX).
public final static int MODE_S_ISVTX = 0x00200;
// Read permission for owner.
public final static int MODE_S_IRUSR = 0x00100;
// Write permission for owner.
public final static int MODE_S_IWUSR = 0x00080;
// Execute permission for owner on a file. Or lookup (search) permission for
// owner in directory.
public final static int MODE_S_IXUSR = 0x00040;
// Read permission for group.
public final static int MODE_S_IRGRP = 0x00020;
// Write permission for group.
public final static int MODE_S_IWGRP = 0x00010;
// Execute permission for group on a file. Or lookup (search) permission for
// group in directory.
public final static int MODE_S_IXGRP = 0x00008;
// Read permission for others.
public final static int MODE_S_IROTH = 0x00004;
// Write permission for others.
public final static int MODE_S_IWOTH = 0x00002;
// Execute permission for others on a file. Or lookup (search) permission for
// others in directory.
public final static int MODE_S_IXOTH = 0x00001;
public final static int MODE_ALL = MODE_S_ISUID | MODE_S_ISGID | MODE_S_ISVTX
| MODE_S_ISVTX | MODE_S_IRUSR | MODE_S_IRUSR | MODE_S_IWUSR
| MODE_S_IXUSR | MODE_S_IRGRP | MODE_S_IWGRP | MODE_S_IXGRP
| MODE_S_IROTH | MODE_S_IWOTH | MODE_S_IXOTH;
/** Write call flavors */
public | NFSPROC3 |
java | reactor__reactor-core | reactor-core-micrometer/src/main/java/reactor/core/observability/micrometer/TimedScheduler.java | {
"start": 10899,
"end": 11942
} | class ____ extends TimedRunnable {
final Scheduler scheduler;
SchedulerBackedTimedRunnable(MeterRegistry registry, TimedScheduler timedScheduler,
Scheduler scheduler, Runnable task) {
super(registry, timedScheduler, task, null);
this.scheduler = scheduler;
}
SchedulerBackedTimedRunnable(MeterRegistry registry, TimedScheduler timedScheduler,
Scheduler scheduler, Runnable task, boolean periodic) {
super(registry, timedScheduler, task, null, periodic);
this.scheduler = scheduler;
}
@Override
Disposable internalSchedule() {
return scheduler.schedule(this);
}
@Override
Disposable internalSchedule(long delay, TimeUnit unit) {
return scheduler.schedule(this, delay, unit);
}
@Override
Disposable internalSchedulePeriodically(long initialDelay, long period, TimeUnit unit) {
return scheduler.schedulePeriodically(this, initialDelay, period, unit);
}
}
/**
* Copy of reactor.core.scheduler.EmptyCompositeDisposable for internal use.
*/
static final | SchedulerBackedTimedRunnable |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/Rounding.java | {
"start": 35995,
"end": 39118
} | class ____ extends AbstractNotToMidnightRounding {
JavaTimeNotToMidnightRounding(long unitMillis) {
super(unitMillis);
}
@Override
public long round(long utcMillis) {
Instant instant = Instant.ofEpochMilli(utcMillis);
final ZoneRules rules = timeZone.getRules();
while (true) {
final Instant truncatedTime = truncateAsLocalTime(instant, rules);
final ZoneOffsetTransition previousTransition = rules.previousTransition(instant);
if (previousTransition == null) {
// truncateAsLocalTime cannot have failed if there were no previous transitions
return truncatedTime.toEpochMilli();
}
Instant previousTransitionInstant = previousTransition.getInstant();
if (truncatedTime != null && previousTransitionInstant.compareTo(truncatedTime) < 1) {
return truncatedTime.toEpochMilli();
}
// There was a transition in between the input time and the truncated time. Return to the transition time and
// round that down instead.
instant = previousTransitionInstant.minusNanos(1_000_000);
}
}
private Instant truncateAsLocalTime(Instant instant, final ZoneRules rules) {
assert unitRoundsToMidnight == false : "truncateAsLocalTime should not be called if unitRoundsToMidnight";
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, timeZone);
final LocalDateTime truncatedLocalDateTime = truncateLocalDateTime(localDateTime);
final List<ZoneOffset> currentOffsets = rules.getValidOffsets(truncatedLocalDateTime);
if (currentOffsets.isEmpty() == false) {
// at least one possibilities - choose the latest one that's still no later than the input time
for (int offsetIndex = currentOffsets.size() - 1; offsetIndex >= 0; offsetIndex--) {
final Instant result = truncatedLocalDateTime.atOffset(currentOffsets.get(offsetIndex)).toInstant();
if (result.isAfter(instant) == false) {
return result;
}
}
assert false : "rounded time not found for " + instant + " with " + this;
return null;
} else {
// The chosen local time didn't happen. This means we were given a time in an hour (or a minute) whose start
// is missing due to an offset transition, so the time cannot be truncated.
return null;
}
}
@Override
public String toString() {
return TimeUnitRounding.this + "[java.time to " + unitMillis + "]";
}
}
private abstract | JavaTimeNotToMidnightRounding |
java | netty__netty | transport/src/test/java/io/netty/channel/CombinedChannelDuplexHandlerTest.java | {
"start": 1804,
"end": 13151
} | enum ____ {
REGISTERED,
UNREGISTERED,
ACTIVE,
INACTIVE,
CHANNEL_READ,
CHANNEL_READ_COMPLETE,
EXCEPTION_CAUGHT,
USER_EVENT_TRIGGERED,
CHANNEL_WRITABILITY_CHANGED,
HANDLER_ADDED,
HANDLER_REMOVED,
BIND,
CONNECT,
WRITE,
FLUSH,
READ,
REGISTER,
DEREGISTER,
CLOSE,
DISCONNECT
}
@Test
public void testInboundRemoveBeforeAdded() {
final CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
new ChannelInboundHandlerAdapter(), new ChannelOutboundHandlerAdapter());
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
handler.removeInboundHandler();
}
});
}
@Test
public void testOutboundRemoveBeforeAdded() {
final CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
new ChannelInboundHandlerAdapter(), new ChannelOutboundHandlerAdapter());
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
handler.removeOutboundHandler();
}
});
}
@Test
public void testInboundHandlerImplementsOutboundHandler() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
new ChannelDuplexHandler(), new ChannelOutboundHandlerAdapter());
}
});
}
@Test
public void testOutboundHandlerImplementsInboundHandler() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
new ChannelInboundHandlerAdapter(), new ChannelDuplexHandler());
}
});
}
@Test
public void testInitNotCalledBeforeAdded() {
final CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>() { };
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() throws Throwable {
handler.handlerAdded(null);
}
});
}
@Test
public void testExceptionCaughtBothCombinedHandlers() {
final Exception exception = new Exception();
final Queue<ChannelHandler> queue = new ArrayDeque<ChannelHandler>();
ChannelInboundHandler inboundHandler = new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
assertSame(exception, cause);
queue.add(this);
ctx.fireExceptionCaught(cause);
}
};
ChannelOutboundHandler outboundHandler = new ChannelOutboundHandlerAdapter() {
@SuppressWarnings("deprecation")
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
assertSame(exception, cause);
queue.add(this);
ctx.fireExceptionCaught(cause);
}
};
ChannelInboundHandler lastHandler = new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
assertSame(exception, cause);
queue.add(this);
}
};
EmbeddedChannel channel = new EmbeddedChannel(
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
inboundHandler, outboundHandler), lastHandler);
channel.pipeline().fireExceptionCaught(exception);
assertFalse(channel.finish());
assertSame(inboundHandler, queue.poll());
assertSame(outboundHandler, queue.poll());
assertSame(lastHandler, queue.poll());
assertTrue(queue.isEmpty());
}
@Test
public void testInboundEvents() {
InboundEventHandler inboundHandler = new InboundEventHandler();
CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
inboundHandler, new ChannelOutboundHandlerAdapter());
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast(handler);
assertEquals(Event.HANDLER_ADDED, inboundHandler.pollEvent());
doInboundOperations(channel);
assertInboundOperations(inboundHandler);
handler.removeInboundHandler();
assertEquals(Event.HANDLER_REMOVED, inboundHandler.pollEvent());
// These should not be handled by the inboundHandler anymore as it was removed before
doInboundOperations(channel);
// Should have not received any more events as it was removed before via removeInboundHandler()
assertNull(inboundHandler.pollEvent());
try {
channel.checkException();
fail();
} catch (Throwable cause) {
assertSame(CAUSE, cause);
}
assertTrue(channel.finish());
assertNull(inboundHandler.pollEvent());
}
@Test
public void testOutboundEvents() {
ChannelInboundHandler inboundHandler = new ChannelInboundHandlerAdapter();
OutboundEventHandler outboundHandler = new OutboundEventHandler();
CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler> handler =
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
inboundHandler, outboundHandler);
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast(new OutboundEventHandler());
channel.pipeline().addLast(handler);
assertEquals(Event.HANDLER_ADDED, outboundHandler.pollEvent());
doOutboundOperations(channel);
assertOutboundOperations(outboundHandler);
handler.removeOutboundHandler();
assertEquals(Event.HANDLER_REMOVED, outboundHandler.pollEvent());
// These should not be handled by the inboundHandler anymore as it was removed before
doOutboundOperations(channel);
// Should have not received any more events as it was removed before via removeInboundHandler()
assertNull(outboundHandler.pollEvent());
assertFalse(channel.finish());
assertNull(outboundHandler.pollEvent());
}
private static void doOutboundOperations(Channel channel) {
channel.pipeline().bind(LOCAL_ADDRESS).syncUninterruptibly();
channel.pipeline().connect(REMOTE_ADDRESS, LOCAL_ADDRESS).syncUninterruptibly();
channel.pipeline().write(MSG).syncUninterruptibly();
channel.pipeline().flush();
channel.pipeline().read();
channel.pipeline().disconnect().syncUninterruptibly();
channel.pipeline().close().syncUninterruptibly();
channel.pipeline().deregister().syncUninterruptibly();
}
private static void assertOutboundOperations(OutboundEventHandler outboundHandler) {
assertEquals(Event.BIND, outboundHandler.pollEvent());
assertEquals(Event.CONNECT, outboundHandler.pollEvent());
assertEquals(Event.WRITE, outboundHandler.pollEvent());
assertEquals(Event.FLUSH, outboundHandler.pollEvent());
assertEquals(Event.READ, outboundHandler.pollEvent());
assertEquals(Event.CLOSE, outboundHandler.pollEvent());
assertEquals(Event.CLOSE, outboundHandler.pollEvent());
assertEquals(Event.DEREGISTER, outboundHandler.pollEvent());
}
private static void doInboundOperations(Channel channel) {
channel.pipeline().fireChannelRegistered();
channel.pipeline().fireChannelActive();
channel.pipeline().fireChannelRead(MSG);
channel.pipeline().fireChannelReadComplete();
channel.pipeline().fireExceptionCaught(CAUSE);
channel.pipeline().fireUserEventTriggered(USER_EVENT);
channel.pipeline().fireChannelWritabilityChanged();
channel.pipeline().fireChannelInactive();
channel.pipeline().fireChannelUnregistered();
}
private static void assertInboundOperations(InboundEventHandler handler) {
assertEquals(Event.REGISTERED, handler.pollEvent());
assertEquals(Event.ACTIVE, handler.pollEvent());
assertEquals(Event.CHANNEL_READ, handler.pollEvent());
assertEquals(Event.CHANNEL_READ_COMPLETE, handler.pollEvent());
assertEquals(Event.EXCEPTION_CAUGHT, handler.pollEvent());
assertEquals(Event.USER_EVENT_TRIGGERED, handler.pollEvent());
assertEquals(Event.CHANNEL_WRITABILITY_CHANGED, handler.pollEvent());
assertEquals(Event.INACTIVE, handler.pollEvent());
assertEquals(Event.UNREGISTERED, handler.pollEvent());
}
@Test
@Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
public void testPromisesPassed() {
OutboundEventHandler outboundHandler = new OutboundEventHandler();
EmbeddedChannel ch = new EmbeddedChannel(outboundHandler,
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>(
new ChannelInboundHandlerAdapter(), new ChannelOutboundHandlerAdapter()));
ChannelPipeline pipeline = ch.pipeline();
ChannelPromise promise = ch.newPromise();
pipeline.bind(LOCAL_ADDRESS, promise);
promise.syncUninterruptibly();
promise = ch.newPromise();
pipeline.connect(REMOTE_ADDRESS, LOCAL_ADDRESS, promise);
promise.syncUninterruptibly();
promise = ch.newPromise();
pipeline.close(promise);
promise.syncUninterruptibly();
promise = ch.newPromise();
pipeline.disconnect(promise);
promise.syncUninterruptibly();
promise = ch.newPromise();
pipeline.write(MSG, promise);
promise.syncUninterruptibly();
promise = ch.newPromise();
pipeline.deregister(promise);
promise.syncUninterruptibly();
ch.finish();
}
@Test
public void testNotSharable() {
assertThrows(IllegalStateException.class, new Executable() {
@Override
public void execute() {
new CombinedChannelDuplexHandler<ChannelInboundHandler, ChannelOutboundHandler>() {
@Override
public boolean isSharable() {
return true;
}
};
}
});
}
private static final | Event |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/authentication/ui/HtmlTemplatesTests.java | {
"start": 911,
"end": 3816
} | class ____ {
@Test
void processTemplateWhenNoVariablesThenRendersTemplate() {
String template = """
<ul>
<li>Lorem ipsum dolor sit amet</li>
<li>consectetur adipiscing elit</li>
<li>sed do eiusmod tempor incididunt ut labore</li>
<li>et dolore magna aliqua</li>
</ul>
""";
assertThat(HtmlTemplates.fromTemplate(template).render()).isEqualTo(template);
}
@Test
void renderWhenVariablesThenRendersTemplate() {
String template = """
<ul>
<li>{{one}}</li>
<li>{{two}}</li>
</ul>
""";
String renderedTemplate = HtmlTemplates.fromTemplate(template)
.withValue("one", "Lorem ipsum dolor sit amet")
.withValue("two", "consectetur adipiscing elit")
.render();
assertThat(renderedTemplate).isEqualTo("""
<ul>
<li>Lorem ipsum dolor sit amet</li>
<li>consectetur adipiscing elit</li>
</ul>
""");
}
@Test
void renderWhenVariablesThenEscapedAndRender() {
String template = "<p>{{content}}</p>";
String renderedTemplate = HtmlTemplates.fromTemplate(template)
.withValue("content", "The <a> tag is very common in HTML.")
.render();
assertThat(renderedTemplate).isEqualTo("<p>The <a> tag is very common in HTML.</p>");
}
@Test
void renderWhenRawHtmlVariablesThenRendersTemplate() {
String template = """
<p>
The {{title}} is a placeholder text used in print.
</p>
""";
String renderedTemplate = HtmlTemplates.fromTemplate(template)
.withRawHtml("title", "<strong>Lorem Ipsum</strong>")
.render();
assertThat(renderedTemplate).isEqualTo("""
<p>
The <strong>Lorem Ipsum</strong> is a placeholder text used in print.
</p>
""");
}
@Test
void renderWhenRawHtmlVariablesThenTrimsTrailingNewline() {
String template = """
<ul>
{{content}}
</ul>
""";
String renderedTemplate = HtmlTemplates.fromTemplate(template)
.withRawHtml("content", "<li>Lorem ipsum dolor sit amet</li>".indent(2))
.render();
assertThat(renderedTemplate).isEqualTo("""
<ul>
<li>Lorem ipsum dolor sit amet</li>
</ul>
""");
}
@Test
void renderWhenEmptyVariablesThenRender() {
String template = """
<li>One: {{one}}</li>
{{two}}
""";
String renderedTemplate = HtmlTemplates.fromTemplate(template)
.withValue("one", "")
.withRawHtml("two", "")
.render();
assertThat(renderedTemplate).isEqualTo("""
<li>One: </li>
""");
}
@Test
void renderWhenMissingVariablesThenThrows() {
String template = """
<li>One: {{one}}</li>
<li>Two: {{two}}</li>
{{three}}
""";
HtmlTemplates.Builder templateBuilder = HtmlTemplates.fromTemplate(template)
.withValue("one", "Lorem ipsum dolor sit amet");
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(templateBuilder::render)
.withMessage("Unused placeholders in template: [two, three]");
}
}
| HtmlTemplatesTests |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java | {
"start": 3801,
"end": 20706
} | class ____ extends ESTestCase {
private static final Settings SETTINGS = Settings.builder()
.put(Node.NODE_NAME_SETTING.getKey(), "TokenServiceTests")
.put(XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey(), true)
.build();
private ThreadPool threadPool;
private TransportService transportService;
private Client client;
private SecurityIndexManager securityIndex;
private ClusterService clusterService;
private AtomicReference<IndexRequest> idxReqReference;
private AuthenticationService authenticationService;
private MockLicenseState license;
private SecurityContext securityContext;
@Before
public void setupClient() {
threadPool = new TestThreadPool(getTestName());
transportService = mock(TransportService.class);
client = mock(Client.class);
idxReqReference = new AtomicReference<>();
authenticationService = mock(AuthenticationService.class);
when(client.threadPool()).thenReturn(threadPool);
when(client.settings()).thenReturn(SETTINGS);
doAnswer(invocationOnMock -> {
GetRequestBuilder builder = new GetRequestBuilder(client);
builder.setIndex((String) invocationOnMock.getArguments()[0]).setId((String) invocationOnMock.getArguments()[1]);
return builder;
}).when(client).prepareGet(anyString(), anyString());
when(client.prepareMultiGet()).thenReturn(new MultiGetRequestBuilder(client));
doAnswer(invocationOnMock -> {
@SuppressWarnings("unchecked")
ActionListener<MultiGetResponse> listener = (ActionListener<MultiGetResponse>) invocationOnMock.getArguments()[1];
MultiGetResponse response = mock(MultiGetResponse.class);
MultiGetItemResponse[] responses = new MultiGetItemResponse[2];
when(response.getResponses()).thenReturn(responses);
GetResponse oldGetResponse = mock(GetResponse.class);
when(oldGetResponse.isExists()).thenReturn(false);
responses[0] = new MultiGetItemResponse(oldGetResponse, null);
GetResponse getResponse = mock(GetResponse.class);
responses[1] = new MultiGetItemResponse(getResponse, null);
when(getResponse.isExists()).thenReturn(false);
listener.onResponse(response);
return Void.TYPE;
}).when(client).multiGet(any(MultiGetRequest.class), anyActionListener());
when(client.prepareIndex(nullable(String.class))).thenReturn(new IndexRequestBuilder(client));
when(client.prepareUpdate(any(String.class), any(String.class))).thenReturn(new UpdateRequestBuilder(client));
doAnswer(invocationOnMock -> {
idxReqReference.set((IndexRequest) invocationOnMock.getArguments()[1]);
@SuppressWarnings("unchecked")
ActionListener<IndexResponse> responseActionListener = (ActionListener<IndexResponse>) invocationOnMock.getArguments()[2];
responseActionListener.onResponse(
new IndexResponse(
new ShardId(".security", UUIDs.randomBase64UUID(), randomInt()),
randomAlphaOfLength(4),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
true
)
);
return null;
}).when(client).execute(eq(TransportIndexAction.TYPE), any(IndexRequest.class), anyActionListener());
securityContext = new SecurityContext(Settings.EMPTY, threadPool.getThreadContext());
// setup lifecycle service
securityIndex = mock(SecurityIndexManager.class);
SecurityIndexManager.IndexState projectIndex = mock(SecurityIndexManager.IndexState.class);
when(securityIndex.forCurrentProject()).thenReturn(projectIndex);
doAnswer(invocationOnMock -> {
Runnable runnable = (Runnable) invocationOnMock.getArguments()[1];
runnable.run();
return null;
}).when(projectIndex).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class));
doAnswer(invocationOnMock -> {
AuthenticationToken authToken = (AuthenticationToken) invocationOnMock.getArguments()[2];
@SuppressWarnings("unchecked")
ActionListener<Authentication> authListener = (ActionListener<Authentication>) invocationOnMock.getArguments()[3];
User user = null;
if (authToken instanceof UsernamePasswordToken) {
UsernamePasswordToken token = (UsernamePasswordToken) invocationOnMock.getArguments()[2];
user = new User(token.principal());
} else if (authToken instanceof KerberosAuthenticationToken) {
KerberosAuthenticationToken token = (KerberosAuthenticationToken) invocationOnMock.getArguments()[2];
if (token.credentials() instanceof byte[]
&& new String((byte[]) token.credentials(), StandardCharsets.UTF_8).equals("fail")) {
String errorMessage = "failed to authenticate user, gss context negotiation not complete";
ElasticsearchSecurityException ese = new ElasticsearchSecurityException(errorMessage, RestStatus.UNAUTHORIZED);
ese.addBodyHeader(KerberosAuthenticationToken.WWW_AUTHENTICATE, "Negotiate FAIL");
authListener.onFailure(ese);
return Void.TYPE;
}
user = new User(token.principal());
threadPool.getThreadContext().addResponseHeader(KerberosAuthenticationToken.WWW_AUTHENTICATE, "Negotiate SUCCESS");
}
Authentication authentication = AuthenticationTestHelper.builder()
.user(user)
.realmRef(new Authentication.RealmRef("fake", "mock", "n1"))
.build(false);
authentication.writeToContext(threadPool.getThreadContext());
authListener.onResponse(authentication);
return Void.TYPE;
}).when(authenticationService)
.authenticate(eq(CreateTokenAction.NAME), any(CreateTokenRequest.class), any(AuthenticationToken.class), anyActionListener());
this.clusterService = ClusterServiceUtils.createClusterService(threadPool);
this.license = mock(MockLicenseState.class);
when(license.isAllowed(Security.TOKEN_SERVICE_FEATURE)).thenReturn(true);
}
@After
public void stopThreadPool() throws Exception {
if (threadPool != null) {
terminate(threadPool);
}
}
public void testClientCredentialsCreatesWithoutRefreshToken() throws Exception {
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
Authentication authentication = AuthenticationTestHelper.builder()
.user(new User("joe"))
.realmRef(new Authentication.RealmRef("realm", "type", "node"))
.build(false);
authentication.writeToContext(threadPool.getThreadContext());
final TransportCreateTokenAction action = new TransportCreateTokenAction(
threadPool,
transportService,
new ActionFilters(Collections.emptySet()),
tokenService,
authenticationService,
securityContext
);
final CreateTokenRequest createTokenRequest = new CreateTokenRequest();
createTokenRequest.setGrantType("client_credentials");
PlainActionFuture<CreateTokenResponse> tokenResponseFuture = new PlainActionFuture<>();
action.doExecute(null, createTokenRequest, tokenResponseFuture);
CreateTokenResponse createTokenResponse = tokenResponseFuture.get();
assertNull(createTokenResponse.getRefreshToken());
assertNotNull(createTokenResponse.getTokenString());
assertNotNull(idxReqReference.get());
Map<String, Object> sourceMap = idxReqReference.get().sourceAsMap();
assertNotNull(sourceMap);
assertNotNull(sourceMap.get("access_token"));
assertNull(sourceMap.get("refresh_token"));
}
public void testPasswordGrantTypeCreatesWithRefreshToken() throws Exception {
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
Authentication authentication = AuthenticationTestHelper.builder()
.user(new User("joe"))
.realmRef(new Authentication.RealmRef("realm", "type", "node"))
.build(false);
authentication.writeToContext(threadPool.getThreadContext());
final TransportCreateTokenAction action = new TransportCreateTokenAction(
threadPool,
transportService,
new ActionFilters(Collections.emptySet()),
tokenService,
authenticationService,
securityContext
);
final CreateTokenRequest createTokenRequest = new CreateTokenRequest();
createTokenRequest.setGrantType("password");
createTokenRequest.setUsername("user");
createTokenRequest.setPassword(new SecureString("password".toCharArray()));
PlainActionFuture<CreateTokenResponse> tokenResponseFuture = new PlainActionFuture<>();
action.doExecute(null, createTokenRequest, tokenResponseFuture);
CreateTokenResponse createTokenResponse = tokenResponseFuture.get();
assertNotNull(createTokenResponse.getRefreshToken());
assertNotNull(createTokenResponse.getTokenString());
assertNotNull(idxReqReference.get());
Map<String, Object> sourceMap = idxReqReference.get().sourceAsMap();
assertNotNull(sourceMap);
assertNotNull(sourceMap.get("access_token"));
assertNotNull(sourceMap.get("refresh_token"));
}
public void testKerberosGrantTypeCreatesWithRefreshToken() throws Exception {
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
Authentication authentication = AuthenticationTestHelper.builder()
.user(new User("joe"))
.realmRef(new Authentication.RealmRef("realm", "type", "node"))
.build(false);
authentication.writeToContext(threadPool.getThreadContext());
final TransportCreateTokenAction action = new TransportCreateTokenAction(
threadPool,
transportService,
new ActionFilters(Collections.emptySet()),
tokenService,
authenticationService,
securityContext
);
final CreateTokenRequest createTokenRequest = new CreateTokenRequest();
createTokenRequest.setGrantType("_kerberos");
String failOrSuccess = randomBoolean() ? "fail" : "success";
String kerbCredentialsBase64 = Base64.getEncoder().encodeToString(failOrSuccess.getBytes(StandardCharsets.UTF_8));
createTokenRequest.setKerberosTicket(new SecureString(kerbCredentialsBase64.toCharArray()));
PlainActionFuture<CreateTokenResponse> tokenResponseFuture = new PlainActionFuture<>();
action.doExecute(null, createTokenRequest, tokenResponseFuture);
if (failOrSuccess.equals("fail")) {
ElasticsearchSecurityException ese = expectThrows(ElasticsearchSecurityException.class, () -> tokenResponseFuture.actionGet());
assertNotNull(ese.getBodyHeader(KerberosAuthenticationToken.WWW_AUTHENTICATE));
assertThat(ese.getBodyHeader(KerberosAuthenticationToken.WWW_AUTHENTICATE).size(), is(1));
assertThat(ese.getBodyHeader(KerberosAuthenticationToken.WWW_AUTHENTICATE).get(0), is("Negotiate FAIL"));
} else {
CreateTokenResponse createTokenResponse = tokenResponseFuture.get();
assertNotNull(createTokenResponse.getRefreshToken());
assertNotNull(createTokenResponse.getTokenString());
assertNotNull(createTokenResponse.getKerberosAuthenticationResponseToken());
assertThat(createTokenResponse.getKerberosAuthenticationResponseToken(), is("SUCCESS"));
assertNotNull(idxReqReference.get());
Map<String, Object> sourceMap = idxReqReference.get().sourceAsMap();
assertNotNull(sourceMap);
assertNotNull(sourceMap.get("access_token"));
assertNotNull(sourceMap.get("refresh_token"));
}
}
public void testKerberosGrantTypeWillFailOnBase64DecodeError() throws Exception {
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
Authentication authentication = AuthenticationTestHelper.builder()
.user(new User("joe"))
.realmRef(new Authentication.RealmRef("realm", "type", "node"))
.build(false);
authentication.writeToContext(threadPool.getThreadContext());
final TransportCreateTokenAction action = new TransportCreateTokenAction(
threadPool,
transportService,
new ActionFilters(Collections.emptySet()),
tokenService,
authenticationService,
securityContext
);
final CreateTokenRequest createTokenRequest = new CreateTokenRequest();
createTokenRequest.setGrantType("_kerberos");
final char[] invalidBase64Chars = "!\"#$%&\\'()*,.:;<>?@[]^_`{|}~\t\n\r".toCharArray();
final String kerberosTicketValue = Strings.arrayToDelimitedString(
randomArray(1, 10, Character[]::new, () -> invalidBase64Chars[randomIntBetween(0, invalidBase64Chars.length - 1)]),
""
);
createTokenRequest.setKerberosTicket(new SecureString(kerberosTicketValue.toCharArray()));
PlainActionFuture<CreateTokenResponse> tokenResponseFuture = new PlainActionFuture<>();
action.doExecute(null, createTokenRequest, assertListenerIsOnlyCalledOnce(tokenResponseFuture));
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class, () -> tokenResponseFuture.actionGet());
assertThat(e.getMessage(), containsString("could not decode base64 kerberos ticket"));
// The code flow should stop after above failure and never reach authenticationService
Mockito.verifyNoMoreInteractions(authenticationService);
}
public void testServiceAccountCannotCreateOAuthToken() throws Exception {
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
Authentication authentication = AuthenticationTestHelper.builder().serviceAccount().build(false);
authentication.writeToContext(threadPool.getThreadContext());
final TransportCreateTokenAction action = new TransportCreateTokenAction(
threadPool,
transportService,
new ActionFilters(Collections.emptySet()),
tokenService,
authenticationService,
securityContext
);
final CreateTokenRequest createTokenRequest = new CreateTokenRequest();
createTokenRequest.setGrantType("client_credentials");
PlainActionFuture<CreateTokenResponse> future = new PlainActionFuture<>();
action.doExecute(null, createTokenRequest, future);
final ElasticsearchException e = expectThrows(ElasticsearchException.class, future::actionGet);
assertThat(e.getMessage(), containsString("OAuth2 token creation is not supported for service accounts"));
}
private static <T> ActionListener<T> assertListenerIsOnlyCalledOnce(ActionListener<T> delegate) {
final AtomicInteger callCount = new AtomicInteger(0);
return ActionListener.runBefore(delegate, () -> {
if (callCount.incrementAndGet() != 1) {
fail("Listener was called twice");
}
});
}
@SuppressWarnings("unchecked")
private static <T> Consumer<T> anyConsumer() {
return any(Consumer.class);
}
}
| TransportCreateTokenActionTests |
java | micronaut-projects__micronaut-core | core/src/main/java/io/micronaut/core/annotation/AnnotationValue.java | {
"start": 54873,
"end": 58643
} | class ____ be present at compilation time
if (value == null) {
return null;
}
if (value instanceof AnnotationClassValue<?> annotationClassValue) {
Class<?> type = annotationClassValue.getType().orElse(null);
if (type != null) {
return new Class<?>[]{type};
}
return null;
}
if (value instanceof AnnotationValue<?>[] annotationValues) {
int len = annotationValues.length;
if (len > 0) {
if (len == 1) {
return annotationValues[0].classValues();
} else {
List<Class<?>> list = new ArrayList<>(5);
for (AnnotationValue<?> annotationValue : annotationValues) {
list.addAll(Arrays.asList(annotationValue.classValues()));
}
return list.toArray(EMPTY_CLASS_ARRAY);
}
}
return null;
}
if (value instanceof AnnotationValue<?> annotationValue) {
return annotationValue.classValues();
}
if (value instanceof Object[] values) {
if (values instanceof Class<?>[] classes) {
return classes;
} else {
List<Class<?>> list = new ArrayList<>(5);
for (Object o : values) {
if (o instanceof AnnotationClassValue<?> annotationClassValue) {
if (annotationClassValue.theClass != null) {
list.add(annotationClassValue.theClass);
}
} else if (o instanceof Class<?> aClass) {
list.add(aClass);
}
}
return list.toArray(EMPTY_CLASS_ARRAY);
}
}
if (value instanceof Class<?> aClass) {
return new Class<?>[]{aClass};
}
return null;
}
/**
* Subclasses can override to provide a custom convertible values instance.
*
* @param values The values
* @return The instance
*/
private ConvertibleValues<Object> newConvertibleValues(Map<CharSequence, Object> values) {
if (CollectionUtils.isEmpty(values)) {
return ConvertibleValues.EMPTY;
} else {
return ConvertibleValues.of(values);
}
}
@Nullable
private Object getRawSingleValue(@NonNull String member, Function<Object, Object> valueMapper) {
Object rawValue = values.get(member);
if (rawValue != null) {
if (rawValue.getClass().isArray()) {
int len = Array.getLength(rawValue);
if (len > 0) {
rawValue = Array.get(rawValue, 0);
}
} else if (rawValue instanceof Iterable<?> iterable) {
Iterator<?> i = iterable.iterator();
if (i.hasNext()) {
rawValue = i.next();
}
}
}
if (valueMapper != null && (rawValue instanceof String || rawValue instanceof EvaluatedExpression)) {
return valueMapper.apply(rawValue);
}
return rawValue;
}
private static <T extends Enum> Optional<T> convertToEnum(Class<T> enumType, Object o) {
if (enumType.isInstance(o)) {
return Optional.of((T) o);
} else {
try {
T t = (T) Enum.valueOf(enumType, o.toString());
return Optional.of(t);
} catch (IllegalArgumentException ex) {
return Optional.empty();
}
}
}
/**
* Creates {@link AnnotationClassValue} from the | can |
java | micronaut-projects__micronaut-core | function/src/main/java/io/micronaut/function/executor/FunctionExitHandler.java | {
"start": 661,
"end": 793
} | interface ____ handling exiting from a function when it is executed via the CLI.
*
* @author graemerocher
* @since 1.0
*/
public | for |
java | quarkusio__quarkus | integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/MinikubeWithMixedStyleEnvTest.java | {
"start": 648,
"end": 3925
} | class ____ {
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
.setApplicationName("minikube-with-mixed-style-env")
.setApplicationVersion("0.1-SNAPSHOT")
.withConfigurationResource("minikube-with-mixed-style-env.properties")
.setForcedDependencies(List.of(Dependency.of("io.quarkus", "quarkus-minikube", Version.getVersion())));
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
public void assertGeneratedResources() throws IOException {
Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
assertThat(kubernetesDir)
.isDirectoryContaining(p -> p.getFileName().endsWith("minikube.json"))
.isDirectoryContaining(p -> p.getFileName().endsWith("minikube.yml"));
List<HasMetadata> kubernetesList = DeserializationUtil
.deserializeAsList(kubernetesDir.resolve("minikube.yml"));
assertThat(kubernetesList).filteredOn(i -> "Deployment".equals(i.getKind())).singleElement().satisfies(i -> {
assertThat(i).isInstanceOfSatisfying(Deployment.class, d -> {
assertThat(d.getSpec()).satisfies(deploymentSpec -> {
assertThat(deploymentSpec.getTemplate()).satisfies(t -> {
assertThat(t.getSpec()).satisfies(podSpec -> {
assertThat(podSpec.getContainers()).singleElement().satisfies(container -> {
assertThat(container.getEnv())
.filteredOn(env -> "FROMFIELD".equals(env.getName()))
.singleElement().satisfies(
env -> assertThat(env.getValueFrom().getFieldRef().getFieldPath())
.isEqualTo("metadata.name"));
assertThat(container.getEnv())
.filteredOn(env -> "ENVVAR".equals(env.getName()))
.singleElement().satisfies(env -> assertThat(env.getValue()).isEqualTo("value"));
final List<EnvFromSource> envFrom = container.getEnvFrom();
assertThat(envFrom).hasSize(2);
assertThat(envFrom)
.filteredOn(e -> e.getSecretRef() != null)
.singleElement().satisfies(
e -> assertThat(e.getSecretRef().getName()).isEqualTo("secretName"));
assertThat(envFrom)
.filteredOn(e -> e.getConfigMapRef() != null)
.singleElement().satisfies(
e -> assertThat(e.getConfigMapRef().getName()).isEqualTo("configName"));
});
});
});
});
});
});
}
}
| MinikubeWithMixedStyleEnvTest |
java | google__guava | android/guava-tests/test/com/google/common/cache/PopulatedCachesTest.java | {
"start": 12321,
"end": 16069
} | class ____ against every one of these caches. */
private Iterable<LoadingCache<Object, Object>> caches() {
// lots of different ways to configure a LoadingCache
CacheBuilderFactory factory = cacheFactory();
return Iterables.transform(
factory.buildAllPermutations(),
new Function<CacheBuilder<Object, Object>, LoadingCache<Object, Object>>() {
@Override
public LoadingCache<Object, Object> apply(CacheBuilder<Object, Object> builder) {
return builder.recordStats().build(identityLoader());
}
});
}
private CacheBuilderFactory cacheFactory() {
// This is trickier than expected. We plan to put 15 values in each of these (WARMUP_MIN to
// WARMUP_MAX), but the tests assume no values get evicted. Even with a maximumSize of 100, one
// of the values gets evicted. With weak keys, we use identity equality, which means using
// System.identityHashCode, which means the assignment of keys to segments is nondeterministic,
// so more than (maximumSize / #segments) keys could get assigned to the same segment, which
// would cause one to be evicted.
return new CacheBuilderFactory()
.withKeyStrengths(ImmutableSet.of(Strength.STRONG, Strength.WEAK))
.withValueStrengths(ImmutableSet.copyOf(Strength.values()))
.withConcurrencyLevels(ImmutableSet.of(1, 4, 16, 64))
.withMaximumSizes(ImmutableSet.of(400, 1000))
.withInitialCapacities(ImmutableSet.of(0, 1, 10, 100, 1000))
.withExpireAfterWrites(
ImmutableSet.of(
// DurationSpec.of(500, MILLISECONDS),
DurationSpec.of(1, SECONDS), DurationSpec.of(1, DAYS)))
.withExpireAfterAccesses(
ImmutableSet.of(
// DurationSpec.of(500, MILLISECONDS),
DurationSpec.of(1, SECONDS), DurationSpec.of(1, DAYS)))
.withRefreshes(
ImmutableSet.of(
// DurationSpec.of(500, MILLISECONDS),
DurationSpec.of(1, SECONDS), DurationSpec.of(1, DAYS)));
}
private List<Entry<Object, Object>> warmUp(LoadingCache<Object, Object> cache) {
return warmUp(cache, WARMUP_MIN, WARMUP_MAX);
}
/**
* Returns the entries that were added to the map, so they won't fall out of a map with weak or
* soft references until the caller drops the reference to the returned entries.
*/
private List<Entry<Object, Object>> warmUp(
LoadingCache<Object, Object> cache, int minimum, int maximum) {
List<Entry<Object, Object>> entries = new ArrayList<>();
for (int i = minimum; i < maximum; i++) {
Object key = i;
Object value = cache.getUnchecked(key);
entries.add(entryOf(key, value));
}
return entries;
}
private Entry<Object, Object> entryOf(Object key, Object value) {
return Maps.immutableEntry(key, value);
}
private void assertMapSize(Map<?, ?> map, int size) {
assertThat(map).hasSize(size);
if (size > 0) {
assertThat(map.isEmpty()).isFalse();
} else {
assertThat(map.isEmpty()).isTrue();
}
assertCollectionSize(map.keySet(), size);
assertCollectionSize(map.entrySet(), size);
assertCollectionSize(map.values(), size);
}
@SuppressWarnings("IterablesSizeOfCollection") // we are testing our iterator implementation
private void assertCollectionSize(Collection<?> collection, int size) {
assertThat(collection.size()).isEqualTo(size);
if (size > 0) {
assertThat(collection.isEmpty()).isFalse();
} else {
assertThat(collection.isEmpty()).isTrue();
}
assertThat(Iterables.size(collection)).isEqualTo(size);
assertThat(Iterators.size(collection.iterator())).isEqualTo(size);
}
}
| run |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authorization/AuthorizationManagers.java | {
"start": 6379,
"end": 6583
} | interface ____<T> extends AuthorizationManager<T> {
@Override
AuthorizationResult authorize(Supplier<? extends @Nullable Authentication> authentication, T object);
}
}
| AuthorizationManagerCheckAdapter |
java | apache__camel | components/camel-cyberark-vault/src/generated/java/org/apache/camel/component/cyberark/vault/CyberArkVaultComponentConfigurer.java | {
"start": 741,
"end": 6761
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private org.apache.camel.component.cyberark.vault.CyberArkVaultConfiguration getOrCreateConfiguration(CyberArkVaultComponent target) {
if (target.getConfiguration() == null) {
target.setConfiguration(new org.apache.camel.component.cyberark.vault.CyberArkVaultConfiguration());
}
return target.getConfiguration();
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
CyberArkVaultComponent target = (CyberArkVaultComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "account": getOrCreateConfiguration(target).setAccount(property(camelContext, java.lang.String.class, value)); return true;
case "apikey":
case "apiKey": getOrCreateConfiguration(target).setApiKey(property(camelContext, java.lang.String.class, value)); return true;
case "authtoken":
case "authToken": getOrCreateConfiguration(target).setAuthToken(property(camelContext, java.lang.String.class, value)); return true;
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "certificatepath":
case "certificatePath": getOrCreateConfiguration(target).setCertificatePath(property(camelContext, java.lang.String.class, value)); return true;
case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.cyberark.vault.CyberArkVaultConfiguration.class, value)); return true;
case "conjurclient":
case "conjurClient": getOrCreateConfiguration(target).setConjurClient(property(camelContext, org.apache.camel.component.cyberark.vault.client.ConjurClient.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "operation": getOrCreateConfiguration(target).setOperation(property(camelContext, org.apache.camel.component.cyberark.vault.CyberArkVaultOperations.class, value)); return true;
case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "secretid":
case "secretId": getOrCreateConfiguration(target).setSecretId(property(camelContext, java.lang.String.class, value)); return true;
case "url": getOrCreateConfiguration(target).setUrl(property(camelContext, java.lang.String.class, value)); return true;
case "username": getOrCreateConfiguration(target).setUsername(property(camelContext, java.lang.String.class, value)); return true;
case "verifyssl":
case "verifySsl": getOrCreateConfiguration(target).setVerifySsl(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "account": return java.lang.String.class;
case "apikey":
case "apiKey": return java.lang.String.class;
case "authtoken":
case "authToken": return java.lang.String.class;
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "certificatepath":
case "certificatePath": return java.lang.String.class;
case "configuration": return org.apache.camel.component.cyberark.vault.CyberArkVaultConfiguration.class;
case "conjurclient":
case "conjurClient": return org.apache.camel.component.cyberark.vault.client.ConjurClient.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "operation": return org.apache.camel.component.cyberark.vault.CyberArkVaultOperations.class;
case "password": return java.lang.String.class;
case "secretid":
case "secretId": return java.lang.String.class;
case "url": return java.lang.String.class;
case "username": return java.lang.String.class;
case "verifyssl":
case "verifySsl": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
CyberArkVaultComponent target = (CyberArkVaultComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "account": return getOrCreateConfiguration(target).getAccount();
case "apikey":
case "apiKey": return getOrCreateConfiguration(target).getApiKey();
case "authtoken":
case "authToken": return getOrCreateConfiguration(target).getAuthToken();
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "certificatepath":
case "certificatePath": return getOrCreateConfiguration(target).getCertificatePath();
case "configuration": return target.getConfiguration();
case "conjurclient":
case "conjurClient": return getOrCreateConfiguration(target).getConjurClient();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "operation": return getOrCreateConfiguration(target).getOperation();
case "password": return getOrCreateConfiguration(target).getPassword();
case "secretid":
case "secretId": return getOrCreateConfiguration(target).getSecretId();
case "url": return getOrCreateConfiguration(target).getUrl();
case "username": return getOrCreateConfiguration(target).getUsername();
case "verifyssl":
case "verifySsl": return getOrCreateConfiguration(target).isVerifySsl();
default: return null;
}
}
}
| CyberArkVaultComponentConfigurer |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/BaseRecord.java | {
"start": 1381,
"end": 8000
} | class ____ implements Comparable<BaseRecord> {
public static final String ERROR_MSG_CREATION_TIME_NEGATIVE =
"The creation time for the record cannot be negative.";
public static final String ERROR_MSG_MODIFICATION_TIME_NEGATIVE =
"The modification time for the record cannot be negative.";
/**
* Set the modification time for the record.
*
* @param time Modification time of the record.
*/
public abstract void setDateModified(long time);
/**
* Get the modification time for the record.
*
* @return Modification time of the record.
*/
public abstract long getDateModified();
/**
* Set the creation time for the record.
*
* @param time Creation time of the record.
*/
public abstract void setDateCreated(long time);
/**
* Get the creation time for the record.
*
* @return Creation time of the record
*/
public abstract long getDateCreated();
/**
* Get the expiration time for the record.
*
* @return Expiration time for the record.
*/
public abstract long getExpirationMs();
/**
* Check if this record is expired. The default is false. Override for
* customized behavior.
*
* @return True if the record is expired.
*/
public boolean isExpired() {
return false;
}
/**
* Get the deletion time for the expired record. The default is disabled.
* Override for customized behavior.
*
* @return Deletion time for the expired record.
*/
public long getDeletionMs() {
return -1;
}
/**
* Map of primary key names to values for the record. The primary key can be
* a combination of 1-n different State Store serialized values.
*
* @return Map of key/value pairs that constitute this object's primary key.
*/
public abstract Map<String, String> getPrimaryKeys();
/**
* Initialize the object.
*/
public void init() {
// Call this after the object has been constructed
initDefaultTimes();
}
/**
* Initialize default times. The driver may update these timestamps on insert
* and/or update. This should only be called when initializing an object that
* is not backed by a data store.
*/
private void initDefaultTimes() {
long now = Time.now();
this.setDateCreated(now);
this.setDateModified(now);
}
/**
* Join the primary keys into one single primary key.
*
* @return A string that is guaranteed to be unique amongst all records of
* this type.
*/
public String getPrimaryKey() {
return generateMashupKey(getPrimaryKeys());
}
/**
* If the record has fields others than the primary keys. This is used by
* TestStateStoreDriverBase to skip the modification check.
*
* @return If the record has more fields.
*/
@VisibleForTesting
public boolean hasOtherFields() {
return true;
}
/**
* Generates a cache key from a map of values.
*
* @param keys Map of values.
* @return String mashup of key values.
*/
protected static String generateMashupKey(final Map<String, String> keys) {
StringBuilder builder = new StringBuilder();
for (Object value : keys.values()) {
if (builder.length() > 0) {
builder.append("-");
}
builder.append(value);
}
return builder.toString();
}
/**
* Check if this record matches a partial record.
*
* @param other Partial record.
* @return If this record matches.
*/
public boolean like(BaseRecord other) {
if (other == null) {
return false;
}
Map<String, String> thisKeys = this.getPrimaryKeys();
Map<String, String> otherKeys = other.getPrimaryKeys();
if (thisKeys == null) {
return otherKeys == null;
}
return thisKeys.equals(otherKeys);
}
/**
* Override equals check to use primary key(s) for comparison.
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BaseRecord)) {
return false;
}
BaseRecord baseObject = (BaseRecord) obj;
Map<String, String> keyset1 = this.getPrimaryKeys();
Map<String, String> keyset2 = baseObject.getPrimaryKeys();
return keyset1.equals(keyset2);
}
/**
* Override hash code to use primary key(s) for comparison.
*/
@Override
public int hashCode() {
Map<String, String> keyset = this.getPrimaryKeys();
return keyset.hashCode();
}
@Override
public int compareTo(BaseRecord record) {
if (record == null) {
return -1;
}
// Descending date order
return (int) (record.getDateModified() - this.getDateModified());
}
/**
* Called when the modification time and current time is available, checks for
* expirations.
*
* @param currentTime The current timestamp in ms from the data store, to be
* compared against the modification and creation dates of the
* object.
* @return boolean True if the record has been updated and should be
* committed to the data store. Override for customized behavior.
*/
public boolean checkExpired(long currentTime) {
long expiration = getExpirationMs();
long modifiedTime = getDateModified();
if (modifiedTime > 0 && expiration > 0) {
return (modifiedTime + expiration) < currentTime;
}
return false;
}
/**
* Called when this record is expired and expired deletion is enabled, checks
* for the deletion. If an expired record exists beyond the deletion time, it
* should be deleted.
*
* @param currentTime The current timestamp in ms from the data store, to be
* compared against the modification and creation dates of the
* object.
* @return boolean True if the record has been updated and should be
* deleted from the data store.
*/
public boolean shouldBeDeleted(long currentTime) {
long deletionTime = getDeletionMs();
if (isExpired() && deletionTime > 0) {
long elapsedTime = currentTime - (getDateModified() + getExpirationMs());
return elapsedTime > deletionTime;
} else {
return false;
}
}
/**
* Validates the record. Called when the record is created, populated from the
* state store, and before committing to the state store. If validate failed,
* there throws an exception.
*/
public void validate() {
if (getDateCreated() <= 0) {
throw new IllegalArgumentException(ERROR_MSG_CREATION_TIME_NEGATIVE);
} else if (getDateModified() <= 0) {
throw new IllegalArgumentException(ERROR_MSG_MODIFICATION_TIME_NEGATIVE);
}
}
@Override
public String toString() {
return getPrimaryKey();
}
} | BaseRecord |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8220ExtensionWithDITest.java | {
"start": 1008,
"end": 2114
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that the central url can be overridden by a user property.
*
* @throws Exception in case of failure
*/
@Test
public void testitModel() throws Exception {
File testDir = extractResources("/mng-8220-extension-with-di");
Verifier verifier = newVerifier(new File(testDir, "extensions").getAbsolutePath());
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier = newVerifier(new File(testDir, "test").getAbsolutePath());
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyTextInLog("[MNG-8220] DumbModelParser1 Called from extension");
verifier.verifyTextInLog("[MNG-8220] DumbModelParser2 Called from extension");
verifier.verifyTextInLog("[MNG-8220] DumbModelParser3 Called from extension");
verifier.verifyTextInLog("[MNG-8220] DumbModelParser4 Called from extension");
}
}
| MavenITmng8220ExtensionWithDITest |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java | {
"start": 24229,
"end": 24584
} | class ____ {
private final String foo;
private String bar;
public MixedInjection(String foo) {
this.foo = foo;
}
public String getFoo() {
return this.foo;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
@SuppressWarnings("unused")
private static final | MixedInjection |
java | apache__avro | lang/java/tools/src/test/java/org/apache/avro/tool/TestRpcReceiveAndSendTools.java | {
"start": 1094,
"end": 2200
} | class ____ {
/**
* Starts a server (using the tool) and sends a single message to it.
*/
@Test
void serveAndSend() throws Exception {
String protocolFile = System.getProperty("share.dir", "../../../share") + "/test/schemas/simple.avpr";
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
PrintStream p1 = new PrintStream(baos1);
RpcReceiveTool receive = new RpcReceiveTool();
receive.run1(null, p1, System.err,
Arrays.asList("http://0.0.0.0:0/", protocolFile, "hello", "-data", "\"Hello!\""));
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
PrintStream p2 = new PrintStream(baos2);
RpcSendTool send = new RpcSendTool();
send.run(null, p2, System.err, Arrays.asList("http://127.0.0.1:" + receive.server.getPort() + "/", protocolFile,
"hello", "-data", "{ \"greeting\": \"Hi!\" }"));
receive.run2(System.err);
assertTrue(baos1.toString("UTF-8").replace("\r", "").endsWith("hello\t{\"greeting\":\"Hi!\"}\n"));
assertEquals("\"Hello!\"\n", baos2.toString("UTF-8").replace("\r", ""));
}
}
| TestRpcReceiveAndSendTools |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/collection/embeddable/EmbeddableList2.java | {
"start": 1283,
"end": 8840
} | class ____ {
private Integer ele_id1 = null;
private StrTestNoProxyEntity entity1;
private StrTestNoProxyEntity entity2;
private StrTestNoProxyEntity entity3;
private StrTestNoProxyEntity entity4;
private StrTestNoProxyEntity entity4Copy;
private ManyToOneEagerComponent manyToOneComponent1;
private ManyToOneEagerComponent manyToOneComponent2;
private ManyToOneEagerComponent manyToOneComponent4;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
// Revision 1 (ele1: saving a list with 1 many-to-one component)
scope.inEntityManager( em -> {
em.getTransaction().begin();
EmbeddableListEntity2 ele1 = new EmbeddableListEntity2();
entity1 = new StrTestNoProxyEntity( "strTestEntity1" );
em.persist( entity1 ); //persisting the entities referenced by the components
entity2 = new StrTestNoProxyEntity( "strTestEntity2" );
em.persist( entity2 );
manyToOneComponent1 = new ManyToOneEagerComponent( entity1, "dataComponent1" );
ele1.getComponentList().add( manyToOneComponent1 );
em.persist( ele1 );
ele_id1 = ele1.getId();
em.getTransaction().commit();
// Revision 2 (ele1: changing the component)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
ele1.getComponentList().clear();
manyToOneComponent2 = new ManyToOneEagerComponent( entity2, "dataComponent2" );
ele1.getComponentList().add( manyToOneComponent2 );
em.getTransaction().commit();
//Revision 3 (ele1: putting back the many-to-one component to the list)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
ele1.getComponentList().add( manyToOneComponent1 );
em.getTransaction().commit();
// Revision 4 (ele1: changing the component's entity)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
entity3 = new StrTestNoProxyEntity( "strTestEntity3" );
em.persist( entity3 );
ele1.getComponentList().get( ele1.getComponentList().indexOf( manyToOneComponent2 ) ).setEntity( entity3 );
ele1.getComponentList()
.get( ele1.getComponentList().indexOf( manyToOneComponent2 ) )
.setData( "dataComponent3" );
em.getTransaction().commit();
// Revision 5 (ele1: adding a new many-to-one component)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
entity4 = new StrTestNoProxyEntity( "strTestEntity4" );
em.persist( entity4 );
entity4Copy = new StrTestNoProxyEntity( entity4.getStr(), entity4.getId() );
manyToOneComponent4 = new ManyToOneEagerComponent( entity4, "dataComponent4" );
ele1.getComponentList().add( manyToOneComponent4 );
em.getTransaction().commit();
// Revision 6 (ele1: changing the component's entity properties)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
ele1.getComponentList()
.get( ele1.getComponentList().indexOf( manyToOneComponent4 ) )
.getEntity()
.setStr( "sat4" );
em.getTransaction().commit();
// Revision 7 (ele1: removing component)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
ele1.getComponentList().remove( ele1.getComponentList().indexOf( manyToOneComponent4 ) );
em.getTransaction().commit();
// Revision 8 (ele1: removing all)
em.getTransaction().begin();
ele1 = em.find( EmbeddableListEntity2.class, ele_id1 );
em.remove( ele1 );
em.getTransaction().commit();
} );
}
@Test
public void testRevisionsCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
assertEquals(
Arrays.asList( 1, 2, 3, 4, 5, 7, 8 ),
auditReader.getRevisions( EmbeddableListEntity2.class, ele_id1 )
);
assertEquals(
Arrays.asList( 1 ), auditReader.getRevisions( StrTestNoProxyEntity.class, entity1.getId() )
);
assertEquals(
Arrays.asList( 1 ), auditReader.getRevisions( StrTestNoProxyEntity.class, entity2.getId() )
);
assertEquals(
Arrays.asList( 4 ), auditReader.getRevisions( StrTestNoProxyEntity.class, entity3.getId() )
);
assertEquals(
Arrays.asList( 5, 6 ),
auditReader.getRevisions( StrTestNoProxyEntity.class, entity4.getId() )
);
} );
}
@Test
public void testManyToOneComponentList(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
// Revision 1: many-to-one component1 in the list
EmbeddableListEntity2 rev1 = auditReader.find( EmbeddableListEntity2.class, ele_id1, 1 );
assertNotNull( rev1, "Revision not found" );
assertTrue( rev1.getComponentList().size() > 0, "The component collection was not audited" );
assertEquals(
"dataComponent1", rev1.getComponentList().get( 0 ).getData(),
"The component primitive property was not audited"
);
assertEquals(
entity1, rev1.getComponentList().get( 0 ).getEntity(),
"The component manyToOne reference was not audited"
);
} );
}
@Test
public void testHistoryOfEle1(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final var auditReader = AuditReaderFactory.get( em );
// Revision 1: many-to-one component in the list
assertEquals(
Arrays.asList( new ManyToOneEagerComponent( entity1, "dataComponent1" ) ),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 1 ).getComponentList()
);
// Revision 2: many-to-one component in the list
assertEquals(
Arrays.asList( new ManyToOneEagerComponent( entity2, "dataComponent2" ) ),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 2 ).getComponentList()
);
// Revision 3: two many-to-one components in the list
assertEquals(
Arrays.asList(
new ManyToOneEagerComponent( entity2, "dataComponent2" ),
new ManyToOneEagerComponent( entity1, "dataComponent1" )
),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 3 ).getComponentList()
);
// Revision 4: second component edited and first one in the list
assertEquals(
Arrays.asList(
new ManyToOneEagerComponent( entity3, "dataComponent3" ),
new ManyToOneEagerComponent( entity1, "dataComponent1" )
),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 4 ).getComponentList()
);
// Revision 5: fourth component added in the list
assertEquals(
Arrays.asList(
new ManyToOneEagerComponent( entity3, "dataComponent3" ),
new ManyToOneEagerComponent( entity1, "dataComponent1" ),
new ManyToOneEagerComponent( entity4Copy, "dataComponent4" )
),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 5 ).getComponentList()
);
// Revision 6: changing fourth component property
assertEquals(
Arrays.asList(
new ManyToOneEagerComponent( entity3, "dataComponent3" ),
new ManyToOneEagerComponent( entity1, "dataComponent1" ),
new ManyToOneEagerComponent( entity4, "dataComponent4" )
),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 6 ).getComponentList()
);
// Revision 7: removing component number four
assertEquals(
Arrays.asList(
new ManyToOneEagerComponent( entity3, "dataComponent3" ),
new ManyToOneEagerComponent( entity1, "dataComponent1" )
),
auditReader.find( EmbeddableListEntity2.class, ele_id1, 7 ).getComponentList()
);
assertNull( auditReader.find( EmbeddableListEntity2.class, ele_id1, 8 ) );
} );
}
}
| EmbeddableList2 |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java | {
"start": 3101,
"end": 3418
} | class ____ as follows:
* </p>
*
* <pre>
* ResolverUtil resolver = new ResolverUtil();
* resolver.findInPackage(new CustomTest(), pkg1);
* resolver.find(new CustomTest(), pkg1);
* resolver.find(new CustomTest(), pkg1, pkg2);
* Set<Class<?>> beans = resolver.getClasses();
* </pre>
*
* <p>
* This | is |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_zitao.java | {
"start": 844,
"end": 895
} | class ____ {
public Number value;
}
}
| Model |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java | {
"start": 5901,
"end": 6598
} | class ____ resource resolves
* to a jar location. Still, there is a portability concern on this operation.
*
* <p>If a jar URL is obtained for the last non-wildcard segment, the resolver
* must be able to get a {@code java.net.JarURLConnection} from it, or
* manually parse the jar URL, to be able to walk the contents of the jar
* and resolve the wildcard. This will work in most environments but will
* fail in others, and it is strongly recommended that the wildcard
* resolution of resources coming from jars be thoroughly tested in your
* specific environment before you rely on it.
*
* <h3>{@code classpath*:} Prefix</h3>
*
* <p>There is special support for retrieving multiple | path |
java | google__guava | android/guava/src/com/google/common/collect/ForwardingMultimap.java | {
"start": 1224,
"end": 1525
} | class ____ <i>not</i> forward calls to {@code
* default} methods. Instead, it inherits their default implementations. When those implementations
* invoke methods, they invoke methods on the {@code ForwardingMultimap}.
*
* @author Robert Konigsberg
* @since 2.0
*/
@GwtCompatible
public abstract | does |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/condition/DisabledIfCondition.java | {
"start": 527,
"end": 793
} | class ____ extends MethodBasedCondition<DisabledIf> {
DisabledIfCondition() {
super(DisabledIf.class, DisabledIf::value, DisabledIf::disabledReason);
}
@Override
protected boolean isEnabled(boolean methodResult) {
return !methodResult;
}
}
| DisabledIfCondition |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/Plugins.java | {
"start": 23051,
"end": 24498
} | class ____ not be found
*/
public Converter newInternalConverter(boolean isKey, String className, Map<String, String> converterConfig) {
Class<? extends Converter> klass;
try {
klass = pluginClass(delegatingLoader, className, Converter.class);
} catch (ClassNotFoundException e) {
throw new ConnectException("Failed to load internal converter class " + className);
}
Converter plugin;
try (LoaderSwap loaderSwap = withClassLoader(klass.getClassLoader())) {
plugin = newPlugin(klass);
plugin.configure(converterConfig, isKey);
}
return plugin;
}
/**
* If the given configuration defines a {@link HeaderConverter} using the named configuration property, return a new configured
* instance.
*
* @param config the configuration containing the {@link HeaderConverter}'s configuration; may not be null
* @param classPropertyName the name of the property that contains the name of the {@link HeaderConverter} class; may not be null
* @param classLoaderUsage the name of the property that contains the version of the {@link HeaderConverter} class; may not be null
* @return the instantiated and configured {@link HeaderConverter}; null if the configuration did not define the specified property
* @throws ConnectException if the {@link HeaderConverter} implementation | could |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryRenderer.java | {
"start": 13012,
"end": 13926
} | class ____ extends QueryRenderer {
private final QueryRenderer delegate;
private ExpressionRenderer(QueryRenderer delegate) {
this.delegate = delegate;
}
@Override
String render() {
return delegate.render();
}
@Override
public Stream<QueryToken> stream() {
return delegate.stream();
}
@Override
public List<QueryToken> toList() {
return delegate.toList();
}
@Override
public Iterator<QueryToken> iterator() {
return delegate.iterator();
}
@Override
public @Nullable QueryToken getFirst() {
return delegate.getFirst();
}
@Override
public @Nullable QueryToken getLast() {
return delegate.getLast();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isExpression() {
return true;
}
}
private static | ExpressionRenderer |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java | {
"start": 2996,
"end": 3235
} | class ____
* to keep the user-facing APIs clean and offer methods/constants from here.
*
* <p>It contains methods for instantiating, validating and extracting types during function
* registration in a catalog.
*/
@Internal
public final | is |
java | spring-projects__spring-boot | test-support/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/classpath/resources/OnClassWithResourceTests.java | {
"start": 2119,
"end": 2404
} | class ____");
assertThat(new ClassPathResource("method-resource-1").getContentAsString(StandardCharsets.UTF_8))
.isEqualTo("method-1");
assertThat(new ClassPathResource("method-resource-2").getContentAsString(StandardCharsets.UTF_8))
.isEqualTo("method-2");
}
@Nested
| content |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/testutils/BinaryOperatorTestBase.java | {
"start": 13943,
"end": 14485
} | class ____<OUT> implements Collector<OUT> {
private final List<OUT> output;
private final TypeSerializer<OUT> serializer;
public ListOutputCollector(List<OUT> outputList, TypeSerializer<OUT> serializer) {
this.output = outputList;
this.serializer = serializer;
}
@Override
public void collect(OUT record) {
this.output.add(serializer.copy(record));
}
@Override
public void close() {}
}
public static final | ListOutputCollector |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerCoordinator.java | {
"start": 76937,
"end": 81560
} | class ____ extends CoordinatorResponseHandler<OffsetFetchResponse, Map<TopicPartition, OffsetAndMetadata>> {
private OffsetFetchResponseHandler() {
super(Generation.NO_GENERATION);
}
@Override
public void handle(OffsetFetchResponse response, RequestFuture<Map<TopicPartition, OffsetAndMetadata>> future) {
var group = response.group(rebalanceConfig.groupId);
var groupError = Errors.forCode(group.errorCode());
if (groupError != Errors.NONE) {
log.debug("Offset fetch failed: {}", groupError.message());
if (groupError == Errors.COORDINATOR_NOT_AVAILABLE ||
groupError == Errors.NOT_COORDINATOR) {
// re-discover the coordinator and retry
markCoordinatorUnknown(groupError);
future.raise(groupError);
} else if (groupError == Errors.GROUP_AUTHORIZATION_FAILED) {
future.raise(GroupAuthorizationException.forGroupId(rebalanceConfig.groupId));
} else if (groupError.exception() instanceof RetriableException) {
// retry
future.raise(groupError);
} else {
future.raise(new KafkaException("Unexpected error in fetch offset response: " + groupError.message()));
}
return;
}
var offsets = new HashMap<TopicPartition, OffsetAndMetadata>();
var unstableTxnOffsetTopicPartitions = new HashSet<TopicPartition>();
var unauthorizedTopics = new HashSet<String>();
for (var topic : group.topics()) {
for (var partition : topic.partitions()) {
var tp = new TopicPartition(
topic.name(),
partition.partitionIndex()
);
var error = Errors.forCode(partition.errorCode());
if (error != Errors.NONE) {
log.debug("Failed to fetch offset for partition {}: {}", tp, error.message());
if (error == Errors.UNKNOWN_TOPIC_OR_PARTITION) {
future.raise(new KafkaException("Topic or Partition " + tp + " does not exist"));
return;
} else if (error == Errors.TOPIC_AUTHORIZATION_FAILED) {
unauthorizedTopics.add(tp.topic());
} else if (error == Errors.UNSTABLE_OFFSET_COMMIT) {
unstableTxnOffsetTopicPartitions.add(tp);
} else {
future.raise(new KafkaException("Unexpected error in fetch offset response for partition " +
tp + ": " + error.message()));
return;
}
} else if (partition.committedOffset() >= 0) {
// record the position with the offset (-1 indicates no committed offset to fetch);
// if there's no committed offset, record as null
offsets.put(tp, new OffsetAndMetadata(
partition.committedOffset(),
RequestUtils.getLeaderEpoch(partition.committedLeaderEpoch()),
partition.metadata()
));
} else {
log.info("Found no committed offset for partition {}", tp);
offsets.put(tp, null);
}
}
}
if (!unauthorizedTopics.isEmpty()) {
future.raise(new TopicAuthorizationException(unauthorizedTopics));
} else if (!unstableTxnOffsetTopicPartitions.isEmpty()) {
// just retry
log.info("The following partitions still have unstable offsets " +
"which are not cleared on the broker side: {}" +
", this could be either " +
"transactional offsets waiting for completion, or " +
"normal offsets waiting for replication after appending to local log", unstableTxnOffsetTopicPartitions);
future.raise(new UnstableOffsetCommitException("There are unstable offsets for the requested topic partitions"));
} else {
future.complete(offsets);
}
}
}
private static | OffsetFetchResponseHandler |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/exception/FederationStateStoreRetriableException.java | {
"start": 1042,
"end": 1467
} | class ____ extends YarnException {
private static final long serialVersionUID = 1L;
public FederationStateStoreRetriableException(Throwable cause) {
super(cause);
}
public FederationStateStoreRetriableException(String message) {
super(message);
}
public FederationStateStoreRetriableException(String message,
Throwable cause) {
super(message, cause);
}
}
| FederationStateStoreRetriableException |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/IncludeExclude.java | {
"start": 6425,
"end": 6530
} | class ____ extends Filter {
public abstract boolean accept(long value);
}
public | LongFilter |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java | {
"start": 4338,
"end": 6161
} | class ____ extends ServletServerHttpResponse {
private static final Field COYOTE_RESPONSE_FIELD;
static {
Field field = ReflectionUtils.findField(ResponseFacade.class, "response");
Assert.state(field != null, "Incompatible Tomcat implementation");
ReflectionUtils.makeAccessible(field);
COYOTE_RESPONSE_FIELD = field;
}
TomcatServerHttpResponse(HttpServletResponse response, AsyncContext context,
DataBufferFactory factory, ServletServerHttpRequest request) throws IOException {
super(createTomcatHttpHeaders(response), response, context, factory, request);
}
private static HttpHeaders createTomcatHttpHeaders(HttpServletResponse response) {
ResponseFacade responseFacade = getResponseFacade(response);
org.apache.catalina.connector.Response connectorResponse = (org.apache.catalina.connector.Response)
ReflectionUtils.getField(COYOTE_RESPONSE_FIELD, responseFacade);
Assert.state(connectorResponse != null, "No Tomcat connector response");
Response tomcatResponse = connectorResponse.getCoyoteResponse();
TomcatHeadersAdapter headers = new TomcatHeadersAdapter(tomcatResponse.getMimeHeaders());
return new HttpHeaders(headers);
}
private static ResponseFacade getResponseFacade(HttpServletResponse response) {
if (response instanceof ResponseFacade facade) {
return facade;
}
else if (response instanceof HttpServletResponseWrapper wrapper) {
HttpServletResponse wrappedResponse = (HttpServletResponse) wrapper.getResponse();
return getResponseFacade(wrappedResponse);
}
else {
throw new IllegalArgumentException("Cannot convert [" + response.getClass() +
"] to org.apache.catalina.connector.ResponseFacade");
}
}
@Override
protected void applyHeaders() {
adaptHeaders(true);
}
}
}
| TomcatServerHttpResponse |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/DefaultVertexParallelismStoreTest.java | {
"start": 1128,
"end": 3486
} | class ____ {
@Test
void testNotSet() {
DefaultVertexParallelismStore store = new DefaultVertexParallelismStore();
assertThatThrownBy(() -> store.getParallelismInfo(new JobVertexID()))
.withFailMessage("No parallelism information set for vertex")
.isInstanceOf(IllegalStateException.class);
}
@Test
void testSetInfo() {
JobVertexID id = new JobVertexID();
VertexParallelismInformation info = new MockVertexParallelismInfo();
DefaultVertexParallelismStore store = new DefaultVertexParallelismStore();
store.setParallelismInfo(id, info);
VertexParallelismInformation storedInfo = store.getParallelismInfo(id);
assertThat(storedInfo).isEqualTo(info);
}
@Test
void testGetAllInfos() {
JobVertexID id = new JobVertexID();
JobVertexID id2 = new JobVertexID();
VertexParallelismInformation info = new MockVertexParallelismInfo();
VertexParallelismInformation info2 = new MockVertexParallelismInfo();
DefaultVertexParallelismStore store = new DefaultVertexParallelismStore();
store.setParallelismInfo(id, info);
store.setParallelismInfo(id2, info2);
assertThat(store.getParallelismInfo(id)).isEqualTo(info);
assertThat(store.getParallelismInfo(id2)).isEqualTo(info2);
}
@Test
void testMergeParallelismStore() {
JobVertexID id = new JobVertexID();
JobVertexID id2 = new JobVertexID();
VertexParallelismInformation info = new MockVertexParallelismInfo();
VertexParallelismInformation info2 = new MockVertexParallelismInfo();
DefaultVertexParallelismStore store = new DefaultVertexParallelismStore();
DefaultVertexParallelismStore store2 = new DefaultVertexParallelismStore();
store.setParallelismInfo(id, info);
store2.setParallelismInfo(id2, info2);
assertThat(store.getParallelismInfo(id)).isEqualTo(info);
assertThatThrownBy(() -> store.getParallelismInfo(id2))
.isInstanceOf(IllegalStateException.class);
store.mergeParallelismStore(store2);
assertThat(store.getParallelismInfo(id)).isEqualTo(info);
assertThat(store.getParallelismInfo(id2)).isEqualTo(info2);
}
private static final | DefaultVertexParallelismStoreTest |
java | spring-projects__spring-framework | spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java | {
"start": 24474,
"end": 24686
} | class ____ {
@Pointcut("execution(* getAge())")
void getAge() {
}
@Around("getAge()")
int changeReturnValue(ProceedingJoinPoint pjp) {
return -1;
}
}
@Aspect
static | NamedPointcutAspectWithoutFQN |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriterTests.java | {
"start": 1425,
"end": 2785
} | class ____ {
@Mock
private RequestMatcher matcher;
@Mock
private HeaderWriter delegate;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private DelegatingRequestMatcherHeaderWriter headerWriter;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.headerWriter = new DelegatingRequestMatcherHeaderWriter(this.matcher, this.delegate);
}
@Test
public void constructorNullRequestMatcher() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(null, this.delegate));
}
@Test
public void constructorNullDelegate() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(this.matcher, null));
}
@Test
public void writeHeadersOnMatch() {
given(this.matcher.matches(this.request)).willReturn(true);
this.headerWriter.writeHeaders(this.request, this.response);
verify(this.delegate).writeHeaders(this.request, this.response);
}
@Test
public void writeHeadersOnNoMatch() {
given(this.matcher.matches(this.request)).willReturn(false);
this.headerWriter.writeHeaders(this.request, this.response);
verify(this.delegate, times(0)).writeHeaders(this.request, this.response);
}
}
| DelegatingRequestMatcherHeaderWriterTests |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/JHSDelegationTokenSecretManager.java | {
"start": 1630,
"end": 5331
} | class ____
extends AbstractDelegationTokenSecretManager<MRDelegationTokenIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(
JHSDelegationTokenSecretManager.class);
private HistoryServerStateStoreService store;
/**
* Create a secret manager
* @param delegationKeyUpdateInterval the number of milliseconds for rolling
* new secret keys.
* @param delegationTokenMaxLifetime the maximum lifetime of the delegation
* tokens in milliseconds
* @param delegationTokenRenewInterval how often the tokens must be renewed
* in milliseconds
* @param delegationTokenRemoverScanInterval how often the tokens are scanned
* for expired tokens in milliseconds
* @param store history server state store for persisting state
*/
public JHSDelegationTokenSecretManager(long delegationKeyUpdateInterval,
long delegationTokenMaxLifetime,
long delegationTokenRenewInterval,
long delegationTokenRemoverScanInterval,
HistoryServerStateStoreService store) {
super(delegationKeyUpdateInterval, delegationTokenMaxLifetime,
delegationTokenRenewInterval, delegationTokenRemoverScanInterval);
this.store = store;
}
@Override
public MRDelegationTokenIdentifier createIdentifier() {
return new MRDelegationTokenIdentifier();
}
@Override
protected void storeNewMasterKey(DelegationKey key) throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Storing master key " + key.getKeyId());
}
try {
store.storeTokenMasterKey(key);
} catch (IOException e) {
LOG.error("Unable to store master key " + key.getKeyId(), e);
}
}
@Override
protected void removeStoredMasterKey(DelegationKey key) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing master key " + key.getKeyId());
}
try {
store.removeTokenMasterKey(key);
} catch (IOException e) {
LOG.error("Unable to remove master key " + key.getKeyId(), e);
}
}
@Override
protected void storeNewToken(MRDelegationTokenIdentifier tokenId,
long renewDate) {
if (LOG.isDebugEnabled()) {
LOG.debug("Storing token " + tokenId.getSequenceNumber());
}
try {
store.storeToken(tokenId, renewDate);
} catch (IOException e) {
LOG.error("Unable to store token " + tokenId.getSequenceNumber(), e);
}
}
@Override
protected void removeStoredToken(MRDelegationTokenIdentifier tokenId)
throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Storing token " + tokenId.getSequenceNumber());
}
try {
store.removeToken(tokenId);
} catch (IOException e) {
LOG.error("Unable to remove token " + tokenId.getSequenceNumber(), e);
}
}
@Override
protected void updateStoredToken(MRDelegationTokenIdentifier tokenId,
long renewDate) {
if (LOG.isDebugEnabled()) {
LOG.debug("Updating token " + tokenId.getSequenceNumber());
}
try {
store.updateToken(tokenId, renewDate);
} catch (IOException e) {
LOG.error("Unable to update token " + tokenId.getSequenceNumber(), e);
}
}
public void recover(HistoryServerState state) throws IOException {
LOG.info("Recovering " + getClass().getSimpleName());
for (DelegationKey key : state.tokenMasterKeyState) {
addKey(key);
}
for (Entry<MRDelegationTokenIdentifier, Long> entry :
state.tokenState.entrySet()) {
addPersistedDelegationToken(entry.getKey(), entry.getValue());
}
}
}
| JHSDelegationTokenSecretManager |
java | square__retrofit | samples/src/main/java/com/example/retrofit/InvocationMetrics.java | {
"start": 1070,
"end": 1329
} | interface ____ {
@GET("/robots.txt")
Call<ResponseBody> robots();
@GET("/favicon.ico")
Call<ResponseBody> favicon();
@GET("/")
Call<ResponseBody> home();
@GET
Call<ResponseBody> page(@Url String path);
}
static final | Browse |
java | spring-projects__spring-boot | module/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/logging/OpenTelemetryLoggingAutoConfigurationTests.java | {
"start": 6175,
"end": 6487
} | class ____ {
@Bean
LogRecordProcessor customLogRecordProcessor1() {
return new NoopLogRecordProcessor();
}
@Bean
LogRecordProcessor customLogRecordProcessor2() {
return new NoopLogRecordProcessor();
}
}
@Configuration(proxyBeanMethods = false)
static | MultipleLogRecordProcessorsConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/testdata/input/VoidExpressionPlaceholderTemplateExample.java | {
"start": 752,
"end": 956
} | class ____ {
public static void foo(String s) {
s.length();
}
public void positiveExample(List<String> list) {
list.stream().forEach(x -> foo(x));
}
}
| VoidExpressionPlaceholderTemplateExample |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/layout/JacksonFactory.java | {
"start": 1901,
"end": 3835
} | class ____ extends JacksonFactory {
private final boolean encodeThreadContextAsList;
private final boolean includeStacktrace;
private final boolean stacktraceAsString;
private final boolean objectMessageAsJsonObject;
public JSON(
final boolean encodeThreadContextAsList,
final boolean includeStacktrace,
final boolean stacktraceAsString,
final boolean objectMessageAsJsonObject) {
this.encodeThreadContextAsList = encodeThreadContextAsList;
this.includeStacktrace = includeStacktrace;
this.stacktraceAsString = stacktraceAsString;
this.objectMessageAsJsonObject = objectMessageAsJsonObject;
}
@Override
protected String getPropertNameForContextMap() {
return JsonConstants.ELT_CONTEXT_MAP;
}
@Override
protected String getPropertyNameForTimeMillis() {
return JsonConstants.ELT_TIME_MILLIS;
}
@Override
protected String getPropertyNameForInstant() {
return JsonConstants.ELT_INSTANT;
}
@Override
protected String getPropertNameForSource() {
return JsonConstants.ELT_SOURCE;
}
@Override
protected String getPropertNameForNanoTime() {
return JsonConstants.ELT_NANO_TIME;
}
@Override
protected PrettyPrinter newCompactPrinter() {
return new MinimalPrettyPrinter();
}
@Override
protected ObjectMapper newObjectMapper() {
return new Log4jJsonObjectMapper(
encodeThreadContextAsList, includeStacktrace, stacktraceAsString, objectMessageAsJsonObject);
}
@Override
protected PrettyPrinter newPrettyPrinter() {
return new DefaultPrettyPrinter();
}
}
static | JSON |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/InterceptorInfo.java | {
"start": 10031,
"end": 10493
} | class ____ last.
*
* @return the interceptor methods
*/
public List<MethodInfo> getAroundConstructs() {
return aroundConstructs;
}
/**
* Returns all methods annotated with {@link jakarta.annotation.PostConstruct} found in the hierarchy of the interceptor
* class.
* <p>
* The returned list is sorted. The method declared on the most general superclass is first. The method declared on the
* interceptor | is |
java | apache__kafka | coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/KRaftCoordinatorMetadataImage.java | {
"start": 3610,
"end": 4938
} | class ____ implements TopicMetadata {
private final TopicImage topicImage;
private final ClusterImage clusterImage;
public KraftTopicMetadata(TopicImage topicImage, ClusterImage clusterImage) {
this.topicImage = topicImage;
this.clusterImage = clusterImage;
}
@Override
public String name() {
return topicImage.name();
}
@Override
public Uuid id() {
return topicImage.id();
}
@Override
public int partitionCount() {
return topicImage.partitions().size();
}
@Override
public List<String> partitionRacks(int partition) {
List<String> racks = new ArrayList<>();
PartitionRegistration partitionRegistration = topicImage.partitions().get(partition);
if (partitionRegistration != null) {
for (int replicaId : partitionRegistration.replicas) {
BrokerRegistration broker = clusterImage.broker(replicaId);
if (broker != null) {
broker.rack().ifPresent(racks::add);
}
}
return racks;
} else {
return List.of();
}
}
}
}
| KraftTopicMetadata |
java | quarkusio__quarkus | extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/DateModule.java | {
"start": 1124,
"end": 1189
} | class ____ used to translate between these two formats.
*
* This | is |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/producer/disposer/illegal/DisposerProducesTest.java | {
"start": 580,
"end": 1108
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(ProducerDisposer.class)
.shouldFail()
.build();
@Test
public void trigger() {
Throwable error = container.getFailure();
assertNotNull(error);
assertInstanceOf(DefinitionException.class, error);
assertTrue(error.getMessage().contains("Disposer method must not be annotated @Produces"));
}
@Dependent
static | DisposerProducesTest |
java | quarkusio__quarkus | extensions/scheduler/runtime/src/main/java/io/quarkus/scheduler/runtime/CompositeScheduler.java | {
"start": 654,
"end": 3543
} | class ____ implements Scheduler {
private final List<Scheduler> schedulers;
private final SchedulerContext schedulerContext;
CompositeScheduler(@All @Constituent List<Scheduler> schedulers, SchedulerContext schedulerContext) {
this.schedulers = schedulers;
this.schedulerContext = schedulerContext;
}
@Override
public boolean isStarted() {
// IMPL NOTE: we return true if at least one of the schedulers is started
for (Scheduler scheduler : schedulers) {
if (scheduler.isStarted()) {
return true;
}
}
return false;
}
@Override
public void pause() {
for (Scheduler scheduler : schedulers) {
scheduler.pause();
}
}
@Override
public void pause(String identity) {
for (Scheduler scheduler : schedulers) {
scheduler.pause(identity);
}
}
@Override
public void resume() {
for (Scheduler scheduler : schedulers) {
scheduler.resume();
}
}
@Override
public void resume(String identity) {
for (Scheduler scheduler : schedulers) {
scheduler.resume(identity);
}
}
@Override
public boolean isPaused(String identity) {
for (Scheduler scheduler : schedulers) {
if (scheduler.isPaused(identity)) {
return true;
}
}
return false;
}
@Override
public boolean isRunning() {
// IMPL NOTE: we return true if at least one of the schedulers is running
for (Scheduler scheduler : schedulers) {
if (scheduler.isRunning()) {
return true;
}
}
return false;
}
@Override
public List<Trigger> getScheduledJobs() {
List<Trigger> triggers = new ArrayList<>();
for (Scheduler scheduler : schedulers) {
triggers.addAll(scheduler.getScheduledJobs());
}
return triggers;
}
@Override
public Trigger getScheduledJob(String identity) {
for (Scheduler scheduler : schedulers) {
Trigger trigger = scheduler.getScheduledJob(identity);
if (trigger != null) {
return trigger;
}
}
return null;
}
@Override
public CompositeJobDefinition newJob(String identity) {
return new CompositeJobDefinition(identity);
}
@Override
public Trigger unscheduleJob(String identity) {
for (Scheduler scheduler : schedulers) {
Trigger trigger = scheduler.unscheduleJob(identity);
if (trigger != null) {
return trigger;
}
}
return null;
}
@Override
public String implementation() {
return Scheduled.AUTO;
}
public | CompositeScheduler |
java | apache__camel | components/camel-consul/src/test/java/org/apache/camel/component/consul/cloud/ConsulDefaultServiceCallRouteIT.java | {
"start": 1360,
"end": 4130
} | class ____ extends ConsulTestSupport {
private static final String SERVICE_NAME = "http-service";
private static final int SERVICE_COUNT = 5;
private AgentClient client;
private List<Registration> registrations;
private List<String> expectedBodies;
// *************************************************************************
// Setup / tear down
// *************************************************************************
@Override
protected void doPreSetup() throws Exception {
super.doPreSetup();
client = getConsul().agentClient();
registrations = new ArrayList<>(SERVICE_COUNT);
expectedBodies = new ArrayList<>(SERVICE_COUNT);
for (int i = 0; i < SERVICE_COUNT; i++) {
Registration r = ImmutableRegistration.builder().id("service-" + i).name(SERVICE_NAME).address("127.0.0.1")
.port(AvailablePortFinder.getNextAvailable()).build();
client.register(r);
registrations.add(r);
expectedBodies.add("ping on " + r.getPort().get());
}
}
@Override
public void doPostTearDown() throws Exception {
super.doPostTearDown();
registrations.forEach(r -> client.deregister(r.getId()));
}
// *************************************************************************
// Test
// *************************************************************************
@Test
public void testServiceCall() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(SERVICE_COUNT);
getMockEndpoint("mock:result").expectedBodiesReceivedInAnyOrder(expectedBodies);
registrations.forEach(r -> template.sendBody("direct:start", "ping"));
MockEndpoint.assertIsSatisfied(context);
}
// *************************************************************************
// Route
// *************************************************************************
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").serviceCall().name(SERVICE_NAME).component("http").defaultLoadBalancer()
.consulServiceDiscovery().url(service.getConsulUrl()).endParent()
.to("log:org.apache.camel.component.consul.cloud?level=INFO&showAll=true&multiline=true")
.to("mock:result");
registrations.forEach(r -> fromF("jetty:http://%s:%d", r.getAddress().get(), r.getPort().get()).transform()
.simple("${in.body} on " + r.getPort().get()));
}
};
}
}
| ConsulDefaultServiceCallRouteIT |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/action/privilege/PutPrivilegesRequestBuilderTests.java | {
"start": 908,
"end": 6232
} | class ____ extends ESTestCase {
public void testBuildRequestWithMultipleElements() throws Exception {
final PutPrivilegesRequestBuilder builder = new PutPrivilegesRequestBuilder(null);
builder.source(new BytesArray("""
{
"foo": {
"read": {
"application": "foo",
"name": "read",
"actions": [ "data:/read/*", "admin:/read/*" ]
},
"write": {
"application": "foo",
"name": "write",
"actions": [ "data:/write/*", "admin:*" ]
},
"all": {
"application": "foo",
"name": "all",
"actions": [ "*" ]
}
},
"bar": {
"read": {
"application": "bar",
"name": "read",
"actions": [ "read/*" ]
},
"write": {
"application": "bar",
"name": "write",
"actions": [ "write/*" ]
},
"all": {
"application": "bar",
"name": "all",
"actions": [ "*" ]
}
}
}"""), XContentType.JSON);
final List<ApplicationPrivilegeDescriptor> privileges = builder.request().getPrivileges();
assertThat(privileges, iterableWithSize(6));
assertThat(
privileges,
contains(
descriptor("foo", "read", "data:/read/*", "admin:/read/*"),
descriptor("foo", "write", "data:/write/*", "admin:*"),
descriptor("foo", "all", "*"),
descriptor("bar", "read", "read/*"),
descriptor("bar", "write", "write/*"),
descriptor("bar", "all", "*")
)
);
}
private ApplicationPrivilegeDescriptor descriptor(String app, String name, String... actions) {
return new ApplicationPrivilegeDescriptor(app, name, Sets.newHashSet(actions), Collections.emptyMap());
}
public void testPrivilegeNameValidationOfMultipleElement() throws Exception {
final PutPrivilegesRequestBuilder builder = new PutPrivilegesRequestBuilder(null);
final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> builder.source(new BytesArray("""
{
"foo": {
"write": {
"application": "foo",
"name": "read",
"actions": [ "data:/read/*", "admin:/read/*" ]
},
"all": {
"application": "foo",
"name": "all",
"actions": [ "/*" ]
}
}
}"""), XContentType.JSON));
assertThat(exception.getMessage(), containsString("write"));
assertThat(exception.getMessage(), containsString("read"));
}
public void testApplicationNameValidationOfMultipleElement() throws Exception {
final PutPrivilegesRequestBuilder builder = new PutPrivilegesRequestBuilder(null);
final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> builder.source(new BytesArray("""
{
"bar": {
"read": {
"application": "foo",
"name": "read",
"actions": [ "data:/read/*", "admin:/read/*" ]
},
"write": {
"application": "foo",
"name": "write",
"actions": [ "data:/write/*", "admin:/*" ]
},
"all": {
"application": "foo",
"name": "all",
"actions": [ "/*" ]
}
}
}"""), XContentType.JSON));
assertThat(exception.getMessage(), containsString("bar"));
assertThat(exception.getMessage(), containsString("foo"));
}
public void testInferApplicationNameAndPrivilegeName() throws Exception {
final PutPrivilegesRequestBuilder builder = new PutPrivilegesRequestBuilder(null);
builder.source(new BytesArray("""
{
"foo": {
"read": {
"actions": [ "data:/read/*", "admin:/read/*" ]
},
"write": {
"actions": [ "data:/write/*", "admin:/*" ]
},
"all": {
"actions": [ "*" ]
}
}
}"""), XContentType.JSON);
assertThat(builder.request().getPrivileges(), iterableWithSize(3));
for (ApplicationPrivilegeDescriptor p : builder.request().getPrivileges()) {
assertThat(p.getApplication(), equalTo("foo"));
assertThat(p.getName(), notNullValue());
}
assertThat(builder.request().getPrivileges().get(0).getName(), equalTo("read"));
assertThat(builder.request().getPrivileges().get(1).getName(), equalTo("write"));
assertThat(builder.request().getPrivileges().get(2).getName(), equalTo("all"));
}
}
| PutPrivilegesRequestBuilderTests |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/TestMapFile.java | {
"start": 12812,
"end": 12919
} | class ____ error !!!");
assertNotNull(MapFile.Writer.valueClass(valueClass),
"writer value | null |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/source/DelegatingOptions.java | {
"start": 4280,
"end": 4922
} | class ____ in uses or imports is created by another annotation processor
// then javac will not return correct TypeMirror with TypeKind#ERROR, but rather a string "<error>"
// the gem tools would return a null TypeMirror in that case.
// Therefore throw TypeHierarchyErroneousException so we can postpone the generation of the mapper
throw new TypeHierarchyErroneousException( typeMirror );
}
result.add( (DeclaredType) typeMirror );
}
result.addAll( next );
return result;
}
public abstract boolean hasAnnotation();
}
| used |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/UnwrapException.java | {
"start": 2103,
"end": 2451
} | class ____ the annotation is placed
*/
Class<? extends Exception>[] value() default {};
/**
* The unwrapping strategy to use for this exception.
* <p>
* Defaults to {@link ExceptionUnwrapStrategy#UNWRAP_IF_NO_MATCH}.
*/
ExceptionUnwrapStrategy strategy() default ExceptionUnwrapStrategy.UNWRAP_IF_NO_MATCH;
}
| where |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/lineage/TableLineageUtils.java | {
"start": 1482,
"end": 3592
} | class ____ {
/** Extract optional lineage info from output format, sink, or sink function. */
public static Optional<LineageVertex> extractLineageDataset(@Nullable Object object) {
if (object != null && object instanceof LineageVertexProvider) {
return Optional.of(((LineageVertexProvider) object).getLineageVertex());
}
return Optional.empty();
}
public static LineageDataset createTableLineageDataset(
ContextResolvedTable contextResolvedTable, Optional<LineageVertex> lineageDataset) {
String name = contextResolvedTable.getIdentifier().asSummaryString();
TableLineageDatasetImpl tableLineageDataset =
new TableLineageDatasetImpl(
contextResolvedTable, findLineageDataset(name, lineageDataset));
return tableLineageDataset;
}
public static ModifyType convert(ChangelogMode inputChangelogMode) {
if (inputChangelogMode.containsOnly(RowKind.INSERT)) {
return ModifyType.INSERT;
} else if (inputChangelogMode.containsOnly(RowKind.DELETE)) {
return ModifyType.DELETE;
} else {
return ModifyType.UPDATE;
}
}
private static Optional<LineageDataset> findLineageDataset(
String name, Optional<LineageVertex> lineageVertexOpt) {
if (lineageVertexOpt.isPresent()) {
LineageVertex lineageVertex = lineageVertexOpt.get();
if (lineageVertex.datasets().size() == 1) {
return Optional.of(lineageVertex.datasets().get(0));
}
for (LineageDataset dataset : lineageVertex.datasets()) {
if (dataset.name().equals(name)) {
return Optional.of(dataset);
}
}
}
return Optional.empty();
}
private static Map<String, String> extractOptions(CatalogBaseTable catalogBaseTable) {
try {
return catalogBaseTable.getOptions();
} catch (Exception e) {
return new HashMap<>();
}
}
}
| TableLineageUtils |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FiltersAggregator.java | {
"start": 19689,
"end": 20343
} | class ____ implements LeafCollector {
final DocCountProvider docCount;
private long count;
Counter(DocCountProvider docCount) {
this.docCount = docCount;
}
public long readAndReset(LeafReaderContext ctx) throws IOException {
long result = count;
count = 0;
docCount.setLeafReaderContext(ctx);
return result;
}
@Override
public void collect(int doc) throws IOException {
count += docCount.getDocCount(doc);
}
@Override
public void setScorer(Scorable scorer) throws IOException {}
}
}
| Counter |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/accesstype/Country.java | {
"start": 239,
"end": 548
} | class ____ {
String name;
String iso2Code;
String nonPersistent;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIso2Code() {
return iso2Code;
}
public void setIso2Code(String iso2Code) {
this.iso2Code = iso2Code;
}
}
| Country |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/lucene/search/XMoreLikeThis.java | {
"start": 6469,
"end": 23208
} | class ____ we upgrade to Lucene 5.0";
// }
/**
* Default maximum number of tokens to parse in each example doc field that is not stored with TermVector support.
*/
public static final int DEFAULT_MAX_NUM_TOKENS_PARSED = 5000;
/**
* Ignore terms with less than this frequency in the source doc.
*
* @see #setMinTermFreq
*/
public static final int DEFAULT_MIN_TERM_FREQ = 2;
/**
* Ignore words which do not occur in at least this many docs.
*
* @see #setMinDocFreq
*/
public static final int DEFAULT_MIN_DOC_FREQ = 5;
/**
* Ignore words which occur in more than this many docs.
*
* @see #setMaxDocFreq
*/
public static final int DEFAULT_MAX_DOC_FREQ = Integer.MAX_VALUE;
/**
* Boost terms in query based on score.
*
* @see #setBoost
*/
public static final boolean DEFAULT_BOOST = false;
/**
* Default field names. Null is used to specify that the field names should be looked
* up at runtime from the provided reader.
*/
public static final String[] DEFAULT_FIELD_NAMES = new String[] { "contents" };
/**
* Ignore words less than this length or if 0 then this has no effect.
*
* @see #setMinWordLen
*/
public static final int DEFAULT_MIN_WORD_LENGTH = 0;
/**
* Ignore words greater than this length or if 0 then this has no effect.
*
* @see #setMaxWordLen
*/
public static final int DEFAULT_MAX_WORD_LENGTH = 0;
/**
* Default set of stopwords.
* If null means to allow stop words.
*
* @see #setStopWords
*/
public static final Set<?> DEFAULT_STOP_WORDS = null;
/**
* Current set of stop words.
*/
private Set<?> stopWords = DEFAULT_STOP_WORDS;
/**
* Return a Query with no more than this many terms.
*
* @see IndexSearcher#getMaxClauseCount
* @see #setMaxQueryTerms
*/
public static final int DEFAULT_MAX_QUERY_TERMS = 25;
/**
* Analyzer that will be used to parse the doc.
*/
private Analyzer analyzer = null;
/**
* Ignore words less frequent that this.
*/
private int minTermFreq = DEFAULT_MIN_TERM_FREQ;
/**
* Ignore words which do not occur in at least this many docs.
*/
private int minDocFreq = DEFAULT_MIN_DOC_FREQ;
/**
* Ignore words which occur in more than this many docs.
*/
private int maxDocFreq = DEFAULT_MAX_DOC_FREQ;
/**
* Should we apply a boost to the Query based on the scores?
*/
private boolean boost = DEFAULT_BOOST;
/**
* Current set of skip terms.
*/
private Set<Term> skipTerms = null;
/**
* Field name we'll analyze.
*/
private String[] fieldNames = DEFAULT_FIELD_NAMES;
/**
* Ignore words if less than this len.
*/
private int minWordLen = DEFAULT_MIN_WORD_LENGTH;
/**
* Ignore words if greater than this len.
*/
private int maxWordLen = DEFAULT_MAX_WORD_LENGTH;
/**
* Don't return a query longer than this.
*/
private int maxQueryTerms = DEFAULT_MAX_QUERY_TERMS;
/**
* For idf() calculations.
*/
private final TFIDFSimilarity similarity;// = new ClassicSimilarity();
/**
* IndexReader to use
*/
private final IndexReader ir;
/**
* Boost factor to use when boosting the terms
*/
private float boostFactor = 1;
/**
* Sets the boost factor to use when boosting terms
*/
public void setBoostFactor(float boostFactor) {
this.boostFactor = boostFactor;
}
/**
* Sets a list of terms to never select from
*/
public void setSkipTerms(Set<Term> skipTerms) {
this.skipTerms = skipTerms;
}
public XMoreLikeThis(IndexReader ir, TFIDFSimilarity sim) {
this.ir = ir;
this.similarity = sim;
}
/**
* Sets the analyzer to use. All 'like' methods require an analyzer.
*
* @param analyzer the analyzer to use to tokenize text.
*/
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
}
/**
* Sets the frequency below which terms will be ignored in the source doc.
*
* @param minTermFreq the frequency below which terms will be ignored in the source doc.
*/
public void setMinTermFreq(int minTermFreq) {
this.minTermFreq = minTermFreq;
}
/**
* Sets the frequency at which words will be ignored which do not occur in at least this
* many docs.
*
* @param minDocFreq the frequency at which words will be ignored which do not occur in at
* least this many docs.
*/
public void setMinDocFreq(int minDocFreq) {
this.minDocFreq = minDocFreq;
}
/**
* Set the maximum frequency in which words may still appear. Words that appear
* in more than this many docs will be ignored.
*
* @param maxFreq the maximum count of documents that a term may appear
* in to be still considered relevant
*/
public void setMaxDocFreq(int maxFreq) {
this.maxDocFreq = maxFreq;
}
/**
* Sets whether to boost terms in query based on "score" or not.
*
* @param boost true to boost terms in query based on "score", false otherwise.
*/
public void setBoost(boolean boost) {
this.boost = boost;
}
/**
* Sets the field names that will be used when generating the 'More Like This' query.
* Set this to null for the field names to be determined at runtime from the IndexReader
* provided in the constructor.
*
* @param fieldNames the field names that will be used when generating the 'More Like This'
* query.
*/
public void setFieldNames(String[] fieldNames) {
this.fieldNames = fieldNames;
}
/**
* Sets the minimum word length below which words will be ignored.
*
* @param minWordLen the minimum word length below which words will be ignored.
*/
public void setMinWordLen(int minWordLen) {
this.minWordLen = minWordLen;
}
/**
* Sets the maximum word length above which words will be ignored.
*
* @param maxWordLen the maximum word length above which words will be ignored.
*/
public void setMaxWordLen(int maxWordLen) {
this.maxWordLen = maxWordLen;
}
/**
* Set the set of stopwords.
* Any word in this set is considered "uninteresting" and ignored.
* Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as
* for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".
*
* @param stopWords set of stopwords, if null it means to allow stop words
*/
public void setStopWords(Set<?> stopWords) {
this.stopWords = stopWords;
}
/**
* Sets the maximum number of query terms that will be included in any generated query.
*
* @param maxQueryTerms the maximum number of query terms that will be included in any
* generated query.
*/
public void setMaxQueryTerms(int maxQueryTerms) {
this.maxQueryTerms = maxQueryTerms;
}
/**
* Return a query that will return docs like the passed Readers.
* This was added in order to treat multi-value fields.
*
* @return a query that will return docs like the passed Readers.
*/
public Query like(String fieldName, Reader... readers) throws IOException {
Map<String, Int> words = new HashMap<>();
for (Reader r : readers) {
addTermFrequencies(r, words, fieldName);
}
return createQuery(createQueue(words));
}
/**
* Return a query that will return docs like the passed Fields.
*
* @return a query that will return docs like the passed Fields.
*/
public Query like(Fields... likeFields) throws IOException {
// get all field names
Set<String> fieldNames = new HashSet<>();
for (Fields fields : likeFields) {
for (String fieldName : fields) {
fieldNames.add(fieldName);
}
}
// term selection is per field, then appended to a single boolean query
BooleanQuery.Builder bq = new BooleanQuery.Builder();
for (String fieldName : fieldNames) {
Map<String, Int> termFreqMap = new HashMap<>();
for (Fields fields : likeFields) {
Terms vector = fields.terms(fieldName);
if (vector != null) {
addTermFrequencies(termFreqMap, vector, fieldName);
}
}
addToQuery(createQueue(termFreqMap, fieldName), bq);
}
return bq.build();
}
/**
* Create the More like query from a PriorityQueue
*/
private Query createQuery(PriorityQueue<ScoreTerm> q) {
BooleanQuery.Builder query = new BooleanQuery.Builder();
addToQuery(q, query);
return query.build();
}
/**
* Add to an existing boolean query the More Like This query from this PriorityQueue
*/
private void addToQuery(PriorityQueue<ScoreTerm> q, BooleanQuery.Builder query) {
ScoreTerm scoreTerm;
float bestScore = -1;
while ((scoreTerm = q.pop()) != null) {
Query tq = new TermQuery(new Term(scoreTerm.topField, scoreTerm.word));
if (boost) {
if (bestScore == -1) {
bestScore = (scoreTerm.score);
}
float myScore = (scoreTerm.score);
tq = new BoostQuery(tq, boostFactor * myScore / bestScore);
}
try {
query.add(tq, BooleanClause.Occur.SHOULD);
} catch (IndexSearcher.TooManyClauses ignore) {
break;
}
}
}
/**
* Create a PriorityQueue from a word->tf map.
*
* @param words a map of words keyed on the word(String) with Int objects as the values.
*/
private PriorityQueue<ScoreTerm> createQueue(Map<String, Int> words) throws IOException {
return createQueue(words, this.fieldNames);
}
/**
* Create a PriorityQueue from a word->tf map.
*
* @param words a map of words keyed on the word(String) with Int objects as the values.
* @param fieldNames an array of field names to override defaults.
*/
private PriorityQueue<ScoreTerm> createQueue(Map<String, Int> words, String... fieldNames) throws IOException {
// have collected all words in doc and their freqs
int numDocs = ir.numDocs();
final int limit = Math.min(maxQueryTerms, words.size());
FreqQ queue = new FreqQ(limit); // will order words by score
for (String word : words.keySet()) { // for every word
int tf = words.get(word).x; // term freq in the source doc
if (minTermFreq > 0 && tf < minTermFreq) {
continue; // filter out words that don't occur enough times in the source
}
// go through all the fields and find the largest document frequency
String topField = fieldNames[0];
int docFreq = 0;
for (String fieldName : fieldNames) {
int freq = ir.docFreq(new Term(fieldName, word));
topField = (freq > docFreq) ? fieldName : topField;
docFreq = Math.max(freq, docFreq);
}
if (minDocFreq > 0 && docFreq < minDocFreq) {
continue; // filter out words that don't occur in enough docs
}
if (docFreq > maxDocFreq) {
continue; // filter out words that occur in too many docs
}
if (docFreq == 0) {
continue; // index update problem?
}
float idf = similarity.idf(docFreq, numDocs);
float score = tf * idf;
if (queue.size() < limit) {
// there is still space in the queue
queue.add(new ScoreTerm(word, topField, score));
} else {
ScoreTerm term = queue.top();
if (term.score < score) { // update the smallest in the queue in place and update the queue.
term.update(word, topField, score);
queue.updateTop();
}
}
}
return queue;
}
/**
* Adds terms and frequencies found in vector into the Map termFreqMap
*
* @param termFreqMap a Map of terms and their frequencies
* @param vector List of terms and their frequencies for a doc/field
* @param fieldName Optional field name of the terms for skip terms
*/
private void addTermFrequencies(Map<String, Int> termFreqMap, Terms vector, @Nullable String fieldName) throws IOException {
final TermsEnum termsEnum = vector.iterator();
final CharsRefBuilder spare = new CharsRefBuilder();
BytesRef text;
while ((text = termsEnum.next()) != null) {
spare.copyUTF8Bytes(text);
final String term = spare.toString();
if (isNoiseWord(term)) {
continue;
}
if (isSkipTerm(fieldName, term)) {
continue;
}
final PostingsEnum docs = termsEnum.postings(null);
int freq = 0;
while (docs != null && docs.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
freq += docs.freq();
}
// increment frequency
Int cnt = termFreqMap.get(term);
if (cnt == null) {
cnt = new Int();
termFreqMap.put(term, cnt);
cnt.x = freq;
} else {
cnt.x += freq;
}
}
}
/**
* Adds term frequencies found by tokenizing text from reader into the Map words
*
* @param r a source of text to be tokenized
* @param termFreqMap a Map of terms and their frequencies
* @param fieldName Used by analyzer for any special per-field analysis
*/
private void addTermFrequencies(Reader r, Map<String, Int> termFreqMap, String fieldName) throws IOException {
if (analyzer == null) {
throw new UnsupportedOperationException("To use MoreLikeThis without " + "term vectors, you must provide an Analyzer");
}
try (TokenStream ts = analyzer.tokenStream(fieldName, r)) {
int tokenCount = 0;
// for every token
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
TermFrequencyAttribute tfAtt = ts.addAttribute(TermFrequencyAttribute.class);
ts.reset();
while (ts.incrementToken()) {
String word = termAtt.toString();
tokenCount++;
/**
* The maximum number of tokens to parse in each example doc field that is not stored with TermVector support
*/
if (tokenCount > DEFAULT_MAX_NUM_TOKENS_PARSED) {
break;
}
if (isNoiseWord(word)) {
continue;
}
if (isSkipTerm(fieldName, word)) {
continue;
}
// increment frequency
Int cnt = termFreqMap.get(word);
if (cnt == null) {
termFreqMap.put(word, new Int(tfAtt.getTermFrequency()));
} else {
cnt.x += tfAtt.getTermFrequency();
}
}
ts.end();
}
}
/**
* determines if the passed term is likely to be of interest in "more like" comparisons
*
* @param term The word being considered
* @return true if should be ignored, false if should be used in further analysis
*/
private boolean isNoiseWord(String term) {
int len = term.length();
if (minWordLen > 0 && len < minWordLen) {
return true;
}
if (maxWordLen > 0 && len > maxWordLen) {
return true;
}
return stopWords != null && stopWords.contains(term);
}
/**
* determines if the passed term is to be skipped all together
*/
private boolean isSkipTerm(@Nullable String field, String value) {
return field != null && skipTerms != null && skipTerms.contains(new Term(field, value));
}
/**
* PriorityQueue that orders words by score.
*/
private static | once |
java | apache__kafka | storage/src/main/java/org/apache/kafka/server/log/remote/storage/RemoteLogManager.java | {
"start": 6777,
"end": 7200
} | class ____ responsible for
* - initializing `RemoteStorageManager` and `RemoteLogMetadataManager` instances
* - receives any leader and follower replica events and partition stop events and act on them
* - also provides APIs to fetch indexes, metadata about remote log segments
* - copying log segments to the remote storage
* - cleaning up segments that are expired based on retention size or retention time
*/
public | is |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/jmx/export/metadata/InvalidMetadataException.java | {
"start": 1037,
"end": 1290
} | class ____ extends JmxException {
/**
* Create a new {@code InvalidMetadataException} with the supplied
* error message.
* @param msg the detail message
*/
public InvalidMetadataException(String msg) {
super(msg);
}
}
| InvalidMetadataException |
java | spring-projects__spring-security | oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapterTests.java | {
"start": 1400,
"end": 2313
} | class ____ {
@Test
public void convertWithGrantedAuthoritiesConverter() {
Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build();
Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Arrays
.asList(new SimpleGrantedAuthority("blah"));
Collection<GrantedAuthority> authorities = new ReactiveJwtGrantedAuthoritiesConverterAdapter(
grantedAuthoritiesConverter)
.convert(jwt)
.toStream()
.collect(Collectors.toList());
assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah"));
}
@Test
public void whenConstructingWithInvalidConverter() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new ReactiveJwtGrantedAuthoritiesConverterAdapter(null))
.withMessage("grantedAuthoritiesConverter cannot be null");
// @formatter:on
}
}
| ReactiveJwtGrantedAuthoritiesConverterAdapterTests |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OidcTests.java | {
"start": 32397,
"end": 33629
} | class ____ extends AuthorizationServerConfiguration {
// @formatter:off
@Bean
SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.tokenGenerator(tokenGenerator())
.oidc(Customizer.withDefaults())
)
.authorizeHttpRequests((authorize) ->
authorize.anyRequest().authenticated()
);
return http.build();
}
// @formatter:on
@Bean
OAuth2TokenGenerator<?> tokenGenerator() {
JwtGenerator jwtGenerator = new JwtGenerator(new NimbusJwtEncoder(jwkSource()));
jwtGenerator.setJwtCustomizer(jwtCustomizer());
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
OAuth2TokenGenerator<OAuth2Token> delegatingTokenGenerator = new DelegatingOAuth2TokenGenerator(
jwtGenerator, refreshTokenGenerator);
return spy(new OAuth2TokenGenerator<OAuth2Token>() {
@Override
public OAuth2Token generate(OAuth2TokenContext context) {
return delegatingTokenGenerator.generate(context);
}
});
}
}
@EnableWebSecurity
@Configuration
static | AuthorizationServerConfigurationWithTokenGenerator |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/utils/FloatConversionUtilsTests.java | {
"start": 349,
"end": 719
} | class ____ extends ESTestCase {
public void testFloatArrayOf() {
double[] doublesArray = { 1.0, 2.0, 3.0 };
float[] floatArray = FloatConversionUtils.floatArrayOf(doublesArray);
assertEquals(1.0, floatArray[0], 0.0);
assertEquals(2.0, floatArray[1], 0.0);
assertEquals(3.0, floatArray[2], 0.0);
}
}
| FloatConversionUtilsTests |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/context/AsyncContinuationTest.java | {
"start": 2808,
"end": 2991
} | class ____ {
@AroundInvoke
Object around(InvocationContext ctx) throws Exception {
return "C1:" + ctx.proceed() + ":C2";
}
}
}
| CharlieInterceptor |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java | {
"start": 3026,
"end": 7378
} | class ____, transaction context)
* unless the TaskExecutor explicitly supports this.
* <p>{@link ApplicationListener} instances which declare no support for asynchronous
* execution ({@link ApplicationListener#supportsAsyncExecution()} always run within
* the original thread which published the event, for example, the transaction-synchronized
* {@link org.springframework.transaction.event.TransactionalApplicationListener}.
* @since 2.0
* @see org.springframework.core.task.SyncTaskExecutor
* @see org.springframework.core.task.SimpleAsyncTaskExecutor
*/
public void setTaskExecutor(@Nullable Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Return the current task executor for this multicaster.
* @since 2.0
*/
protected @Nullable Executor getTaskExecutor() {
return this.taskExecutor;
}
/**
* Set the {@link ErrorHandler} to invoke in case an exception is thrown
* from a listener.
* <p>Default is none, with a listener exception stopping the current
* multicast and getting propagated to the publisher of the current event.
* If a {@linkplain #setTaskExecutor task executor} is specified, each
* individual listener exception will get propagated to the executor but
* won't necessarily stop execution of other listeners.
* <p>Consider setting an {@link ErrorHandler} implementation that catches
* and logs exceptions (a la
* {@link org.springframework.scheduling.support.TaskUtils#LOG_AND_SUPPRESS_ERROR_HANDLER})
* or an implementation that logs exceptions while nevertheless propagating them
* (for example, {@link org.springframework.scheduling.support.TaskUtils#LOG_AND_PROPAGATE_ERROR_HANDLER}).
* @since 4.1
*/
public void setErrorHandler(@Nullable ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Return the current error handler for this multicaster.
* @since 4.1
*/
protected @Nullable ErrorHandler getErrorHandler() {
return this.errorHandler;
}
@Override
public void multicastEvent(ApplicationEvent event) {
multicastEvent(event, null);
}
@Override
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : ResolvableType.forInstance(event));
Executor executor = getTaskExecutor();
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null && listener.supportsAsyncExecution()) {
try {
executor.execute(() -> invokeListener(listener, event));
}
catch (RejectedExecutionException ex) {
// Probably on shutdown -> invoke listener locally instead
invokeListener(listener, event);
}
}
else {
invokeListener(listener, event);
}
}
}
/**
* Invoke the given listener with the given event.
* @param listener the ApplicationListener to invoke
* @param event the current event to propagate
* @since 4.1
*/
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
doInvokeListener(listener, event);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass()) ||
(event instanceof PayloadApplicationEvent payloadEvent &&
matchesClassCastMessage(msg, payloadEvent.getPayload().getClass()))) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception.
Log loggerToUse = this.lazyLogger;
if (loggerToUse == null) {
loggerToUse = LogFactory.getLog(getClass());
this.lazyLogger = loggerToUse;
}
if (loggerToUse.isTraceEnabled()) {
loggerToUse.trace("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
private boolean matchesClassCastMessage(String classCastMessage, Class<?> eventClass) {
// On Java 8, the message starts with the | loader |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/joined/notownedrelation/Address.java | {
"start": 378,
"end": 1648
} | class ____ implements Serializable {
@Id
private Long id;
private String address1;
@ManyToOne
private Contact contact;
public Address() {
}
public Address(Long id, String address1) {
this.id = id;
this.address1 = address1;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof Address) ) {
return false;
}
Address address = (Address) o;
if ( address1 != null ? !address1.equals( address.address1 ) : address.address1 != null ) {
return false;
}
if ( id != null ? !id.equals( address.id ) : address.id != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + (address1 != null ? address1.hashCode() : 0);
return result;
}
public String toString() {
return "Address(id = " + getId() + ", address1 = " + getAddress1() + ")";
}
}
| Address |
java | apache__kafka | streams/src/test/java/org/apache/kafka/test/MockReducer.java | {
"start": 1142,
"end": 1360
} | class ____ implements Reducer<String> {
@Override
public String apply(final String value1, final String value2) {
return value1 + "-" + value2;
}
}
private static | StringRemove |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/customproviders/AbortingFiltersTest.java | {
"start": 482,
"end": 1667
} | class ____ {
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(CustomContainerRequestFilter.class, CustomFiltersResource.class, ResponseFilter.class,
OptionalRequestFilter.class, IllegalStateExceptionMapper.class);
}
});
@Test
public void testFilters() {
RestAssured.given().header("some-input", "bar").get("/custom/req")
.then().statusCode(200).body(containsString("/custom/req-bar")).extract().headers();
}
@Test
public void testOptionalFilter() {
RestAssured.given().header("optional-input", "abort").get("/custom/req")
.then().statusCode(204);
}
@Test
public void testResponseFilter() {
RestAssured.given().header("response-input", "abort").get("/custom/req")
.then().statusCode(202).body(containsString("abort"));
}
}
| AbortingFiltersTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.