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 | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/CorsRegistryTests.java | {
"start": 1041,
"end": 3743
} | class ____ {
private CorsRegistry registry;
@BeforeEach
void setUp() {
this.registry = new CorsRegistry();
}
@Test
void noMapping() {
assertThat(this.registry.getCorsConfigurations()).isEmpty();
}
@Test
void multipleMappings() {
this.registry.addMapping("/foo");
this.registry.addMapping("/bar");
assertThat(this.registry.getCorsConfigurations()).hasSize(2);
}
@Test
void customizedMapping() {
this.registry.addMapping("/foo").allowedOrigins("https://domain2.com", "https://domain2.com")
.allowedMethods("DELETE").allowCredentials(true).allowPrivateNetwork(true)
.allowedHeaders("header1", "header2").exposedHeaders("header3", "header4").maxAge(3600);
Map<String, CorsConfiguration> configs = this.registry.getCorsConfigurations();
assertThat(configs).hasSize(1);
CorsConfiguration config = configs.get("/foo");
assertThat(config.getAllowedOrigins()).isEqualTo(Arrays.asList("https://domain2.com", "https://domain2.com"));
assertThat(config.getAllowedMethods()).isEqualTo(Collections.singletonList("DELETE"));
assertThat(config.getAllowedHeaders()).isEqualTo(Arrays.asList("header1", "header2"));
assertThat(config.getExposedHeaders()).isEqualTo(Arrays.asList("header3", "header4"));
assertThat(config.getAllowCredentials()).isTrue();
assertThat(config.getAllowPrivateNetwork()).isTrue();
assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(3600));
}
@Test
void allowCredentials() {
this.registry.addMapping("/foo").allowCredentials(true);
CorsConfiguration config = this.registry.getCorsConfigurations().get("/foo");
assertThat(config.getAllowedOrigins())
.as("Globally origins=\"*\" and allowCredentials=true should be possible")
.containsExactly("*");
}
@Test
void combine() {
CorsConfiguration otherConfig = new CorsConfiguration();
otherConfig.addAllowedOrigin("http://localhost:3000");
otherConfig.addAllowedMethod("*");
otherConfig.applyPermitDefaultValues();
this.registry.addMapping("/api/**").combine(otherConfig);
Map<String, CorsConfiguration> configs = this.registry.getCorsConfigurations();
assertThat(configs).hasSize(1);
CorsConfiguration config = configs.get("/api/**");
assertThat(config.getAllowedOrigins()).isEqualTo(Collections.singletonList("http://localhost:3000"));
assertThat(config.getAllowedMethods()).isEqualTo(Collections.singletonList("*"));
assertThat(config.getAllowedHeaders()).isEqualTo(Collections.singletonList("*"));
assertThat(config.getExposedHeaders()).isEmpty();
assertThat(config.getAllowCredentials()).isNull();
assertThat(config.getAllowPrivateNetwork()).isNull();
assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(1800));
}
}
| CorsRegistryTests |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java | {
"start": 1038,
"end": 2627
} | class ____ extends AbstractJmxAssemblerTests {
protected static final String OBJECT_NAME = "bean:name=testBean4";
@Test
void testGetAgeIsReadOnly() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE);
assertThat(attr.isReadable()).as("Age is not readable").isTrue();
assertThat(attr.isWritable()).as("Age is not writable").isTrue();
}
@Test
void testNickNameIsExposed() throws Exception {
ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo();
MBeanAttributeInfo attr = inf.getAttribute("NickName");
assertThat(attr).as("Nick Name should not be null").isNotNull();
assertThat(attr.isWritable()).as("Nick Name should be writable").isTrue();
assertThat(attr.isReadable()).as("Nick Name should be readable").isTrue();
}
@Override
protected String getObjectName() {
return OBJECT_NAME;
}
@Override
protected int getExpectedOperationCount() {
return 11;
}
@Override
protected int getExpectedAttributeCount() {
return 4;
}
@Override
protected String getApplicationContextPath() {
return "org/springframework/jmx/export/assembler/methodExclusionAssemblerNotMapped.xml";
}
@Override
protected MBeanInfoAssembler getAssembler() {
MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler();
Properties props = new Properties();
props.setProperty("bean:name=testBean5", "setAge,isSuperman,setSuperman,dontExposeMe");
assembler.setIgnoredMethodMappings(props);
return assembler;
}
}
| MethodExclusionMBeanInfoAssemblerNotMappedTests |
java | apache__camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/cluster/ZooKeeperClusterView.java | {
"start": 6008,
"end": 6429
} | class ____ implements CamelClusterMember {
@Override
public boolean isLeader() {
return leaderSelector != null && leaderSelector.hasLeadership();
}
@Override
public boolean isLocal() {
return true;
}
@Override
public String getId() {
return getClusterService().getId();
}
}
private final | CuratorLocalMember |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/rest/ParamDefinition.java | {
"start": 7958,
"end": 9812
} | enum ____
*/
public ParamDefinition allowableValues(String allowableValues) {
List<ValueDefinition> list = new ArrayList<>();
for (String av : allowableValues.split(",")) {
list.add(new ValueDefinition(av));
}
setAllowableValues(list);
return this;
}
/**
* The parameter type such as body, form, header, path, query
*/
public ParamDefinition type(RestParamType type) {
setType(type);
return this;
}
/**
* Adds a body example with the given content-type
*/
public ParamDefinition example(String contentType, String example) {
if (examples == null) {
examples = new ArrayList<>();
}
examples.add(new RestPropertyDefinition(contentType, example));
return this;
}
/**
* Adds a single example
*/
public ParamDefinition example(String example) {
if (examples == null) {
examples = new ArrayList<>();
}
examples.add(new RestPropertyDefinition("", example));
return this;
}
/**
* Ends the configuration of this parameter
*/
public RestDefinition endParam() {
// name is mandatory
StringHelper.notEmpty(name, "name");
verb.getParams().add(this);
return verb.getRest();
}
public List<String> getAllowableValuesAsStringList() {
if (allowableValues == null) {
return Collections.emptyList();
} else {
List<String> answer = new ArrayList<>();
for (ValueDefinition v : allowableValues) {
answer.add(v.getValue());
}
return answer;
}
}
public String getAllowableValuesAsCommaString() {
return String.join(",", getAllowableValuesAsStringList());
}
}
| type |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/ModelSemantics.java | {
"start": 1053,
"end": 1232
} | class ____ only available for model arguments (i.e. arguments of a {@link
* ProcessTableFunction} that are annotated with {@code @ArgumentHint(MODEL)}).
*/
@PublicEvolving
public | is |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/activities/ActivityNode.java | {
"start": 1264,
"end": 4041
} | class ____ {
private String activityNodeName;
private String parentName;
private Integer appPriority;
private Integer requestPriority;
private ActivityState state;
private String diagnostic;
private NodeId nodeId;
private Long allocationRequestId;
private List<ActivityNode> childNode;
public ActivityNode(String activityNodeName, String parentName,
Integer priority, ActivityState state, String diagnostic,
ActivityLevel level, NodeId nodeId, Long allocationRequestId) {
this.activityNodeName = activityNodeName;
this.parentName = parentName;
if (level != null) {
switch (level) {
case APP:
this.appPriority = priority;
break;
case REQUEST:
this.requestPriority = priority;
this.allocationRequestId = allocationRequestId;
break;
case NODE:
this.requestPriority = priority;
this.allocationRequestId = allocationRequestId;
this.nodeId = nodeId;
break;
default:
break;
}
}
this.state = state;
this.diagnostic = diagnostic;
this.childNode = new LinkedList<>();
}
public String getName() {
return this.activityNodeName;
}
public String getParentName() {
return this.parentName;
}
public void addChild(ActivityNode node) {
childNode.add(0, node);
}
public List<ActivityNode> getChildren() {
return this.childNode;
}
public ActivityState getState() {
return this.state;
}
public String getDiagnostic() {
return this.diagnostic;
}
public Integer getAppPriority() {
return appPriority;
}
public Integer getRequestPriority() {
return requestPriority;
}
public NodeId getNodeId() {
return nodeId;
}
public Long getAllocationRequestId() {
return allocationRequestId;
}
public boolean isAppType() {
if (appPriority != null) {
return true;
} else {
return false;
}
}
public boolean isRequestType() {
return requestPriority != null && nodeId == null;
}
public String getShortDiagnostic() {
if (this.diagnostic == null) {
return "";
} else {
return StringUtils.split(this.diagnostic,
ActivitiesManager.DIAGNOSTICS_DETAILS_SEPARATOR)[0];
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.activityNodeName + " ")
.append(this.appPriority + " ")
.append(this.state + " ");
if (this.nodeId != null) {
sb.append(this.nodeId + " ");
}
if (!this.diagnostic.equals("")) {
sb.append(this.diagnostic + "\n");
}
sb.append("\n");
for (ActivityNode child : childNode) {
sb.append(child.toString() + "\n");
}
return sb.toString();
}
}
| ActivityNode |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/ioc/beans/User.java | {
"start": 170,
"end": 334
} | class ____ {
public final String name; // <1>
public int age = 18; // <2>
public User(String name) {
this.name = name;
}
}
// end::class[]
| User |
java | junit-team__junit5 | documentation/src/test/java/example/defaultmethods/Testable.java | {
"start": 376,
"end": 443
} | interface ____<T> {
T createValue();
}
// end::user_guide[]
| Testable |
java | quarkusio__quarkus | core/devmode-spi/src/main/java/io/quarkus/dev/testing/ContinuousTestingSharedStateManager.java | {
"start": 2252,
"end": 4392
} | class ____ {
public final long lastRun;
public final boolean running;
public final boolean inProgress;
public final long run;
public final long passed;
public final long failed;
public final long skipped;
public final long currentPassed;
public final long currentFailed;
public final long currentSkipped;
public final boolean isBrokenOnly;
public final boolean isTestOutput;
public final boolean isInstrumentationBasedReload;
public final boolean isLiveReload;
public State(StateBuilder builder) {
this.lastRun = builder.lastRun;
this.running = builder.running;
this.inProgress = builder.inProgress;
this.run = builder.run;
this.passed = builder.passed;
this.failed = builder.failed;
this.skipped = builder.skipped;
this.currentPassed = builder.currentPassed;
this.currentFailed = builder.currentFailed;
this.currentSkipped = builder.currentSkipped;
this.isBrokenOnly = builder.isBrokenOnly;
this.isTestOutput = builder.isTestOutput;
this.isInstrumentationBasedReload = builder.isInstrumentationBasedReload;
this.isLiveReload = builder.isLiveReload;
}
StateBuilder builder() {
return new StateBuilder(this);
}
@Override
public String toString() {
return "State{" +
"lastRun=" + lastRun +
", running=" + running +
", inProgress=" + inProgress +
", run=" + run +
", passed=" + passed +
", failed=" + failed +
", skipped=" + skipped +
", isBrokenOnly=" + isBrokenOnly +
", isTestOutput=" + isTestOutput +
", isInstrumentationBasedReload=" + isInstrumentationBasedReload +
", isLiveReload=" + isLiveReload +
'}';
}
}
public static | State |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/SlotPoolUtils.java | {
"start": 2108,
"end": 7394
} | class ____ {
public static final Duration TIMEOUT = Duration.ofSeconds(10L);
private SlotPoolUtils() {
throw new UnsupportedOperationException("Cannot instantiate this class.");
}
public static DeclarativeSlotPoolBridge createDeclarativeSlotPoolBridge() {
return new DeclarativeSlotPoolBridgeBuilder().build();
}
public static CompletableFuture<PhysicalSlot> requestNewAllocatedBatchSlot(
SlotPool slotPool,
ComponentMainThreadExecutor mainThreadExecutor,
ResourceProfile resourceProfile) {
return CompletableFuture.supplyAsync(
() ->
slotPool.requestNewAllocatedBatchSlot(
PhysicalSlotRequestUtils.batchRequest(resourceProfile)),
mainThreadExecutor)
.thenCompose(Function.identity());
}
public static ResourceID offerSlots(
SlotPool slotPool,
ComponentMainThreadExecutor mainThreadExecutor,
List<ResourceProfile> resourceProfiles) {
return offerSlots(
slotPool,
mainThreadExecutor,
resourceProfiles,
new SimpleAckingTaskManagerGateway());
}
public static ResourceID tryOfferSlots(
SlotPool slotPool,
ComponentMainThreadExecutor mainThreadExecutor,
List<ResourceProfile> resourceProfiles) {
return offerSlots(
slotPool,
mainThreadExecutor,
resourceProfiles,
new SimpleAckingTaskManagerGateway(),
false);
}
public static ResourceID offerSlots(
SlotPool slotPool,
ComponentMainThreadExecutor mainThreadExecutor,
List<ResourceProfile> resourceProfiles,
TaskManagerGateway taskManagerGateway) {
return offerSlots(slotPool, mainThreadExecutor, resourceProfiles, taskManagerGateway, true);
}
private static ResourceID offerSlots(
SlotPool slotPool,
ComponentMainThreadExecutor mainThreadExecutor,
List<ResourceProfile> resourceProfiles,
TaskManagerGateway taskManagerGateway,
boolean assertAllSlotsAreAccepted) {
final TaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation();
CompletableFuture.runAsync(
() -> {
slotPool.registerTaskManager(taskManagerLocation.getResourceID());
final Collection<SlotOffer> slotOffers =
IntStream.range(0, resourceProfiles.size())
.mapToObj(
i ->
new SlotOffer(
new AllocationID(),
i,
resourceProfiles.get(i)))
.collect(Collectors.toList());
final Collection<SlotOffer> acceptedOffers =
slotPool.offerSlots(
taskManagerLocation, taskManagerGateway, slotOffers);
if (assertAllSlotsAreAccepted) {
assertThat(acceptedOffers).isEqualTo(slotOffers);
}
},
mainThreadExecutor)
.join();
return taskManagerLocation.getResourceID();
}
public static void releaseTaskManager(
SlotPool slotPool,
ComponentMainThreadExecutor mainThreadExecutor,
ResourceID taskManagerResourceId) {
CompletableFuture.runAsync(
() ->
slotPool.releaseTaskManager(
taskManagerResourceId,
new FlinkException("Let's get rid of the offered slot.")),
mainThreadExecutor)
.join();
}
public static void notifyNotEnoughResourcesAvailable(
SlotPoolService slotPoolService,
ComponentMainThreadExecutor mainThreadExecutor,
Collection<ResourceRequirement> acquiredResources) {
CompletableFuture.runAsync(
() -> slotPoolService.notifyNotEnoughResourcesAvailable(acquiredResources),
mainThreadExecutor)
.join();
}
static ResourceCounter calculateResourceCounter(ResourceProfile[] resourceProfiles) {
final Map<ResourceProfile, Integer> resources =
Arrays.stream(resourceProfiles)
.collect(
Collectors.groupingBy(
Function.identity(), reducing(0, e -> 1, Integer::sum)));
final ResourceCounter increment = ResourceCounter.withResources(resources);
return increment;
}
}
| SlotPoolUtils |
java | spring-projects__spring-framework | spring-web/src/testFixtures/java/org/springframework/web/testfixture/method/MvcAnnotationPredicates.java | {
"start": 9200,
"end": 10071
} | class ____ implements Predicate<MethodParameter> {
private String name;
private String pathVar;
public MatrixVariablePredicate name(String name) {
this.name = name;
return this;
}
public MatrixVariablePredicate noName() {
this.name = "";
return this;
}
public MatrixVariablePredicate pathVar(String name) {
this.pathVar = name;
return this;
}
public MatrixVariablePredicate noPathVar() {
this.pathVar = ValueConstants.DEFAULT_NONE;
return this;
}
@Override
public boolean test(MethodParameter parameter) {
MatrixVariable annotation = parameter.getParameterAnnotation(MatrixVariable.class);
return annotation != null &&
(this.name == null || this.name.equalsIgnoreCase(annotation.name())) &&
(this.pathVar == null || this.pathVar.equalsIgnoreCase(annotation.pathVar()));
}
}
}
| MatrixVariablePredicate |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/initializers/annotation/OrderedInitializersAnnotationConfigTests.java | {
"start": 3706,
"end": 3875
} | class ____ {
@Bean
public String baz() {
return PROFILE_TWO;
}
}
// -------------------------------------------------------------------------
static | ConfigTwo |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TraditionalSwitchExpressionTest.java | {
"start": 1941,
"end": 2286
} | class ____ {
void f(int i) {
switch (i) {
default -> System.err.println();
}
}
}
""")
.doTest();
}
@Test
public void negativeArrow() {
testHelper
.addSourceLines(
"Test.java",
"""
| Test |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/Scannable.java | {
"start": 2712,
"end": 9144
} | class ____ exceptions.
*/
/**
* The direct dependent component downstream reference if any. Operators in
* Flux/Mono for instance delegate to a target Subscriber, which is going to be
* the actual chain navigated with this reference key. Subscribers are not always
* {@link Scannable}, but this attribute will convert these raw results to an
* {@link Scannable#isScanAvailable() unavailable scan} object in this case.
* <p>
* A reference chain downstream can be navigated via {@link Scannable#actuals()}.
*/
public static final Attr<Scannable> ACTUAL = new Attr<>(null,
Scannable::from);
/**
* Indicate that for some purposes a {@link Scannable} should be used as additional
* source of information about a contiguous {@link Scannable} in the chain.
* <p>
* For example {@link Scannable#steps()} uses this to collate the
* {@link Scannable#stepName() stepName} of an assembly trace to its
* wrapped operator (the one before it in the assembly chain).
*/
public static final Attr<Boolean> ACTUAL_METADATA = new Attr<>(false);
/**
* A {@link Integer} attribute implemented by components with a backlog
* capacity. It will expose current queue size or similar related to
* user-provided held data. Note that some operators and processors CAN keep
* a backlog larger than {@code Integer.MAX_VALUE}, in which case
* the {@link Attr#LARGE_BUFFERED Attr} {@literal LARGE_BUFFERED}
* should be used instead. Such operators will attempt to serve a BUFFERED
* query but will return {@link Integer#MIN_VALUE} when actual buffer size is
* oversized for int.
*/
public static final Attr<Integer> BUFFERED = new Attr<>(0);
/**
* Return an an {@link Integer} capacity when no {@link #PREFETCH} is defined or
* when an arbitrary maximum limit is applied to the backlog capacity of the
* scanned component. {@link Integer#MAX_VALUE} signal unlimited capacity.
* <p>
* Note: This attribute usually resolves to a constant value.
*/
public static final Attr<Integer> CAPACITY = new Attr<>(0);
/**
* A {@link Boolean} attribute indicating whether or not a downstream component
* has interrupted consuming this scanned component, e.g., a cancelled
* subscription. Note that it differs from {@link #TERMINATED} which is
* intended for "normal" shutdown cycles.
*/
public static final Attr<Boolean> CANCELLED = new Attr<>(false);
/**
* Delay_Error exposes a {@link Boolean} whether the scanned component
* actively supports error delaying if it manages a backlog instead of fast
* error-passing which might drop pending backlog.
* <p>
* Note: This attribute usually resolves to a constant value.
*/
public static final Attr<Boolean> DELAY_ERROR = new Attr<>(false);
/**
* a {@link Throwable} attribute which indicate an error state if the scanned
* component keeps track of it.
*/
public static final Attr<Throwable> ERROR = new Attr<>(null);
/**
* Similar to {@link Attr#BUFFERED}, but reserved for operators that can hold
* a backlog of items that can grow beyond {@literal Integer.MAX_VALUE}. These
* operators will also answer to a {@link Attr#BUFFERED} query up to the point
* where their buffer is actually too large, at which point they'll return
* {@literal Integer.MIN_VALUE}, which serves as a signal that this attribute
* should be used instead. Defaults to {@literal null}.
* <p>
* {@code Flux.flatMap}, {@code Flux.filterWhen}
* and {@code Flux.window} (with overlap) are known to use this attribute.
*/
public static final Attr<Long> LARGE_BUFFERED = new Attr<>(null);
/**
* An arbitrary name given to the operator component. Defaults to {@literal null}.
*/
public static final Attr<String> NAME = new Attr<>(null);
/**
* Parent key exposes the direct upstream relationship of the scanned component.
* It can be a Publisher source to an operator, a Subscription to a Subscriber
* (main flow if ambiguous with inner Subscriptions like flatMap), a Scheduler to
* a Worker. These types are not always {@link Scannable}, but this attribute
* will convert such raw results to an {@link Scannable#isScanAvailable() unavailable scan}
* object in this case.
* <p>
* {@link Scannable#parents()} can be used to navigate the parent chain.
*/
public static final Attr<Scannable> PARENT = new Attr<>(null,
Scannable::from);
/**
* A key that links a {@link Scannable} to another {@link Scannable} it runs on.
* Usually exposes a link between an operator/subscriber and its {@link Worker} or
* {@link Scheduler}, provided these are {@link Scannable}. Will return
* {@link Attr#UNAVAILABLE_SCAN} if the supporting execution is not Scannable or
* {@link Attr#NULL_SCAN} if the operator doesn't define a specific runtime.
*/
public static final Attr<Scannable> RUN_ON = new Attr<>(null, Scannable::from);
/**
* Prefetch is an {@link Integer} attribute defining the rate of processing in a
* component which has capacity to request and hold a backlog of data. It
* usually maps to a component capacity when no arbitrary {@link #CAPACITY} is
* set. {@link Integer#MAX_VALUE} signal unlimited capacity and therefore
* unbounded demand.
* <p>
* Note: This attribute usually resolves to a constant value.
*/
public static final Attr<Integer> PREFETCH = new Attr<>(0);
/**
* A {@link Long} attribute exposing the current pending demand of a downstream
* component. Note that {@link Long#MAX_VALUE} indicates an unbounded (push-style)
* demand as specified in {@link org.reactivestreams.Subscription#request(long)}.
*/
public static final Attr<Long> REQUESTED_FROM_DOWNSTREAM = new Attr<>(0L);
/**
* A {@link Boolean} attribute indicating whether or not an upstream component
* terminated this scanned component. e.g. a post onComplete/onError subscriber.
* By opposition to {@link #CANCELLED} which determines if a downstream
* component interrupted this scanned component.
*/
public static final Attr<Boolean> TERMINATED = new Attr<>(false);
/**
* A {@link Stream} of {@link reactor.util.function.Tuple2} representing key/value
* pairs for tagged components. Defaults to {@literal null}.
*/
public static final Attr<Stream<Tuple2<String, String>>> TAGS = new Attr<>(null);
/**
* An {@link RunStyle} | cast |
java | mapstruct__mapstruct | processor/src/main/java/org/mapstruct/ap/internal/model/assignment/SetterWrapper.java | {
"start": 451,
"end": 2441
} | class ____ extends AssignmentWrapper {
private final List<Type> thrownTypesToExclude;
private final boolean includeSourceNullCheck;
private final boolean setExplicitlyToNull;
private final boolean setExplicitlyToDefault;
public SetterWrapper(Assignment rhs,
List<Type> thrownTypesToExclude,
boolean fieldAssignment,
boolean includeSourceNullCheck,
boolean setExplicitlyToNull,
boolean setExplicitlyToDefault) {
super( rhs, fieldAssignment );
this.thrownTypesToExclude = thrownTypesToExclude;
this.includeSourceNullCheck = includeSourceNullCheck;
this.setExplicitlyToDefault = setExplicitlyToDefault;
this.setExplicitlyToNull = setExplicitlyToNull;
}
public SetterWrapper(Assignment rhs, List<Type> thrownTypesToExclude, boolean fieldAssignment ) {
super( rhs, fieldAssignment );
this.thrownTypesToExclude = thrownTypesToExclude;
this.includeSourceNullCheck = false;
this.setExplicitlyToNull = false;
this.setExplicitlyToDefault = false;
}
@Override
public List<Type> getThrownTypes() {
List<Type> parentThrownTypes = super.getThrownTypes();
List<Type> result = new ArrayList<>( parentThrownTypes );
for ( Type thrownTypeToExclude : thrownTypesToExclude ) {
for ( Type parentThrownType : parentThrownTypes ) {
if ( parentThrownType.isAssignableTo( thrownTypeToExclude ) ) {
result.remove( parentThrownType );
}
}
}
return result;
}
public boolean isSetExplicitlyToNull() {
return setExplicitlyToNull;
}
public boolean isSetExplicitlyToDefault() {
return setExplicitlyToDefault;
}
public boolean isIncludeSourceNullCheck() {
return includeSourceNullCheck;
}
}
| SetterWrapper |
java | apache__camel | components/camel-workday/src/main/java/org/apache/camel/component/workday/auth/AuthClientForIntegration.java | {
"start": 1595,
"end": 4791
} | class ____ implements AuthenticationClient {
public static final String BASE_TOKEN_ENDPOINT = "https://%s/ccx/oauth2/%s/token";
private static final String GRANT_TYPE = "grant_type";
private static final String REFRESH_TOKEN = "refresh_token";
private static final String CONTENT_TYPE_HEADER = "Content-Type";
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String ACCESS_TOKEN = "access_token";
private static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
private final WorkdayConfiguration workdayConfiguration;
public AuthClientForIntegration(WorkdayConfiguration workdayConfiguration) {
this.workdayConfiguration = workdayConfiguration;
}
@Override
public void configure(CloseableHttpClient httpClient, HttpUriRequest method) throws IOException {
String bearerToken = getBearerToken(httpClient);
method.addHeader(AUTHORIZATION_HEADER, "Bearer " + bearerToken);
}
protected String getBearerToken(CloseableHttpClient httpClient) throws IOException {
String tokenUrl = String.format(BASE_TOKEN_ENDPOINT, workdayConfiguration.getHost(), workdayConfiguration.getTenant());
HttpPost httpPost = createPostMethod(tokenUrl);
return httpClient.execute(
httpPost,
httpResponse -> {
if (httpResponse.getCode() != HttpStatus.SC_OK) {
throw new IllegalStateException(
"Got the invalid http status value '" + new StatusLine(httpResponse)
+ "' as the result of the Token Request '" + tokenUrl + "'");
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
httpResponse.getEntity().writeTo(baos);
return parseResponse(baos.toString());
}
});
}
private HttpPost createPostMethod(String tokenUrl) {
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair(GRANT_TYPE, REFRESH_TOKEN));
nvps.add(new BasicNameValuePair(REFRESH_TOKEN, workdayConfiguration.getTokenRefresh()));
HttpPost postMethod = new HttpPost(tokenUrl);
postMethod.addHeader(CONTENT_TYPE_HEADER, CONTENT_TYPE);
postMethod.addHeader(AUTHORIZATION_HEADER,
"Basic " + Arrays.toString(Base64.getEncoder()
.encode((workdayConfiguration.getClientId() + ":" + workdayConfiguration.getClientSecret())
.getBytes())));
postMethod.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
return postMethod;
}
private String parseResponse(String response) {
int tokenIdx = response.indexOf(ACCESS_TOKEN);
if (tokenIdx < 1) {
throw new IllegalStateException("No valid access token response.");
}
response = response.substring(response.indexOf(ACCESS_TOKEN) + 16, response.length() - 3);
return response;
}
}
| AuthClientForIntegration |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/TestJsonSerializeAs.java | {
"start": 760,
"end": 923
} | class ____ implements Fooable {
@Override
public int getFoo() { return 42; }
public int getBar() { return 15; }
}
public | FooImplNoAnno |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryMethodUnitTests.java | {
"start": 19310,
"end": 20139
} | interface ____ extends Repository<User, Integer> {
// Invalid return type
User findByFirstname(String firstname, Pageable pageable);
// Should not use Pageable *and* Sort
Page<User> findByFirstname(String firstname, Pageable pageable, Sort sort);
// Must not use two Pageables
Page<User> findByFirstname(String firstname, Pageable first, Pageable second);
// Must not use two Pageables
Page<User> findByFirstname(String firstname, Sort first, Sort second);
// Not backed by a named query or @Query annotation
@Modifying
void updateMethod(String firstname);
// Modifying and Pageable is not allowed
@Modifying
Page<String> updateMethod(String firstname, Pageable pageable);
// Modifying and Sort is not allowed
@Modifying
void updateMethod(String firstname, Sort sort);
}
| InvalidRepository |
java | quarkusio__quarkus | independent-projects/bootstrap/core/src/test/java/io/quarkus/bootstrap/resolver/test/SystemPropertyOverridesPomPropertyDependencyTestCase.java | {
"start": 456,
"end": 1818
} | class ____ extends CollectDependenciesBase {
@Override
protected void setupDependencies() {
final TsArtifact x12 = new TsArtifact("x", "2");
final TsArtifact x13 = new TsArtifact("x", "3");
install(x12);
install(x13);
// x.version in pom is 2
setPomProperty("x.version", "2");
addDep(new TsArtifact("x", "${x.version}"));
// the system property of x.version is 3
setSystemProperty("x.version", "3");
// it is expected that the system property will dominate
addCollectedDep(x13, DependencyFlags.DIRECT);
}
@Override
protected BootstrapAppModelResolver getTestResolver() throws Exception {
// location of the root in the local maven repo
final Path installDir = getInstallDir(root);
// here i'm faking a project from which the root could have been installed
final Path projectDir = workDir.resolve("project");
Files.createDirectories(projectDir);
IoUtils.copy(installDir.resolve(root.toPomArtifact().getArtifactFileName()), projectDir.resolve("pom.xml"));
// workspace reader for the root project
final LocalProject currentProject = LocalProject.loadWorkspace(projectDir);
return newAppModelResolver(currentProject);
}
}
| SystemPropertyOverridesPomPropertyDependencyTestCase |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/graph/StreamConfigTest.java | {
"start": 2330,
"end": 2957
} | class ____'t be cleared.
streamConfig.clearInitialConfigs();
assertThatThrownBy(() -> streamConfig.getStreamOperatorFactory(classLoader))
.hasCauseInstanceOf(IllegalStateException.class)
.hasRootCauseMessage("serializedUDF has been removed.");
assertThat(streamConfig.getStreamOperatorFactoryClass(classLoader)).isNotNull();
assertThatThrownBy(() -> streamConfig.getTransitiveChainedTaskConfigs(classLoader))
.hasCauseInstanceOf(IllegalStateException.class)
.hasRootCauseMessage("chainedTaskConfig_ has been removed.");
}
}
| shouldn |
java | redisson__redisson | redisson/src/main/java/org/redisson/client/protocol/decoder/MapScanResultReplayDecoder.java | {
"start": 926,
"end": 1389
} | class ____ implements MultiDecoder<MapScanResult<Object, Object>> {
@Override
public Decoder<Object> getDecoder(Codec codec, int paramNum, State state, long size) {
return StringCodec.INSTANCE.getValueDecoder();
}
@Override
public MapScanResult<Object, Object> decode(List<Object> parts, State state) {
return new MapScanResult<>((String) parts.get(0), (Map<Object, Object>) parts.get(1));
}
}
| MapScanResultReplayDecoder |
java | quarkusio__quarkus | extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java | {
"start": 99729,
"end": 103230
} | enum ____
return Modifier.isStatic(target.asField().flags());
default:
throw new IllegalArgumentException();
}
}
static boolean enumConstantFilter(AnnotationTarget target) {
if (target.kind() == Kind.FIELD) {
return target.asField().isEnumConstant();
}
return false;
}
static String findTemplatePath(TemplatesAnalysisBuildItem analysis, String id) {
for (TemplateAnalysis templateAnalysis : analysis.getAnalysis()) {
if (templateAnalysis.generatedId.equals(id)) {
return templateAnalysis.path;
}
}
return null;
}
@BuildStep
void generateValueResolvers(QuteConfig config,
BuildProducer<GeneratedClassBuildItem> generatedClasses,
BuildProducer<GeneratedResourceBuildItem> generatedResources,
BeanArchiveIndexBuildItem beanArchiveIndex,
ApplicationArchivesBuildItem applicationArchivesBuildItem,
List<TemplateExtensionMethodBuildItem> templateExtensionMethods,
List<ImplicitValueResolverBuildItem> implicitClasses,
TemplatesAnalysisBuildItem templatesAnalysis,
List<PanacheEntityClassesBuildItem> panacheEntityClasses,
List<TemplateDataBuildItem> templateData,
List<TemplateGlobalBuildItem> templateGlobals,
List<IncorrectExpressionBuildItem> incorrectExpressions,
LiveReloadBuildItem liveReloadBuildItem,
CompletedApplicationClassPredicateBuildItem applicationClassPredicate,
BuildProducer<GeneratedValueResolverBuildItem> generatedResolvers,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<TemplateGlobalProviderBuildItem> globalProviders) {
if (!incorrectExpressions.isEmpty()) {
// Skip generation if a validation error occurs
return;
}
IndexView index = beanArchiveIndex.getIndex();
ClassOutput classOutput = new GeneratedClassGizmo2Adaptor(generatedClasses, generatedResources,
new Function<String, String>() {
@Override
public String apply(String name) {
int idx = name.lastIndexOf(ExtensionMethodGenerator.NAMESPACE_SUFFIX);
if (idx == -1) {
idx = name.lastIndexOf(ExtensionMethodGenerator.SUFFIX);
}
if (idx == -1) {
idx = name.lastIndexOf(ValueResolverGenerator.NAMESPACE_SUFFIX);
}
if (idx == -1) {
idx = name.lastIndexOf(ValueResolverGenerator.SUFFIX);
}
if (idx == -1) {
idx = name.lastIndexOf(TemplateGlobalGenerator.SUFFIX);
}
String className = name.substring(0, idx);
if (className.contains(ValueResolverGenerator.NESTED_SEPARATOR)) {
className = className.replace(ValueResolverGenerator.NESTED_SEPARATOR, "$");
}
return className;
}
});
// NOTE: We can't use this optimization for classes generated by ValueResolverGenerator because we cannot easily
// map a target | support |
java | quarkusio__quarkus | devtools/cli/src/main/java/io/quarkus/cli/deploy/Openshift.java | {
"start": 1120,
"end": 1907
} | enum ____ {
Deployment,
DeploymentConfig,
StatefulSet,
Job
}
@CommandLine.Option(names = { "--deployment-kind" }, description = "The kind of resource to generate and deploy")
public Optional<DeploymentKind> kind;
@Override
public void populateContext(BuildToolContext context) {
super.populateContext(context);
context.getPropertiesOptions().properties.put(String.format(QUARKUS_DEPLOY_FORMAT, OPENSHIFT), "true");
context.getForcedExtensions().add(OPENSHIFT_EXTENSION);
kind.ifPresent(k -> {
context.getPropertiesOptions().properties.put(DEPLOYMENT_KIND, k.name());
});
}
@Override
public String getDefaultImageBuilder() {
return OPENSHIFT;
}
}
| DeploymentKind |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/LambdaMonoSubscriber.java | {
"start": 1244,
"end": 6848
} | class ____<T> implements InnerConsumer<T>, Disposable {
final @Nullable Consumer<? super T> consumer;
final @Nullable Consumer<? super Throwable> errorConsumer;
final @Nullable Runnable completeConsumer;
final @Nullable Consumer<? super Subscription> subscriptionConsumer;
final Context initialContext;
@SuppressWarnings("NotNullFieldNotInitialized") // initialized in onSubscribe
volatile Subscription subscription;
// https://github.com/uber/NullAway/issues/1157
@SuppressWarnings({"rawtypes", "DataFlowIssue"})
static final AtomicReferenceFieldUpdater<LambdaMonoSubscriber, @Nullable Subscription> S =
AtomicReferenceFieldUpdater.newUpdater(LambdaMonoSubscriber.class,
Subscription.class,
"subscription");
/**
* Create a {@link Subscriber} reacting onNext, onError and onComplete. The subscriber
* will automatically request Long.MAX_VALUE onSubscribe.
* <p>
* The argument {@code subscriptionHandler} is executed once by new subscriber to
* generate a context shared by every request calls.
*
* @param consumer A {@link Consumer} with argument onNext data
* @param errorConsumer A {@link Consumer} called onError
* @param completeConsumer A {@link Runnable} called onComplete with the actual
* context if any
* @param subscriptionConsumer A {@link Consumer} called with the {@link Subscription}
* to perform initial request, or null to request max
* @param initialContext A {@link Context} for this subscriber, or null to use the default
* of an {@link Context#empty() empty Context}.
*/
LambdaMonoSubscriber(@Nullable Consumer<? super T> consumer,
@Nullable Consumer<? super Throwable> errorConsumer,
@Nullable Runnable completeConsumer,
@Nullable Consumer<? super Subscription> subscriptionConsumer,
@Nullable Context initialContext) {
this.consumer = consumer;
this.errorConsumer = errorConsumer;
this.completeConsumer = completeConsumer;
this.subscriptionConsumer = subscriptionConsumer;
this.initialContext = initialContext == null ? Context.empty() : initialContext;
}
/**
* Create a {@link Subscriber} reacting onNext, onError and onComplete. The subscriber
* will automatically request Long.MAX_VALUE onSubscribe.
* <p>
* The argument {@code subscriptionHandler} is executed once by new subscriber to
* generate a context shared by every request calls.
*
* @param consumer A {@link Consumer} with argument onNext data
* @param errorConsumer A {@link Consumer} called onError
* @param completeConsumer A {@link Runnable} called onComplete with the actual
* context if any
* @param subscriptionConsumer A {@link Consumer} called with the {@link Subscription}
* to perform initial request, or null to request max
*/ //left mainly for the benefit of tests
LambdaMonoSubscriber(@Nullable Consumer<? super T> consumer,
@Nullable Consumer<? super Throwable> errorConsumer,
@Nullable Runnable completeConsumer,
@Nullable Consumer<? super Subscription> subscriptionConsumer) {
this(consumer, errorConsumer, completeConsumer, subscriptionConsumer, null);
}
@Override
public Context currentContext() {
return this.initialContext;
}
@Override
public final void onSubscribe(Subscription s) {
if (Operators.validate(subscription, s)) {
this.subscription = s;
if (subscriptionConsumer != null) {
try {
subscriptionConsumer.accept(s);
}
catch (Throwable t) {
Exceptions.throwIfFatal(t);
s.cancel();
onError(t);
}
}
else {
s.request(Long.MAX_VALUE);
}
}
}
@Override
public final void onComplete() {
Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
if (s == Operators.cancelledSubscription()) {
return;
}
if (completeConsumer != null) {
try {
completeConsumer.run();
}
catch (Throwable t) {
Operators.onErrorDropped(t, this.initialContext);
}
}
}
@Override
public final void onError(Throwable t) {
Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
if (s == Operators.cancelledSubscription()) {
Operators.onErrorDropped(t, this.initialContext);
return;
}
doError(t);
}
void doError(Throwable t) {
if (errorConsumer != null) {
errorConsumer.accept(t);
}
else {
Operators.onErrorDropped(Exceptions.errorCallbackNotImplemented(t), this.initialContext);
}
}
@Override
public final void onNext(T x) {
Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
if (s == Operators.cancelledSubscription()) {
Operators.onNextDropped(x, this.initialContext);
return;
}
if (consumer != null) {
try {
consumer.accept(x);
}
catch (Throwable t) {
Exceptions.throwIfFatal(t);
s.cancel();
doError(t);
}
}
if (completeConsumer != null) {
try {
completeConsumer.run();
}
catch (Throwable t) {
Operators.onErrorDropped(t, this.initialContext);
}
}
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) {
return subscription;
}
if (key == Attr.PREFETCH) {
return Integer.MAX_VALUE;
}
if (key == Attr.TERMINATED || key == Attr.CANCELLED) {
return isDisposed();
}
if (key == RUN_STYLE) {
return SYNC;
}
return null;
}
@Override
public boolean isDisposed() {
return subscription == Operators.cancelledSubscription();
}
@Override
public void dispose() {
Subscription s = S.getAndSet(this, Operators.cancelledSubscription());
if (s != null && s != Operators.cancelledSubscription()) {
s.cancel();
}
}
}
| LambdaMonoSubscriber |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java | {
"start": 64133,
"end": 64932
} | class ____ extends RuntimeException {
private static final JavaVersion MINIMUM_REQUIRED_JAVA_VERSION = JavaVersion.TWENTY_FIVE;
private static final JavaVersion CURRENT_JAVA_VERSION = JavaVersion.getJavaVersion();
NativeImageRequirementsException(String message) {
super(message);
}
static void throwIfNotMet() {
if (CURRENT_JAVA_VERSION.isOlderThan(MINIMUM_REQUIRED_JAVA_VERSION)) {
throw new NativeImageRequirementsException("Native Image requirements not met. "
+ "Native Image must support at least Java %s but Java %s was detected"
.formatted(MINIMUM_REQUIRED_JAVA_VERSION, CURRENT_JAVA_VERSION));
}
}
}
/**
* {@link SpringApplicationHook} decorator that ensures the hook is only used once.
*/
private static final | NativeImageRequirementsException |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MisusedDayOfYearTest.java | {
"start": 2774,
"end": 3346
} | class ____ {
static {
DateTimeFormatter.ofPattern("'D'yy-MM-dd");
DateTimeFormatter.ofPattern("'D'''yy-MM-dd");
DateTimeFormatter.ofPattern("'''D'yy-MM-dd");
DateTimeFormatter.ofPattern("'D''D'yy-MM-dd");
}
}
""")
.doTest();
}
@Test
public void escapedInQuotes_butAlsoAsSpecialChar() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.time.format.DateTimeFormatter;
| Test |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/data/utils/ProjectedRowDataTest.java | {
"start": 1371,
"end": 3458
} | class ____ {
@Test
void testProjectedRows() {
final RowData initialRow = GenericRowData.of(0L, 1L, 2L, 3L, 4L);
final ProjectedRowData projectedRowData =
ProjectedRowData.from(
new int[][] {new int[] {2}, new int[] {0}, new int[] {1}, new int[] {4}});
final RowDataAssert rowAssert = assertThat(projectedRowData);
projectedRowData.replaceRow(initialRow);
rowAssert.hasKind(RowKind.INSERT).hasArity(4);
rowAssert.getLong(0).isEqualTo(2);
rowAssert.getLong(1).isEqualTo(0);
rowAssert.getLong(2).isEqualTo(1);
rowAssert.getLong(3).isEqualTo(4);
projectedRowData.replaceRow(GenericRowData.of(5L, 6L, 7L, 8L, 9L, 10L));
rowAssert.hasKind(RowKind.INSERT).hasArity(4);
rowAssert.getLong(0).isEqualTo(7);
rowAssert.getLong(1).isEqualTo(5);
rowAssert.getLong(2).isEqualTo(6);
rowAssert.getLong(3).isEqualTo(9);
}
@Test
void testProjectedRowsDoesntSupportNestedProjections() {
assertThatThrownBy(
() ->
ProjectedRowData.from(
new int[][] {
new int[] {2},
new int[] {0, 1},
new int[] {1},
new int[] {4}
}))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testIsNullAtNonProjected() {
RowData initialRow = GenericRowData.of(-1L, -1L, 3L, -1L, 5L);
RowData projected = ProjectedRowData.from(new int[] {2, 4}, true).replaceRow(initialRow);
assertFalse(projected.isNullAt(0)); // 3L, projected
assertFalse(projected.isNullAt(1)); // 5L, projected
assertTrue(projected.isNullAt(2)); // not projected
assertTrue(projected.isNullAt(3)); // not projected and doesn't exist in the original
}
}
| ProjectedRowDataTest |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/authorization/method/AuthorizationManagerAfterReactiveMethodInterceptorTests.java | {
"start": 14100,
"end": 14253
} | interface ____
extends ReactiveAuthorizationManager<MethodInvocationResult>, MethodAuthorizationDeniedHandler {
}
| HandlingReactiveAuthorizationManager |
java | apache__camel | components/camel-grpc/src/main/java/org/apache/camel/component/grpc/GrpcUtils.java | {
"start": 2382,
"end": 3736
} | class ____ depends on the invocation style newBlockingStub - for sync style newStub - for async
* style newFutureStub - for ListenableFuture-style (not implemented yet)
*/
@SuppressWarnings({ "rawtypes" })
private static Object constructGrpcStubClass(
String packageName, String serviceName, String stubMethod, Channel channel, final CallCredentials creds,
final CamelContext context) {
Class[] paramChannel = { Channel.class };
Object grpcStub = null;
String serviceClassName = constructFullClassName(packageName, serviceName + GrpcConstants.GRPC_SERVICE_CLASS_POSTFIX);
try {
Class grpcServiceClass = context.getClassResolver().resolveMandatoryClass(serviceClassName);
Method grpcMethod = ReflectionHelper.findMethod(grpcServiceClass, stubMethod, paramChannel);
if (grpcMethod == null) {
throw new IllegalArgumentException("gRPC service method not found: " + serviceClassName + "." + stubMethod);
}
grpcStub = ObjectHelper.invokeMethod(grpcMethod, grpcServiceClass, channel);
if (creds != null) {
return addClientCallCredentials(grpcStub, creds);
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("gRPC service | instance |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/scanner/ErrorProneInjectorTest.java | {
"start": 2972,
"end": 3204
} | class ____ {
final int x;
ErrorProneFlagsAndZeroArgsConstructor() {
this.x = 0;
}
ErrorProneFlagsAndZeroArgsConstructor(ErrorProneFlags flags) {
this.x = 1;
}
}
}
| ErrorProneFlagsAndZeroArgsConstructor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/ondelete/toone/ToOneOnDeleteSetNullTest.java | {
"start": 3152,
"end": 3350
} | class ____ {
@Id
private Long id;
private String name;
@ManyToOne
@OnDelete(action = OnDeleteAction.SET_NULL)
private Parent parent;
}
@Entity(name = "GrandChild")
public static | Child |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/dataset/DataSetEndpointTest.java | {
"start": 4824,
"end": 5013
} | class ____ extends DataSetSupport {
@Override
protected Object createMessageBody(long messageIndex) {
return "Message " + messageIndex;
}
}
}
| MyDataSet |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/monitor/event/EventMonitor.java | {
"start": 876,
"end": 1131
} | interface ____ {
void startEvent(String eventName, String target, long timestamp);
void endEvent(String eventName, String target, long timestamp);
void errorEvent(String eventName, String target, long timestamp, Throwable cause);
}
| EventMonitor |
java | spring-projects__spring-boot | module/spring-boot-cache/src/main/java/org/springframework/boot/cache/autoconfigure/CouchbaseCacheManagerBuilderCustomizer.java | {
"start": 1172,
"end": 1392
} | interface ____ {
/**
* Customize the {@link CouchbaseCacheManagerBuilder}.
* @param builder the builder to customize
*/
void customize(CouchbaseCacheManagerBuilder builder);
}
| CouchbaseCacheManagerBuilderCustomizer |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/upgrade/GlobalHttpUpgradeCheckTest.java | {
"start": 7032,
"end": 7232
} | class ____ extends ChainHttpUpgradeCheckBase {
@Override
protected int priority() {
return 1000;
}
}
@Dependent
public static final | ChainHttpUpgradeCheck4 |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/ConstructorParameterPropertyDescriptor.java | {
"start": 1076,
"end": 2088
} | class ____ extends ParameterPropertyDescriptor {
private final ExecutableElement setter;
private final VariableElement field;
ConstructorParameterPropertyDescriptor(String name, TypeMirror type, VariableElement parameter,
TypeElement declaringElement, ExecutableElement getter, ExecutableElement setter, VariableElement field) {
super(name, type, parameter, declaringElement, getter);
this.setter = setter;
this.field = field;
}
@Override
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
return resolveItemDeprecation(environment, getGetter(), this.setter, this.field);
}
@Override
protected boolean isMarkedAsNested(MetadataGenerationEnvironment environment) {
return environment.getNestedConfigurationPropertyAnnotation(this.field) != null;
}
@Override
protected String resolveDescription(MetadataGenerationEnvironment environment) {
return environment.getTypeUtils().getJavaDoc(this.field);
}
}
| ConstructorParameterPropertyDescriptor |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/MissingRuntimeRetentionTest.java | {
"start": 5156,
"end": 5390
} | class ____ {
/** A scoping (@Scope) annotation with runtime retention */
@Scope
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @ | MissingRuntimeRetentionNegativeCases |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/transport/StubLinkedProjectConfigService.java | {
"start": 873,
"end": 1277
} | class ____ implements LinkedProjectConfigService {
public static final StubLinkedProjectConfigService INSTANCE = new StubLinkedProjectConfigService();
@Override
public void register(LinkedProjectConfigListener listener) {}
@Override
public Collection<LinkedProjectConfig> getInitialLinkedProjectConfigs() {
return Collections.emptyList();
}
}
| StubLinkedProjectConfigService |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/exec/OrderingTests.java | {
"start": 575,
"end": 1590
} | class ____ {
@Test
public void testBasicOrdering(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "from SalesAssociate p order by p.name.familiarName" )
.list();
}
);
}
@Test
@JiraKey( value = "HHH-1356" )
public void testFunctionBasedOrdering(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "from SalesAssociate p order by upper( p.name.familiarName )" )
.list();
}
);
}
@Test
@JiraKey( value = "HHH-11688" )
public void testSelectAliasOrdering(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "select v.name as n from Vendor v order by n" )
.list();
}
);
}
@Test
@JiraKey( value = "HHH-11688" )
public void testSelectPositionOrdering(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
session.createQuery( "select v.name as n from Vendor v order by 1" )
.list();
}
);
}
}
| OrderingTests |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java | {
"start": 24786,
"end": 25113
} | class ____ {
@Test
void deleteTempDir(@TempDir Path tempDir) throws IOException {
Files.delete(tempDir);
assertThat(tempDir).doesNotExist();
}
}
// https://github.com/junit-team/junit-framework/issues/2046
@SuppressWarnings("JUnitMalformedDeclaration")
static | UserTempDirectoryDeletionDoesNotCauseFailureTestCase |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/jdk/JDKNumberDeserTest.java | {
"start": 3795,
"end": 4241
} | class ____ extends Result {
private Point center;
private Double radius;
public Double getRadius() {
return radius;
}
public void setRadius(Double radius) {
this.radius = radius;
}
public Point getCenter() {
return center;
}
public void setCenter(Point center) {
this.center = center;
}
}
static | CenterResult |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_807.java | {
"start": 1344,
"end": 1515
} | class ____ {
public String ckid;
public String rcToken;
public WechatUserInfo userInfo;
public boolean isNewUser;
}
public static | Root |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/xslt/XsltIncludeRelativeFileSchemeTest.java | {
"start": 1042,
"end": 1925
} | class ____ extends ContextTestSupport {
@Test
public void testXsltIncludeRelative() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
// the include file has the span style so check that its there
mock.message(0).body().contains("<span style=\"font-size=22px;\">Minnie Mouse</span>");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("file:src/test/data/?fileName=staff.xml&noop=true&initialDelay=0&delay=10")
.to("xslt:file:src/test/resources/xslt/staff/staff.xsl").to("log:foo")
.to("mock:result");
}
};
}
}
| XsltIncludeRelativeFileSchemeTest |
java | spring-projects__spring-security | docs/src/test/java/org/springframework/security/docs/servlet/authorization/authzauthorizationmanagerfactory/AuthorizationManagerFactoryConfiguration.java | {
"start": 1398,
"end": 2426
} | class ____ {
// tag::config[]
@Bean
<T> AuthorizationManagerFactory<T> authorizationManagerFactory() {
DefaultAuthorizationManagerFactory<T> authorizationManagerFactory =
new DefaultAuthorizationManagerFactory<>();
authorizationManagerFactory.setTrustResolver(getAuthenticationTrustResolver());
authorizationManagerFactory.setRoleHierarchy(getRoleHierarchy());
authorizationManagerFactory.setRolePrefix("role_");
return authorizationManagerFactory;
}
// end::config[]
private static AuthenticationTrustResolverImpl getAuthenticationTrustResolver() {
AuthenticationTrustResolverImpl authenticationTrustResolver =
new AuthenticationTrustResolverImpl();
authenticationTrustResolver.setAnonymousClass(Anonymous.class);
authenticationTrustResolver.setRememberMeClass(RememberMe.class);
return authenticationTrustResolver;
}
private static RoleHierarchyImpl getRoleHierarchy() {
return RoleHierarchyImpl.fromHierarchy("role_admin > role_user");
}
static | AuthorizationManagerFactoryConfiguration |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/isolation/PluginsRecommenders.java | {
"start": 7394,
"end": 7640
} | class ____ extends ConverterPluginVersionRecommender {
@Override
protected String converterConfig() {
return ConnectorConfig.VALUE_CONVERTER_CLASS_CONFIG;
}
}
public | ValueConverterPluginVersionRecommender |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/AuxServices.java | {
"start": 8377,
"end": 8694
} | class ____ for auxiliary " +
"service" + service.getName());
}
return ReflectionUtils.newInstance(sClass, null);
}
/**
* Creates an auxiliary service from a specification using a custom local
* classpath.
*
* @param service aux service record
* @param appLocalClassPath local | defined |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerFileSplitIT.java | {
"start": 1062,
"end": 1957
} | class ____ extends FtpServerTestSupport {
private String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}/incoming/?password=admin&delete=true";
}
@Test
public void testFtpRoute() throws Exception {
MockEndpoint resultEndpoint = getMockEndpoint("mock:result");
resultEndpoint.expectedBodiesReceived("line1", "line2", "line3");
template.sendBodyAndHeader(getFtpUrl(), new File("src/test/data/ftptextfile/textexample.txt"), Exchange.FILE_NAME,
"textexample.txt");
resultEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(getFtpUrl()).to("log:file").split(body().tokenize(LS)).to("log:line").to("mock:result");
}
};
}
}
| FtpConsumerFileSplitIT |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/asm/SymbolTable.java | {
"start": 44953,
"end": 50845
} | class ____, an arbitrary string, a method descriptor, a module or a
* package name, depending on tag.
*/
private void addConstantUtf8Reference(final int index, final int tag, final String value) {
add(new Entry(index, tag, value, hash(tag, value)));
}
// -----------------------------------------------------------------------------------------------
// Bootstrap method entries management.
// -----------------------------------------------------------------------------------------------
/**
* Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if
* the BootstrapMethods already contains a similar bootstrap method.
*
* @param bootstrapMethodHandle a bootstrap method handle.
* @param bootstrapMethodArguments the bootstrap method arguments.
* @return a new or already existing Symbol with the given value.
*/
Symbol addBootstrapMethod(
final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {
ByteVector bootstrapMethodsAttribute = bootstrapMethods;
if (bootstrapMethodsAttribute == null) {
bootstrapMethodsAttribute = bootstrapMethods = new ByteVector();
}
// The bootstrap method arguments can be Constant_Dynamic values, which reference other
// bootstrap methods. We must therefore add the bootstrap method arguments to the constant pool
// and BootstrapMethods attribute first, so that the BootstrapMethods attribute is not modified
// while adding the given bootstrap method to it, in the rest of this method.
int numBootstrapArguments = bootstrapMethodArguments.length;
int[] bootstrapMethodArgumentIndexes = new int[numBootstrapArguments];
for (int i = 0; i < numBootstrapArguments; i++) {
bootstrapMethodArgumentIndexes[i] = addConstant(bootstrapMethodArguments[i]).index;
}
// Write the bootstrap method in the BootstrapMethods table. This is necessary to be able to
// compare it with existing ones, and will be reverted below if there is already a similar
// bootstrap method.
int bootstrapMethodOffset = bootstrapMethodsAttribute.length;
bootstrapMethodsAttribute.putShort(
addConstantMethodHandle(
bootstrapMethodHandle.getTag(),
bootstrapMethodHandle.getOwner(),
bootstrapMethodHandle.getName(),
bootstrapMethodHandle.getDesc(),
bootstrapMethodHandle.isInterface())
.index);
bootstrapMethodsAttribute.putShort(numBootstrapArguments);
for (int i = 0; i < numBootstrapArguments; i++) {
bootstrapMethodsAttribute.putShort(bootstrapMethodArgumentIndexes[i]);
}
// Compute the length and the hash code of the bootstrap method.
int bootstrapMethodlength = bootstrapMethodsAttribute.length - bootstrapMethodOffset;
int hashCode = bootstrapMethodHandle.hashCode();
for (Object bootstrapMethodArgument : bootstrapMethodArguments) {
hashCode ^= bootstrapMethodArgument.hashCode();
}
hashCode &= 0x7FFFFFFF;
// Add the bootstrap method to the symbol table or revert the above changes.
return addBootstrapMethod(bootstrapMethodOffset, bootstrapMethodlength, hashCode);
}
/**
* Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if
* the BootstrapMethods already contains a similar bootstrap method (more precisely, reverts the
* content of {@link #bootstrapMethods} to remove the last, duplicate bootstrap method).
*
* @param offset the offset of the last bootstrap method in {@link #bootstrapMethods}, in bytes.
* @param length the length of this bootstrap method in {@link #bootstrapMethods}, in bytes.
* @param hashCode the hash code of this bootstrap method.
* @return a new or already existing Symbol with the given value.
*/
private Symbol addBootstrapMethod(final int offset, final int length, final int hashCode) {
final byte[] bootstrapMethodsData = bootstrapMethods.data;
Entry entry = get(hashCode);
while (entry != null) {
if (entry.tag == Symbol.BOOTSTRAP_METHOD_TAG && entry.hashCode == hashCode) {
int otherOffset = (int) entry.data;
boolean isSameBootstrapMethod = true;
for (int i = 0; i < length; ++i) {
if (bootstrapMethodsData[offset + i] != bootstrapMethodsData[otherOffset + i]) {
isSameBootstrapMethod = false;
break;
}
}
if (isSameBootstrapMethod) {
bootstrapMethods.length = offset; // Revert to old position.
return entry;
}
}
entry = entry.next;
}
return put(new Entry(bootstrapMethodCount++, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode));
}
// -----------------------------------------------------------------------------------------------
// Type table entries management.
// -----------------------------------------------------------------------------------------------
/**
* Returns the type table element whose index is given.
*
* @param typeIndex a type table index.
* @return the type table element whose index is given.
*/
Symbol getType(final int typeIndex) {
return typeTable[typeIndex];
}
/**
* Returns the label corresponding to the "forward uninitialized" type table element whose index
* is given.
*
* @param typeIndex the type table index of a "forward uninitialized" type table element.
* @return the label corresponding of the NEW instruction which created this "forward
* uninitialized" type.
*/
Label getForwardUninitializedLabel(final int typeIndex) {
return labelTable[(int) typeTable[typeIndex].data].label;
}
/**
* Adds a type in the type table of this symbol table. Does nothing if the type table already
* contains a similar type.
*
* @param value an internal | name |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/Lifecycle.java | {
"start": 2254,
"end": 15384
} | class ____ implements Closeable {
private static final LifecycleVersion LOGGING_MINIMUM_VERSION = LifecycleVersion.parse("0.0.5");
private static final String PLATFORM_API_VERSION_KEY = "CNB_PLATFORM_API";
private static final String SOURCE_DATE_EPOCH_KEY = "SOURCE_DATE_EPOCH";
private static final String DOMAIN_SOCKET_PATH = "/var/run/docker.sock";
private static final List<String> DEFAULT_SECURITY_OPTIONS = List.of("label=disable");
private final BuildLog log;
private final DockerApi docker;
private final @Nullable ResolvedDockerHost dockerHost;
private final BuildRequest request;
private final EphemeralBuilder builder;
private final LifecycleVersion lifecycleVersion;
private final ApiVersion platformVersion;
private final Cache layers;
private final Cache application;
private final Cache buildCache;
private final Cache launchCache;
private final String applicationDirectory;
private final List<String> securityOptions;
private boolean executed;
private boolean applicationVolumePopulated;
/**
* Create a new {@link Lifecycle} instance.
* @param log build output log
* @param docker the Docker API
* @param dockerHost the Docker host information
* @param request the request to process
* @param builder the ephemeral builder used to run the phases
*/
Lifecycle(BuildLog log, DockerApi docker, @Nullable ResolvedDockerHost dockerHost, BuildRequest request,
EphemeralBuilder builder) {
this.log = log;
this.docker = docker;
this.dockerHost = dockerHost;
this.request = request;
this.builder = builder;
this.lifecycleVersion = LifecycleVersion.parse(builder.getBuilderMetadata().getLifecycle().getVersion());
this.platformVersion = getPlatformVersion(builder.getBuilderMetadata().getLifecycle());
this.layers = getLayersBindingSource(request);
this.application = getApplicationBindingSource(request);
this.buildCache = getBuildCache(request);
this.launchCache = getLaunchCache(request);
this.applicationDirectory = getApplicationDirectory(request);
this.securityOptions = getSecurityOptions(request);
}
String getApplicationDirectory() {
return this.applicationDirectory;
}
private Cache getBuildCache(BuildRequest request) {
if (request.getBuildCache() != null) {
return request.getBuildCache();
}
return createVolumeCache(request, "build");
}
private Cache getLaunchCache(BuildRequest request) {
if (request.getLaunchCache() != null) {
return request.getLaunchCache();
}
return createVolumeCache(request, "launch");
}
private String getApplicationDirectory(BuildRequest request) {
return (request.getApplicationDirectory() != null) ? request.getApplicationDirectory() : Directory.APPLICATION;
}
private List<String> getSecurityOptions(BuildRequest request) {
if (request.getSecurityOptions() != null) {
return request.getSecurityOptions();
}
return (Platform.isWindows()) ? Collections.emptyList() : DEFAULT_SECURITY_OPTIONS;
}
private ApiVersion getPlatformVersion(BuilderMetadata.Lifecycle lifecycle) {
if (lifecycle.getApis().getPlatform() != null) {
String[] supportedVersions = lifecycle.getApis().getPlatform();
return ApiVersions.SUPPORTED_PLATFORMS.findLatestSupported(supportedVersions);
}
String version = lifecycle.getApi().getPlatform();
return ApiVersions.SUPPORTED_PLATFORMS.findLatestSupported(version);
}
/**
* Execute this lifecycle by running each phase in turn.
* @throws IOException on IO error
*/
void execute() throws IOException {
Assert.state(!this.executed, "Lifecycle has already been executed");
this.executed = true;
this.log.executingLifecycle(this.request, this.lifecycleVersion, this.buildCache);
if (this.request.isCleanCache()) {
deleteCache(this.buildCache);
}
if (this.request.isTrustBuilder()) {
run(createPhase());
}
else {
run(analyzePhase());
run(detectPhase());
if (!this.request.isCleanCache()) {
run(restorePhase());
}
else {
this.log.skippingPhase("restorer", "because 'cleanCache' is enabled");
}
run(buildPhase());
run(exportPhase());
}
this.log.executedLifecycle(this.request);
}
private Phase createPhase() {
Phase phase = new Phase("creator", isVerboseLogging());
phase.withApp(this.applicationDirectory,
Binding.from(getCacheBindingSource(this.application), this.applicationDirectory));
phase.withPlatform(Directory.PLATFORM);
ImageReference runImage = this.request.getRunImage();
Assert.state(runImage != null, "'runImage' must not be null");
phase.withRunImage(runImage);
phase.withLayers(Directory.LAYERS, Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS));
phase.withBuildCache(Directory.CACHE, Binding.from(getCacheBindingSource(this.buildCache), Directory.CACHE));
phase.withLaunchCache(Directory.LAUNCH_CACHE,
Binding.from(getCacheBindingSource(this.launchCache), Directory.LAUNCH_CACHE));
configureDaemonAccess(phase);
if (this.request.isCleanCache()) {
phase.withSkipRestore();
}
if (requiresProcessTypeDefault()) {
phase.withProcessType("web");
}
phase.withImageName(this.request.getName());
configureOptions(phase);
configureCreatedDate(phase);
return phase;
}
private Phase analyzePhase() {
Phase phase = new Phase("analyzer", isVerboseLogging());
configureDaemonAccess(phase);
phase.withLaunchCache(Directory.LAUNCH_CACHE,
Binding.from(getCacheBindingSource(this.launchCache), Directory.LAUNCH_CACHE));
phase.withLayers(Directory.LAYERS, Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS));
ImageReference runImage = this.request.getRunImage();
Assert.state(runImage != null, "'runImage' must not be null");
phase.withRunImage(runImage);
phase.withImageName(this.request.getName());
configureOptions(phase);
return phase;
}
private Phase detectPhase() {
Phase phase = new Phase("detector", isVerboseLogging());
phase.withApp(this.applicationDirectory,
Binding.from(getCacheBindingSource(this.application), this.applicationDirectory));
phase.withLayers(Directory.LAYERS, Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS));
phase.withPlatform(Directory.PLATFORM);
configureOptions(phase);
return phase;
}
private Phase restorePhase() {
Phase phase = new Phase("restorer", isVerboseLogging());
configureDaemonAccess(phase);
phase.withBuildCache(Directory.CACHE, Binding.from(getCacheBindingSource(this.buildCache), Directory.CACHE));
phase.withLayers(Directory.LAYERS, Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS));
configureOptions(phase);
return phase;
}
private Phase buildPhase() {
Phase phase = new Phase("builder", isVerboseLogging());
phase.withApp(this.applicationDirectory,
Binding.from(getCacheBindingSource(this.application), this.applicationDirectory));
phase.withLayers(Directory.LAYERS, Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS));
phase.withPlatform(Directory.PLATFORM);
configureOptions(phase);
return phase;
}
private Phase exportPhase() {
Phase phase = new Phase("exporter", isVerboseLogging());
configureDaemonAccess(phase);
phase.withApp(this.applicationDirectory,
Binding.from(getCacheBindingSource(this.application), this.applicationDirectory));
phase.withBuildCache(Directory.CACHE, Binding.from(getCacheBindingSource(this.buildCache), Directory.CACHE));
phase.withLaunchCache(Directory.LAUNCH_CACHE,
Binding.from(getCacheBindingSource(this.launchCache), Directory.LAUNCH_CACHE));
phase.withLayers(Directory.LAYERS, Binding.from(getCacheBindingSource(this.layers), Directory.LAYERS));
if (requiresProcessTypeDefault()) {
phase.withProcessType("web");
}
phase.withImageName(this.request.getName());
configureOptions(phase);
configureCreatedDate(phase);
return phase;
}
private Cache getLayersBindingSource(BuildRequest request) {
if (request.getBuildWorkspace() != null) {
return getBuildWorkspaceBindingSource(request.getBuildWorkspace(), "layers");
}
return createVolumeCache("pack-layers-");
}
private Cache getApplicationBindingSource(BuildRequest request) {
if (request.getBuildWorkspace() != null) {
return getBuildWorkspaceBindingSource(request.getBuildWorkspace(), "app");
}
return createVolumeCache("pack-app-");
}
private Cache getBuildWorkspaceBindingSource(Cache buildWorkspace, String suffix) {
if (buildWorkspace.getVolume() != null) {
return Cache.volume(buildWorkspace.getVolume().getName() + "-" + suffix);
}
Bind bind = buildWorkspace.getBind();
Assert.state(bind != null, "'bind' must not be null");
return Cache.bind(bind.getSource() + "-" + suffix);
}
private String getCacheBindingSource(Cache cache) {
if (cache.getVolume() != null) {
return cache.getVolume().getName();
}
Bind bind = cache.getBind();
Assert.state(bind != null, "'bind' must not be null");
return bind.getSource();
}
private Cache createVolumeCache(String prefix) {
return Cache.volume(createRandomVolumeName(prefix));
}
private Cache createVolumeCache(BuildRequest request, String suffix) {
return Cache.volume(
VolumeName.basedOn(request.getName(), ImageReference::toLegacyString, "pack-cache-", "." + suffix, 6));
}
protected VolumeName createRandomVolumeName(String prefix) {
return VolumeName.random(prefix);
}
private void configureDaemonAccess(Phase phase) {
phase.withDaemonAccess();
if (this.dockerHost != null) {
if (this.dockerHost.isRemote()) {
phase.withEnv("DOCKER_HOST", this.dockerHost.getAddress());
if (this.dockerHost.isSecure()) {
phase.withEnv("DOCKER_TLS_VERIFY", "1");
if (this.dockerHost.getCertificatePath() != null) {
phase.withEnv("DOCKER_CERT_PATH", this.dockerHost.getCertificatePath());
}
}
}
else {
phase.withBinding(Binding.from(this.dockerHost.getAddress(), DOMAIN_SOCKET_PATH));
}
}
else {
phase.withBinding(Binding.from(DOMAIN_SOCKET_PATH, DOMAIN_SOCKET_PATH));
}
if (this.securityOptions != null) {
this.securityOptions.forEach(phase::withSecurityOption);
}
}
private void configureCreatedDate(Phase phase) {
if (this.request.getCreatedDate() != null) {
phase.withEnv(SOURCE_DATE_EPOCH_KEY, Long.toString(this.request.getCreatedDate().getEpochSecond()));
}
}
private void configureOptions(Phase phase) {
if (this.request.getBindings() != null) {
this.request.getBindings().forEach(phase::withBinding);
}
if (this.request.getNetwork() != null) {
phase.withNetworkMode(this.request.getNetwork());
}
phase.withEnv(PLATFORM_API_VERSION_KEY, this.platformVersion.toString());
}
private boolean isVerboseLogging() {
return this.request.isVerboseLogging() && this.lifecycleVersion.isEqualOrGreaterThan(LOGGING_MINIMUM_VERSION);
}
private boolean requiresProcessTypeDefault() {
return this.platformVersion.supportsAny(ApiVersion.of(0, 4), ApiVersion.of(0, 5));
}
private void run(Phase phase) throws IOException {
Consumer<LogUpdateEvent> logConsumer = this.log.runningPhase(this.request, phase.getName());
ContainerConfig containerConfig = ContainerConfig.of(this.builder.getName(), phase::apply);
ContainerReference reference = createContainer(containerConfig, phase.requiresApp());
try {
this.docker.container().start(reference);
this.docker.container().logs(reference, logConsumer::accept);
ContainerStatus status = this.docker.container().wait(reference);
if (status.getStatusCode() != 0) {
throw new BuilderException(phase.getName(), status.getStatusCode());
}
}
finally {
this.docker.container().remove(reference, true);
}
}
private ContainerReference createContainer(ContainerConfig config, boolean requiresAppUpload) throws IOException {
if (!requiresAppUpload || this.applicationVolumePopulated) {
return this.docker.container().create(config, this.request.getImagePlatform());
}
try {
if (this.application.getBind() != null) {
Files.createDirectories(Path.of(this.application.getBind().getSource()));
}
TarArchive applicationContent = this.request.getApplicationContent(this.builder.getBuildOwner());
return this.docker.container()
.create(config, this.request.getImagePlatform(),
ContainerContent.of(applicationContent, this.applicationDirectory));
}
finally {
this.applicationVolumePopulated = true;
}
}
@Override
public void close() throws IOException {
deleteCache(this.layers);
deleteCache(this.application);
}
private void deleteCache(Cache cache) throws IOException {
if (cache.getVolume() != null) {
deleteVolume(cache.getVolume().getVolumeName());
}
if (cache.getBind() != null) {
deleteBind(cache.getBind());
}
}
private void deleteVolume(VolumeName name) throws IOException {
this.docker.volume().delete(name, true);
}
private void deleteBind(Cache.Bind bind) {
try {
FileSystemUtils.deleteRecursively(Path.of(bind.getSource()));
}
catch (Exception ex) {
this.log.failedCleaningWorkDir(bind, ex);
}
}
/**
* Common directories used by the various phases.
*/
private static final | Lifecycle |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/StreamOperatorUtils.java | {
"start": 1228,
"end": 1809
} | class ____ {
@VisibleForTesting
public static <OUT> void setupStreamOperator(
AbstractStreamOperator<OUT> operator,
StreamTask<?, ?> containingTask,
StreamConfig config,
Output<StreamRecord<OUT>> output) {
operator.setup(containingTask, config, output);
}
@VisibleForTesting
public static void setProcessingTimeService(
AbstractStreamOperator<?> operator, ProcessingTimeService processingTimeService) {
operator.setProcessingTimeService(processingTimeService);
}
}
| StreamOperatorUtils |
java | apache__maven | api/maven-api-cli/src/main/java/org/apache/maven/api/cli/InvokerException.java | {
"start": 1307,
"end": 2235
} | class ____ extends MavenException {
/**
* Constructs a new {@code InvokerException} with the specified detail message.
*
* @param message the detail message explaining the cause of the exception
*/
public InvokerException(@Nullable String message) {
super(message);
}
/**
* Constructs a new {@code InvokerException} with the specified detail message and cause.
*
* @param message the detail message explaining the cause of the exception
* @param cause the underlying cause of the exception
*/
public InvokerException(@Nullable String message, @Nullable Throwable cause) {
super(message, cause);
}
/**
* Exception for intentional exit: No message or anything will be displayed, just the
* carried exit code will be returned from invoker {@link Invoker#invoke(InvokerRequest)} method.
*/
public static final | InvokerException |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/origin/OriginTrackedValue.java | {
"start": 991,
"end": 2815
} | class ____ implements OriginProvider {
private final Object value;
private final @Nullable Origin origin;
private OriginTrackedValue(Object value, @Nullable Origin origin) {
this.value = value;
this.origin = origin;
}
/**
* Return the tracked value.
* @return the tracked value
*/
public Object getValue() {
return this.value;
}
@Override
public @Nullable Origin getOrigin() {
return this.origin;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
return ObjectUtils.nullSafeEquals(this.value, ((OriginTrackedValue) obj).value);
}
@Override
public int hashCode() {
return ObjectUtils.nullSafeHashCode(this.value);
}
@Override
public @Nullable String toString() {
return (this.value != null) ? this.value.toString() : null;
}
@Contract("!null -> !null")
public static @Nullable OriginTrackedValue of(@Nullable Object value) {
return of(value, null);
}
/**
* Create an {@link OriginTrackedValue} containing the specified {@code value} and
* {@code origin}. If the source value implements {@link CharSequence} then so will
* the resulting {@link OriginTrackedValue}.
* @param value the source value
* @param origin the origin
* @return an {@link OriginTrackedValue} or {@code null} if the source value was
* {@code null}.
*/
@Contract("null, _ -> null; !null, _ -> !null")
public static @Nullable OriginTrackedValue of(@Nullable Object value, @Nullable Origin origin) {
if (value == null) {
return null;
}
if (value instanceof CharSequence charSequence) {
return new OriginTrackedCharSequence(charSequence, origin);
}
return new OriginTrackedValue(value, origin);
}
/**
* {@link OriginTrackedValue} for a {@link CharSequence}.
*/
private static | OriginTrackedValue |
java | apache__camel | components/camel-micrometer-observability/src/test/java/org/apache/camel/micrometer/observability/MicrometerObservabilityTracerTestSupport.java | {
"start": 1267,
"end": 2834
} | class ____ extends ExchangeTestSupport {
protected SimpleTracer tracer = new SimpleTracer();
protected MicrometerObservabilityTracer tst = new MicrometerObservabilityTracer();
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getRegistry().bind("MicrometerObservabilityTracer", tracer);
CamelContextAware.trySetCamelContext(tst, context);
tst.init(context);
return context;
}
protected Map<String, MicrometerObservabilityTrace> traces() {
HashMap<String, MicrometerObservabilityTrace> map = new HashMap<>();
for (SimpleSpan span : tracer.getSpans()) {
String traceId = span.getTraceId();
MicrometerObservabilityTrace trace = map.get(traceId);
if (trace == null) {
trace = new MicrometerObservabilityTrace(traceId);
map.put(traceId, trace);
}
trace.add(span);
}
return map;
}
protected static SimpleSpan getSpan(List<SimpleSpan> trace, String uri, Op op) {
for (SimpleSpan span : trace) {
if (span.getTags().get("camel.uri") != null && span.getTags().get("camel.uri").equals(uri)) {
if (span.getTags().get(TagConstants.OP).equals(op.toString())) {
return span;
}
}
}
throw new IllegalArgumentException("Trying to get a non existing span!");
}
}
| MicrometerObservabilityTracerTestSupport |
java | elastic__elasticsearch | x-pack/plugin/eql/src/internalClusterTest/java/org/elasticsearch/xpack/eql/action/AbstractEqlIntegTestCase.java | {
"start": 616,
"end": 1446
} | class ____ extends ESIntegTestCase {
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
Settings.Builder settings = Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings));
settings.put(XPackSettings.SECURITY_ENABLED.getKey(), false);
settings.put(XPackSettings.WATCHER_ENABLED.getKey(), false);
settings.put(XPackSettings.GRAPH_ENABLED.getKey(), false);
settings.put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), false);
settings.put(LicenseSettings.SELF_GENERATED_LICENSE_TYPE.getKey(), "trial");
return settings.build();
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singletonList(LocalStateEQLXPackPlugin.class);
}
}
| AbstractEqlIntegTestCase |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StEnvelopeFromWKBGeoEvaluator.java | {
"start": 1191,
"end": 4712
} | class ____ extends AbstractConvertFunction.AbstractEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(StEnvelopeFromWKBGeoEvaluator.class);
private final EvalOperator.ExpressionEvaluator wkb;
public StEnvelopeFromWKBGeoEvaluator(Source source, EvalOperator.ExpressionEvaluator wkb,
DriverContext driverContext) {
super(driverContext, source);
this.wkb = wkb;
}
@Override
public EvalOperator.ExpressionEvaluator next() {
return wkb;
}
@Override
public Block evalVector(Vector v) {
BytesRefVector vector = (BytesRefVector) v;
int positionCount = v.getPositionCount();
BytesRef scratchPad = new BytesRef();
if (vector.isConstant()) {
try {
return driverContext.blockFactory().newConstantBytesRefBlockWith(evalValue(vector, 0, scratchPad), positionCount);
} catch (IllegalArgumentException e) {
registerException(e);
return driverContext.blockFactory().newConstantNullBlock(positionCount);
}
}
try (BytesRefBlock.Builder builder = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) {
for (int p = 0; p < positionCount; p++) {
try {
builder.appendBytesRef(evalValue(vector, p, scratchPad));
} catch (IllegalArgumentException e) {
registerException(e);
builder.appendNull();
}
}
return builder.build();
}
}
private BytesRef evalValue(BytesRefVector container, int index, BytesRef scratchPad) {
BytesRef value = container.getBytesRef(index, scratchPad);
return StEnvelope.fromWellKnownBinaryGeo(value);
}
@Override
public Block evalBlock(Block b) {
BytesRefBlock block = (BytesRefBlock) b;
int positionCount = block.getPositionCount();
try (BytesRefBlock.Builder builder = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) {
BytesRef scratchPad = new BytesRef();
for (int p = 0; p < positionCount; p++) {
int valueCount = block.getValueCount(p);
int start = block.getFirstValueIndex(p);
int end = start + valueCount;
boolean positionOpened = false;
boolean valuesAppended = false;
for (int i = start; i < end; i++) {
try {
BytesRef value = evalValue(block, i, scratchPad);
if (positionOpened == false && valueCount > 1) {
builder.beginPositionEntry();
positionOpened = true;
}
builder.appendBytesRef(value);
valuesAppended = true;
} catch (IllegalArgumentException e) {
registerException(e);
}
}
if (valuesAppended == false) {
builder.appendNull();
} else if (positionOpened) {
builder.endPositionEntry();
}
}
return builder.build();
}
}
private BytesRef evalValue(BytesRefBlock container, int index, BytesRef scratchPad) {
BytesRef value = container.getBytesRef(index, scratchPad);
return StEnvelope.fromWellKnownBinaryGeo(value);
}
@Override
public String toString() {
return "StEnvelopeFromWKBGeoEvaluator[" + "wkb=" + wkb + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(wkb);
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += wkb.baseRamBytesUsed();
return baseRamBytesUsed;
}
public static | StEnvelopeFromWKBGeoEvaluator |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/FaultFilter.java | {
"start": 7958,
"end": 8587
} | class ____ implements ClientInterceptor {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions,
final Channel next) {
boolean checkFault = false;
if (faultConfig.maxActiveFaults() == null
|| activeFaultCounter.get() < faultConfig.maxActiveFaults()) {
checkFault = faultConfig.faultDelay() != null || faultConfig.faultAbort() != null;
}
if (!checkFault) {
return next.newCall(method, callOptions);
}
final | FaultInjectionInterceptor |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/PositionOutOfRangeException.java | {
"start": 847,
"end": 1148
} | class ____ extends ApiException {
private static final long serialVersionUID = 1;
public PositionOutOfRangeException(String s) {
super(s);
}
public PositionOutOfRangeException(String message, Throwable cause) {
super(message, cause);
}
}
| PositionOutOfRangeException |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/parsing/PropertyEntryTests.java | {
"start": 889,
"end": 1369
} | class ____ {
@Test
void testCtorBailsOnNullPropertyNameArgument() {
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertyEntry(null));
}
@Test
void testCtorBailsOnEmptyPropertyNameArgument() {
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertyEntry(""));
}
@Test
void testCtorBailsOnWhitespacedPropertyNameArgument() {
assertThatIllegalArgumentException().isThrownBy(() ->
new PropertyEntry("\t "));
}
}
| PropertyEntryTests |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/InputStreamResponseTest.java | {
"start": 456,
"end": 818
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(RootResource.class));
@Test
public void test() {
when().get("/test").then().body(Matchers.is("Hello World"));
}
@Path("test")
public static | InputStreamResponseTest |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PackageDataFormatMojo.java | {
"start": 2956,
"end": 4823
} | class ____ extends AbstractGeneratorMojo {
/**
* The output directory for the generated data format resources
*/
@Parameter(defaultValue = "${project.basedir}/src/generated/resources")
protected File dataFormatOutDir;
/**
* The output directory for the generated data format java classes
*/
@Parameter(defaultValue = "${project.basedir}/src/generated/java")
protected File configurerSourceOutDir;
/**
* The output directory for the generated data format configurer resources
*/
@Parameter(defaultValue = "${project.basedir}/src/generated/resources")
protected File configurerResourceOutDir;
/**
* The output directory for the generated data format schema resources
*/
@Parameter(defaultValue = "${project.basedir}/src/generated/resources")
protected File schemaOutDir;
private final Map<String, Optional<JavaClassSource>> sources = new HashMap<>();
@Inject
public PackageDataFormatMojo(MavenProjectHelper projectHelper, BuildContext buildContext) {
super(projectHelper, buildContext);
}
PackageDataFormatMojo(Log log, MavenProject project, MavenProjectHelper projectHelper,
File dataFormatOutDir, File configurerSourceOutDir,
File configurerResourceOutDir, File schemaOutDir,
BuildContext buildContext) {
this(projectHelper, buildContext);
setLog(log);
this.project = project;
this.dataFormatOutDir = dataFormatOutDir;
this.configurerSourceOutDir = configurerSourceOutDir;
this.configurerResourceOutDir = configurerResourceOutDir;
this.schemaOutDir = schemaOutDir;
}
/**
* Execute goal.
*
* @throws org.apache.maven.plugin.MojoExecutionException execution of the main | PackageDataFormatMojo |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/TokenRenewer.java | {
"start": 1098,
"end": 1215
} | interface ____ plugins that handle tokens.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public abstract | for |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/request/target/NotificationTarget.java | {
"start": 868,
"end": 6805
} | class ____ extends CustomTarget<Bitmap> {
private final RemoteViews remoteViews;
private final Context context;
private final int notificationId;
private final String notificationTag;
private final Notification notification;
private final int viewId;
/**
* Constructor using a Notification object and a notificationId to get a handle on the
* Notification in order to update it that uses {@link #SIZE_ORIGINAL} as the target width and
* height.
*
* @param context Context to use in the AppWidgetManager initialization.
* @param viewId The id of the ImageView view that will load the image.
* @param remoteViews RemoteViews object which contains the ImageView that will load the bitmap.
* @param notification The Notification object that we want to update.
* @param notificationId The notificationId of the Notification that we want to load the Bitmap.
*/
@SuppressLint("InlinedApi")
// Alert users of Glide to have this permission.
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
public NotificationTarget(
Context context,
int viewId,
RemoteViews remoteViews,
Notification notification,
int notificationId) {
this(context, viewId, remoteViews, notification, notificationId, null);
}
/**
* Constructor using a Notification object, a notificationId, and a notificationTag to get a
* handle on the Notification in order to update it that uses {@link #SIZE_ORIGINAL} as the target
* width and height.
*
* @param context Context to use in the AppWidgetManager initialization.
* @param viewId The id of the ImageView view that will load the image.
* @param remoteViews RemoteViews object which contains the ImageView that will load the bitmap.
* @param notification The Notification object that we want to update.
* @param notificationId The notificationId of the Notification that we want to load the Bitmap.
* @param notificationTag The notificationTag of the Notification that we want to load the Bitmap.
* May be {@code null}.
*/
@SuppressLint("InlinedApi")
// Alert users of Glide to have this permission.
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
public NotificationTarget(
Context context,
int viewId,
RemoteViews remoteViews,
Notification notification,
int notificationId,
String notificationTag) {
this(
context,
SIZE_ORIGINAL,
SIZE_ORIGINAL,
viewId,
remoteViews,
notification,
notificationId,
notificationTag);
}
/**
* Constructor using a Notification object, a notificationId, and a notificationTag to get a
* handle on the Notification in order to update it.
*
* @param context Context to use in the AppWidgetManager initialization.
* @param width Desired width of the bitmap that will be loaded.(Need to be manually put because
* of RemoteViews limitations.)
* @param height Desired height of the bitmap that will be loaded. (Need to be manually put
* because of RemoteViews limitations.)
* @param viewId The id of the ImageView view that will load the image.
* @param remoteViews RemoteViews object which contains the ImageView that will load the bitmap.
* @param notification The Notification object that we want to update.
* @param notificationId The notificationId of the Notification that we want to load the Bitmap.
* @param notificationTag The notificationTag of the Notification that we want to load the Bitmap.
* May be {@code null}.
*/
@SuppressLint("InlinedApi")
// Alert users of Glide to have this permission.
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
public NotificationTarget(
Context context,
int width,
int height,
int viewId,
RemoteViews remoteViews,
Notification notification,
int notificationId,
String notificationTag) {
super(width, height);
this.context = Preconditions.checkNotNull(context, "Context must not be null!");
this.notification =
Preconditions.checkNotNull(notification, "Notification object can not be null!");
this.remoteViews =
Preconditions.checkNotNull(remoteViews, "RemoteViews object can not be null!");
this.viewId = viewId;
this.notificationId = notificationId;
this.notificationTag = notificationTag;
}
/** Updates the Notification after the Bitmap resource is loaded. */
@SuppressLint("InlinedApi")
// Help tools to recognize that this method requires a permission, because it posts a
// notification.
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
private void update() {
NotificationManager manager =
(NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
Preconditions.checkNotNull(manager)
.notify(this.notificationTag, this.notificationId, this.notification);
}
@SuppressLint("InlinedApi")
// Help tools to recognize that this method requires a permission, because it calls setBitmap().
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
@Override
public void onResourceReady(
@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
setBitmap(resource);
}
@SuppressLint("InlinedApi")
// Help tools to recognize that this method requires a permission, because it calls setBitmap().
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
setBitmap(null);
}
@SuppressLint("InlinedApi")
// Help tools to recognize that this method requires a permission, because it calls update().
@RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
private void setBitmap(@Nullable Bitmap bitmap) {
this.remoteViews.setImageViewBitmap(this.viewId, bitmap);
this.update();
}
}
| NotificationTarget |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/onetomany/ids/SetRefEdEmbIdEntity.java | {
"start": 482,
"end": 1926
} | class ____ {
@EmbeddedId
private EmbId id;
@Audited
private String data;
@Audited
@OneToMany(mappedBy = "reference")
private Set<SetRefIngEmbIdEntity> reffering;
public SetRefEdEmbIdEntity() {
}
public SetRefEdEmbIdEntity(EmbId id, String data) {
this.id = id;
this.data = data;
}
public SetRefEdEmbIdEntity(String data) {
this.data = data;
}
public EmbId getId() {
return id;
}
public void setId(EmbId id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Set<SetRefIngEmbIdEntity> getReffering() {
return reffering;
}
public void setReffering(Set<SetRefIngEmbIdEntity> reffering) {
this.reffering = reffering;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof SetRefEdEmbIdEntity) ) {
return false;
}
SetRefEdEmbIdEntity that = (SetRefEdEmbIdEntity) o;
if ( data != null ? !data.equals( that.getData() ) : that.getData() != null ) {
return false;
}
if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + (data != null ? data.hashCode() : 0);
return result;
}
public String toString() {
return "SetRefEdEmbIdEntity(id = " + id + ", data = " + data + ")";
}
}
| SetRefEdEmbIdEntity |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/search/aggregations/AggregatorTestCase.java | {
"start": 9983,
"end": 10205
} | class ____ testing {@link Aggregator} implementations.
* Provides helpers for constructing and searching an {@link Aggregator} implementation based on a provided
* {@link AggregationBuilder} instance.
*/
public abstract | for |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessor.java | {
"start": 17412,
"end": 17621
} | class ____ {
private final String passcode;
public StompPasscode(String passcode) {
this.passcode = passcode;
}
@Override
public String toString() {
return "[PROTECTED]";
}
}
}
| StompPasscode |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/object/SqlQuery.java | {
"start": 1557,
"end": 2439
} | class ____ a number of public {@code execute} methods that are
* analogous to the different convenient JDO query execute methods. Subclasses
* can either rely on one of these inherited methods, or can add their own
* custom execution methods, with meaningful names and typed parameters
* (definitely a best practice). Each custom query method will invoke one of
* this class's untyped query methods.
*
* <p>Like all {@code RdbmsOperation} classes that ship with the Spring
* Framework, {@code SqlQuery} instances are thread-safe after their
* initialization is complete. That is, after they are constructed and configured
* via their setter methods, they can be used safely from multiple threads.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Thomas Risberg
* @author Yanming Zhou
* @param <T> the result type
* @see SqlUpdate
*/
public abstract | provides |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenExchangeAuthenticationProviderTests.java | {
"start": 4398,
"end": 43004
} | class ____ {
private static final Set<String> RESOURCES = Set.of("https://mydomain.com/resource1",
"https://mydomain.com/resource2");
private static final Set<String> AUDIENCES = Set.of("audience1", "audience2");
private static final String SUBJECT_TOKEN = "EfYu_0jEL";
private static final String ACTOR_TOKEN = "JlNE_xR1f";
private static final String ACCESS_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:access_token";
private static final String JWT_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:jwt";
private OAuth2AuthorizationService authorizationService;
private OAuth2TokenGenerator<OAuth2Token> tokenGenerator;
private JwtEncoder dPoPProofJwtEncoder;
private OAuth2TokenExchangeAuthenticationProvider authenticationProvider;
@BeforeEach
@SuppressWarnings("unchecked")
public void setUp() {
this.authorizationService = mock(OAuth2AuthorizationService.class);
this.tokenGenerator = mock(OAuth2TokenGenerator.class);
JWKSet clientJwkSet = new JWKSet(TestJwks.DEFAULT_EC_JWK);
JWKSource<SecurityContext> clientJwkSource = (jwkSelector, securityContext) -> jwkSelector.select(clientJwkSet);
this.dPoPProofJwtEncoder = new NimbusJwtEncoder(clientJwkSource);
this.authenticationProvider = new OAuth2TokenExchangeAuthenticationProvider(this.authorizationService,
this.tokenGenerator);
mockAuthorizationServerContext();
}
@AfterEach
public void tearDown() {
AuthorizationServerContextHolder.resetContext();
}
@Test
public void constructorWhenAuthorizationServiceNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2TokenExchangeAuthenticationProvider(null, this.tokenGenerator))
.withMessage("authorizationService cannot be null");
// @formatter:on
}
@Test
public void constructorWhenTokenGeneratorNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2TokenExchangeAuthenticationProvider(this.authorizationService, null))
.withMessage("tokenGenerator cannot be null");
// @formatter:on
}
@Test
public void supportsWhenTypeOAuth2TokenExchangeAuthenticationTokenThenReturnTrue() {
assertThat(this.authenticationProvider.supports(OAuth2TokenExchangeAuthenticationToken.class)).isTrue();
}
@Test
public void authenticateWhenClientNotAuthenticatedThenThrowOAuth2AuthenticationException() {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken("client-1",
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null, null);
Authentication authentication = new OAuth2TokenExchangeAuthenticationToken(JWT_TOKEN_TYPE_VALUE, SUBJECT_TOKEN,
ACCESS_TOKEN_TYPE_VALUE, clientPrincipal, null, null, RESOURCES, AUDIENCES, null, null);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT);
// @formatter:on
}
@Test
public void authenticateWhenInvalidGrantTypeThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
// @formatter:on
}
@Test
public void authenticateWhenInvalidRequestedTokenTypeThenThrowOAuth2AuthenticationException() {
// @formatter:off
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.tokenSettings(TokenSettings.builder().accessTokenFormat(OAuth2TokenFormat.REFERENCE).build())
.build();
// @formatter:on
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
}
@Test
public void authenticateWhenSubjectTokenNotFoundThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(null);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenSubjectTokenNotActiveThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createExpiredAccessToken(SUBJECT_TOKEN))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenSubjectTokenTypeJwtAndSubjectTokenFormatReferenceThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createJwtRequest(registeredClient);
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN), withTokenFormat(OAuth2TokenFormat.REFERENCE))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenSubjectPrincipalNullThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
// @formatter:off
OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.attributes((attributes) -> attributes.remove(Principal.class.getName()))
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenActorTokenNotFoundThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, (OAuth2Authorization) null);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenActorTokenNotActiveThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.build();
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createExpiredAccessToken(ACTOR_TOKEN))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenActorTokenTypeJwtAndActorTokenFormatReferenceThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createJwtRequest(registeredClient);
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN), withTokenFormat(OAuth2TokenFormat.SELF_CONTAINED))
.build();
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(ACTOR_TOKEN), withTokenFormat(OAuth2TokenFormat.REFERENCE))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenMayActAndActorIssClaimNotAuthorizedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
Map<String, String> authorizedActorClaims = Map.of(OAuth2TokenClaimNames.ISS, "issuer",
OAuth2TokenClaimNames.SUB, "actor");
// @formatter:off
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN), withClaims(Map.of("may_act", authorizedActorClaims)))
.build();
// @formatter:on
Map<String, Object> actorTokenClaims = Map.of(OAuth2TokenClaimNames.ISS, "invalid-issuer",
OAuth2TokenClaimNames.SUB, "actor");
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(ACTOR_TOKEN), withClaims(actorTokenClaims))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenMayActAndActorSubClaimNotAuthorizedThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
Map<String, String> authorizedActorClaims = Map.of(OAuth2TokenClaimNames.ISS, "issuer",
OAuth2TokenClaimNames.SUB, "actor");
// @formatter:off
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN), withClaims(Map.of("may_act", authorizedActorClaims)))
.build();
// @formatter:on
Map<String, Object> actorTokenClaims = Map.of(OAuth2TokenClaimNames.ISS, "issuer", OAuth2TokenClaimNames.SUB,
"invalid-actor");
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(ACTOR_TOKEN), withClaims(actorTokenClaims))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenMayActAndImpersonationThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createImpersonationRequest(registeredClient);
Map<String, String> authorizedActorClaims = Map.of(OAuth2TokenClaimNames.ISS, "issuer",
OAuth2TokenClaimNames.SUB, "actor");
// @formatter:off
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN), withClaims(Map.of("may_act", authorizedActorClaims)))
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_GRANT);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenInvalidScopeInRequestThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient,
Set.of("invalid"));
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.build();
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(ACTOR_TOKEN))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenInvalidScopeInSubjectAuthorizationThenThrowOAuth2AuthenticationException() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient, Set.of());
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.authorizedScopes(Set.of("invalid"))
.build();
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(ACTOR_TOKEN))
.build();
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(authentication))
.extracting(OAuth2AuthenticationException::getError)
.extracting(OAuth2Error::getErrorCode)
.isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE);
// @formatter:on
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verifyNoMoreInteractions(this.authorizationService);
verifyNoInteractions(this.tokenGenerator);
}
@Test
public void authenticateWhenNoActorTokenAndValidTokenExchangeThenReturnAccessTokenForImpersonation() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put("dpop_proof", generateDPoPProof("http://localhost/oauth2/token"));
additionalParameters.put("dpop_method", "POST");
additionalParameters.put("dpop_target_uri", "http://localhost/oauth2/token");
OAuth2TokenExchangeAuthenticationToken authentication = new OAuth2TokenExchangeAuthenticationToken(
JWT_TOKEN_TYPE_VALUE, SUBJECT_TOKEN, ACCESS_TOKEN_TYPE_VALUE, clientPrincipal, null, null, RESOURCES,
AUDIENCES, registeredClient.getScopes(), additionalParameters);
TestingAuthenticationToken userPrincipal = new TestingAuthenticationToken("user", null, "ROLE_USER");
// @formatter:off
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.attribute(Principal.class.getName(), userPrincipal)
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization);
OAuth2AccessToken accessToken = createAccessToken("token-value");
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken);
OAuth2AccessTokenAuthenticationToken authenticationResult = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient);
assertThat(authenticationResult.getPrincipal()).isEqualTo(authentication.getPrincipal());
assertThat(authenticationResult.getAccessToken()).isEqualTo(accessToken);
assertThat(authenticationResult.getRefreshToken()).isNull();
assertThat(authenticationResult.getAdditionalParameters()).hasSize(1);
assertThat(authenticationResult.getAdditionalParameters().get(OAuth2ParameterNames.ISSUED_TOKEN_TYPE))
.isEqualTo(JWT_TOKEN_TYPE_VALUE);
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
ArgumentCaptor<OAuth2TokenContext> tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class);
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.tokenGenerator).generate(tokenContextCaptor.capture());
verify(this.authorizationService).save(authorizationCaptor.capture());
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
OAuth2TokenContext tokenContext = tokenContextCaptor.getValue();
assertThat(tokenContext.getRegisteredClient()).isEqualTo(registeredClient);
assertThat(tokenContext.getAuthorization()).isEqualTo(subjectAuthorization);
assertThat(tokenContext.<Authentication>getPrincipal()).isSameAs(userPrincipal);
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
assertThat(tokenContext.getAuthorizedScopes()).isEqualTo(authentication.getScopes());
assertThat(tokenContext.getTokenType()).isEqualTo(OAuth2TokenType.ACCESS_TOKEN);
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.TOKEN_EXCHANGE);
assertThat(tokenContext.<Jwt>get(OAuth2TokenContext.DPOP_PROOF_KEY)).isNotNull();
OAuth2Authorization authorization = authorizationCaptor.getValue();
assertThat(authorization.getPrincipalName()).isEqualTo(subjectAuthorization.getPrincipalName());
assertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.TOKEN_EXCHANGE);
assertThat(authorization.getAuthorizedScopes()).isEqualTo(authentication.getScopes());
assertThat(authorization.<Authentication>getAttribute(Principal.class.getName())).isSameAs(userPrincipal);
assertThat(authorization.getAccessToken().getToken()).isEqualTo(accessToken);
assertThat(authorization.getRefreshToken()).isNull();
}
@Test
public void authenticateWhenNoActorTokenAndPreviousActorThenReturnAccessTokenForImpersonation() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createImpersonationRequest(registeredClient);
TestingAuthenticationToken userPrincipal = new TestingAuthenticationToken("user", null, "ROLE_USER");
OAuth2TokenExchangeActor previousActor = new OAuth2TokenExchangeActor(
Map.of(OAuth2TokenClaimNames.ISS, "issuer1", OAuth2TokenClaimNames.SUB, "actor"));
OAuth2TokenExchangeCompositeAuthenticationToken subjectPrincipal = new OAuth2TokenExchangeCompositeAuthenticationToken(
userPrincipal, List.of(previousActor));
// @formatter:off
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN))
.attribute(Principal.class.getName(), subjectPrincipal)
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization);
OAuth2AccessToken accessToken = createAccessToken("token-value");
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken);
OAuth2AccessTokenAuthenticationToken authenticationResult = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient);
assertThat(authenticationResult.getPrincipal()).isEqualTo(authentication.getPrincipal());
assertThat(authenticationResult.getAccessToken()).isEqualTo(accessToken);
assertThat(authenticationResult.getRefreshToken()).isNull();
assertThat(authenticationResult.getAdditionalParameters()).hasSize(1);
assertThat(authenticationResult.getAdditionalParameters().get(OAuth2ParameterNames.ISSUED_TOKEN_TYPE))
.isEqualTo(JWT_TOKEN_TYPE_VALUE);
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
ArgumentCaptor<OAuth2TokenContext> tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class);
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.tokenGenerator).generate(tokenContextCaptor.capture());
verify(this.authorizationService).save(authorizationCaptor.capture());
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
OAuth2TokenContext tokenContext = tokenContextCaptor.getValue();
assertThat(tokenContext.getRegisteredClient()).isEqualTo(registeredClient);
assertThat(tokenContext.getAuthorization()).isEqualTo(subjectAuthorization);
assertThat(tokenContext.<Authentication>getPrincipal()).isSameAs(userPrincipal);
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
assertThat(tokenContext.getAuthorizedScopes()).isEqualTo(authentication.getScopes());
assertThat(tokenContext.getTokenType()).isEqualTo(OAuth2TokenType.ACCESS_TOKEN);
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.TOKEN_EXCHANGE);
OAuth2Authorization authorization = authorizationCaptor.getValue();
assertThat(authorization.getPrincipalName()).isEqualTo(subjectAuthorization.getPrincipalName());
assertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.TOKEN_EXCHANGE);
assertThat(authorization.getAuthorizedScopes()).isEqualTo(authentication.getScopes());
assertThat(authorization.<Authentication>getAttribute(Principal.class.getName())).isSameAs(userPrincipal);
assertThat(authorization.getAccessToken().getToken()).isEqualTo(accessToken);
assertThat(authorization.getRefreshToken()).isNull();
}
@Test
public void authenticateWhenActorTokenAndValidTokenExchangeThenReturnAccessTokenForDelegation() {
RegisteredClient registeredClient = TestRegisteredClients.registeredClient()
.authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE)
.build();
OAuth2TokenExchangeAuthenticationToken authentication = createDelegationRequest(registeredClient);
TestingAuthenticationToken userPrincipal = new TestingAuthenticationToken("user", null, "ROLE_USER");
OAuth2TokenExchangeActor actor1 = new OAuth2TokenExchangeActor(
Map.of(OAuth2TokenClaimNames.ISS, "issuer1", OAuth2TokenClaimNames.SUB, "actor1"));
OAuth2TokenExchangeActor actor2 = new OAuth2TokenExchangeActor(
Map.of(OAuth2TokenClaimNames.ISS, "issuer2", OAuth2TokenClaimNames.SUB, "actor2"));
OAuth2TokenExchangeCompositeAuthenticationToken subjectPrincipal = new OAuth2TokenExchangeCompositeAuthenticationToken(
userPrincipal, List.of(actor1));
// @formatter:off
OAuth2Authorization subjectAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.token(createAccessToken(SUBJECT_TOKEN), withClaims(Map.of("may_act", actor2.getClaims())))
.attribute(Principal.class.getName(), subjectPrincipal)
.build();
OAuth2Authorization actorAuthorization = TestOAuth2Authorizations.authorization(registeredClient)
.principalName(actor2.getSubject())
.token(createAccessToken(ACTOR_TOKEN), withClaims(actor2.getClaims()))
.build();
// @formatter:on
given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class)))
.willReturn(subjectAuthorization, actorAuthorization);
OAuth2AccessToken accessToken = createAccessToken("token-value");
given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken);
OAuth2AccessTokenAuthenticationToken authenticationResult = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider
.authenticate(authentication);
assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient);
assertThat(authenticationResult.getPrincipal()).isEqualTo(authentication.getPrincipal());
assertThat(authenticationResult.getAccessToken()).isEqualTo(accessToken);
assertThat(authenticationResult.getRefreshToken()).isNull();
assertThat(authenticationResult.getAdditionalParameters()).hasSize(1);
assertThat(authenticationResult.getAdditionalParameters().get(OAuth2ParameterNames.ISSUED_TOKEN_TYPE))
.isEqualTo(JWT_TOKEN_TYPE_VALUE);
ArgumentCaptor<OAuth2Authorization> authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class);
ArgumentCaptor<OAuth2TokenContext> tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class);
verify(this.authorizationService).findByToken(SUBJECT_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.authorizationService).findByToken(ACTOR_TOKEN, OAuth2TokenType.ACCESS_TOKEN);
verify(this.tokenGenerator).generate(tokenContextCaptor.capture());
verify(this.authorizationService).save(authorizationCaptor.capture());
verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator);
OAuth2TokenContext tokenContext = tokenContextCaptor.getValue();
assertThat(tokenContext.getRegisteredClient()).isEqualTo(registeredClient);
assertThat(tokenContext.getAuthorization()).isEqualTo(subjectAuthorization);
assertThat(tokenContext.getAuthorizationServerContext()).isNotNull();
assertThat(tokenContext.getAuthorizedScopes()).isEqualTo(authentication.getScopes());
assertThat(tokenContext.getTokenType()).isEqualTo(OAuth2TokenType.ACCESS_TOKEN);
assertThat(tokenContext.<Authentication>getAuthorizationGrant()).isEqualTo(authentication);
assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.TOKEN_EXCHANGE);
OAuth2TokenExchangeCompositeAuthenticationToken tokenContextPrincipal = tokenContext.getPrincipal();
assertThat(tokenContextPrincipal.getSubject()).isSameAs(subjectPrincipal.getSubject());
assertThat(tokenContextPrincipal.getActors()).containsExactly(actor2, actor1);
OAuth2Authorization authorization = authorizationCaptor.getValue();
assertThat(authorization.getPrincipalName()).isEqualTo(subjectAuthorization.getPrincipalName());
assertThat(authorization.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.TOKEN_EXCHANGE);
assertThat(authorization.getAuthorizedScopes()).isEqualTo(authentication.getScopes());
assertThat(authorization.getAccessToken().getToken()).isEqualTo(accessToken);
assertThat(authorization.getRefreshToken()).isNull();
OAuth2TokenExchangeCompositeAuthenticationToken authorizationPrincipal = authorization
.getAttribute(Principal.class.getName());
assertThat(authorizationPrincipal).isNotNull();
assertThat(authorizationPrincipal.getSubject()).isSameAs(subjectPrincipal.getSubject());
assertThat(authorizationPrincipal.getActors()).containsExactly(actor2, actor1);
}
private static void mockAuthorizationServerContext() {
AuthorizationServerSettings authorizationServerSettings = AuthorizationServerSettings.builder().build();
TestAuthorizationServerContext authorizationServerContext = new TestAuthorizationServerContext(
authorizationServerSettings, () -> "https://provider.com");
AuthorizationServerContextHolder.setContext(authorizationServerContext);
}
private static OAuth2TokenExchangeAuthenticationToken createDelegationRequest(RegisteredClient registeredClient) {
return createDelegationRequest(registeredClient, registeredClient.getScopes());
}
private static OAuth2TokenExchangeAuthenticationToken createDelegationRequest(RegisteredClient registeredClient,
Set<String> requestedScopes) {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
return new OAuth2TokenExchangeAuthenticationToken(JWT_TOKEN_TYPE_VALUE, SUBJECT_TOKEN, ACCESS_TOKEN_TYPE_VALUE,
clientPrincipal, ACTOR_TOKEN, ACCESS_TOKEN_TYPE_VALUE, RESOURCES, AUDIENCES, requestedScopes, null);
}
private static OAuth2TokenExchangeAuthenticationToken createImpersonationRequest(
RegisteredClient registeredClient) {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
return new OAuth2TokenExchangeAuthenticationToken(JWT_TOKEN_TYPE_VALUE, SUBJECT_TOKEN, ACCESS_TOKEN_TYPE_VALUE,
clientPrincipal, null, null, RESOURCES, AUDIENCES, registeredClient.getScopes(), null);
}
private static OAuth2TokenExchangeAuthenticationToken createJwtRequest(RegisteredClient registeredClient) {
OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient,
ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
return new OAuth2TokenExchangeAuthenticationToken(JWT_TOKEN_TYPE_VALUE, SUBJECT_TOKEN, JWT_TOKEN_TYPE_VALUE,
clientPrincipal, ACTOR_TOKEN, JWT_TOKEN_TYPE_VALUE, RESOURCES, AUDIENCES, registeredClient.getScopes(),
null);
}
private static OAuth2AccessToken createAccessToken(String tokenValue) {
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(30, ChronoUnit.MINUTES);
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, tokenValue, issuedAt, expiresAt);
}
private static OAuth2AccessToken createExpiredAccessToken(String tokenValue) {
Instant issuedAt = Instant.now().minus(45, ChronoUnit.MINUTES);
Instant expiresAt = issuedAt.plus(30, ChronoUnit.MINUTES);
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, tokenValue, issuedAt, expiresAt);
}
private static Consumer<Map<String, Object>> withClaims(Map<String, Object> claims) {
return (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, claims);
}
private static Consumer<Map<String, Object>> withTokenFormat(OAuth2TokenFormat tokenFormat) {
return (metadata) -> metadata.put(OAuth2TokenFormat.class.getName(), tokenFormat.getValue());
}
private String generateDPoPProof(String tokenEndpointUri) {
// @formatter:off
Map<String, Object> publicJwk = TestJwks.DEFAULT_EC_JWK
.toPublicJWK()
.toJSONObject();
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.ES256)
.type("dpop+jwt")
.jwk(publicJwk)
.build();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(Instant.now())
.claim("htm", "POST")
.claim("htu", tokenEndpointUri)
.id(UUID.randomUUID().toString())
.build();
// @formatter:on
Jwt jwt = this.dPoPProofJwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims));
return jwt.getTokenValue();
}
}
| OAuth2TokenExchangeAuthenticationProviderTests |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/junitrule/MockitoJUnitTestRuleTest.java | {
"start": 441,
"end": 1026
} | class ____ {
@Rule public MockitoTestRule mockitoRule = MockitoJUnit.testRule(this);
// Fixes #1578: Protect against multiple execution.
@Rule public MockitoTestRule mockitoRule2 = mockitoRule;
@Mock private Injected injected;
@InjectMocks private InjectInto injectInto;
@Test
public void testInjectMocks() throws Exception {
assertNotNull("Mock created", injected);
assertNotNull("Object created", injectInto);
assertEquals("A injected into B", injected, injectInto.getInjected());
}
public static | MockitoJUnitTestRuleTest |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/base/DaggerSuperficialValidation.java | {
"start": 23468,
"end": 23632
} | class ____ extends RuntimeException {
/** A {@link ValidationException} that originated from an unexpected exception. */
public static final | ValidationException |
java | alibaba__nacos | naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceQueryRequestHandler.java | {
"start": 1907,
"end": 3515
} | class ____ extends RequestHandler<ServiceQueryRequest, QueryServiceResponse> {
private final ServiceStorage serviceStorage;
private final NamingMetadataManager metadataManager;
public ServiceQueryRequestHandler(ServiceStorage serviceStorage, NamingMetadataManager metadataManager) {
this.serviceStorage = serviceStorage;
this.metadataManager = metadataManager;
}
@Override
@NamespaceValidation
@TpsControl(pointName = "RemoteNamingServiceQuery", name = "RemoteNamingServiceQuery")
@Secured(action = ActionTypes.READ)
@ExtractorManager.Extractor(rpcExtractor = ServiceQueryRequestParamExtractor.class)
public QueryServiceResponse handle(ServiceQueryRequest request, RequestMeta meta) throws NacosException {
String namespaceId = request.getNamespace();
String groupName = request.getGroupName();
String serviceName = request.getServiceName();
Service service = Service.newService(namespaceId, groupName, serviceName);
String cluster = null == request.getCluster() ? "" : request.getCluster();
boolean healthyOnly = request.isHealthyOnly();
ServiceInfo result = serviceStorage.getData(service);
ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(service).orElse(null);
result = ServiceUtil.selectInstancesWithHealthyProtection(result, serviceMetadata, cluster, healthyOnly, true,
NamingRequestUtil.getSourceIpForGrpcRequest(meta));
return QueryServiceResponse.buildSuccessResponse(result);
}
}
| ServiceQueryRequestHandler |
java | grpc__grpc-java | xds/src/main/java/io/grpc/xds/internal/rbac/engine/GrpcAuthorizationEngine.java | {
"start": 3104,
"end": 3349
} | enum ____ {
ALLOW,
DENY,
}
/**
* An authorization decision provides information about the decision type and the policy name
* identifier based on the authorization engine evaluation. */
@AutoValue
public abstract static | Action |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest24.java | {
"start": 1017,
"end": 3148
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"select /*+ no_parallel_index(t, \"HT_TASK_TRADE_HIS_GOR_IND \") dbms_stats cursor_sharing_exact use_weak_name_resl dynamic_sampling(0) no_monitoring no_expand index_ffs(t, \"HT_TASK_TRADE_HIS_GOR_IND \") */ count(*) as nrw,count(distinct sys_op_lbid(196675,'L',t.rowid)) as nlb,count(distinct hextoraw(sys_op_descend( \"GMT_MODIFIED \")||sys_op_descend( \"OWNER \")||sys_op_descend( \"RECORD_TYPE \"))) as ndk,sys_op_countchg(substrb(t.rowid,1,15),1) as clf from \"ESCROW\". \"HT_TASK_TRADE_HISTORY\" sample block ( 34.6426417370,1) t where \"GMT_MODIFIED \" is not null or \"OWNER \" is not null or \"RECORD_TYPE \" is not null";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
String output = SQLUtils.toOracleString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
System.out.println(output);
assertEquals(1, statementList.size());
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("ESCROW.HT_TASK_TRADE_HISTORY")));
assertEquals(5, visitor.getColumns().size());
// assertTrue(visitor.getColumns().contains(new TableStat.Column("ESCROW.HT_TASK_TRADE_HISTORY", "*")));
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR")));
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode")));
}
}
| OracleSelectTest24 |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java | {
"start": 1755,
"end": 2444
} | class ____ setting up a {@link java.util.concurrent.ExecutorService}
* (typically a {@link java.util.concurrent.ThreadPoolExecutor} or
* {@link java.util.concurrent.ScheduledThreadPoolExecutor}).
*
* <p>Defines common configuration settings and common lifecycle handling,
* inheriting thread customization options (name, priority, etc) from
* {@link org.springframework.util.CustomizableThreadCreator}.
*
* @author Juergen Hoeller
* @since 3.0
* @see java.util.concurrent.ExecutorService
* @see java.util.concurrent.Executors
* @see java.util.concurrent.ThreadPoolExecutor
* @see java.util.concurrent.ScheduledThreadPoolExecutor
*/
@SuppressWarnings("serial")
public abstract | for |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/SplitIteratorNullTest.java | {
"start": 1920,
"end": 2872
} | class ____ implements Iterator<String> {
private int count = 4;
private boolean nullReturned;
@Override
public boolean hasNext() {
// we return true one extra time, and cause next to return null
return count > 0;
}
@Override
public String next() {
count--;
if (count == 0) {
nullReturned = true;
return null;
} else if (count == 1) {
return "C";
} else if (count == 2) {
return "B";
} else {
return "A";
}
}
public boolean isNullReturned() {
return nullReturned;
}
@Override
public void remove() {
// noop
}
@Override
public void forEachRemaining(Consumer<? super String> action) {
// noop
}
}
}
| MyIterator |
java | elastic__elasticsearch | x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/MatchProcessor.java | {
"start": 542,
"end": 1382
} | class ____ extends AbstractEnrichProcessor {
MatchProcessor(
String tag,
String description,
EnrichProcessorFactory.SearchRunner searchRunner,
String policyName,
TemplateScript.Factory field,
TemplateScript.Factory targetField,
boolean overrideEnabled,
boolean ignoreMissing,
String matchField,
int maxMatches
) {
super(tag, description, searchRunner, policyName, field, targetField, ignoreMissing, overrideEnabled, matchField, maxMatches);
}
@Override
public QueryBuilder getQueryBuilder(Object fieldValue) {
if (fieldValue instanceof List<?> list) {
return new TermsQueryBuilder(matchField, list);
} else {
return new TermQueryBuilder(matchField, fieldValue);
}
}
}
| MatchProcessor |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ZoneReencryptionStatus.java | {
"start": 1183,
"end": 1264
} | class ____ {
/**
* State of re-encryption.
*/
public | ZoneReencryptionStatus |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/RestrictedTrustManager.java | {
"start": 2086,
"end": 10314
} | class ____ extends X509ExtendedTrustManager {
private static final Logger logger = LogManager.getLogger(RestrictedTrustManager.class);
private static final String CN_OID = "2.5.4.3";
private static final int SAN_CODE_OTHERNAME = 0;
private static final int SAN_CODE_DNS = 2;
private final X509ExtendedTrustManager delegate;
private final CertificateTrustRestrictions trustRestrictions;
private final Set<X509Field> x509Fields;
public RestrictedTrustManager(X509ExtendedTrustManager delegate, CertificateTrustRestrictions restrictions, Set<X509Field> x509Fields) {
this.delegate = delegate;
this.trustRestrictions = restrictions;
this.x509Fields = x509Fields;
logger.debug("Configured with trust restrictions: [{}]", restrictions);
logger.debug("Configured with x509 fields: [{}]", x509Fields);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
delegate.checkClientTrusted(chain, authType, socket);
verifyTrust(chain);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
delegate.checkServerTrusted(chain, authType, socket);
verifyTrust(chain);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
delegate.checkClientTrusted(chain, authType, engine);
verifyTrust(chain);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
delegate.checkServerTrusted(chain, authType, engine);
verifyTrust(chain);
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
delegate.checkClientTrusted(chain, authType);
verifyTrust(chain);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
delegate.checkServerTrusted(chain, authType);
verifyTrust(chain);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return delegate.getAcceptedIssuers();
}
private void verifyTrust(X509Certificate[] chain) throws CertificateException {
if (chain.length == 0) {
throw new CertificateException("No certificate presented");
}
final X509Certificate certificate = chain[0];
Set<String> values = readX509Certificate(certificate);
if (verifyCertificateNames(values)) {
logger.debug(
() -> format(
"Trusting certificate [%s] [%s] with fields [%s] with values [%s]",
certificate.getSubjectX500Principal(),
certificate.getSerialNumber().toString(16),
x509Fields,
values
)
);
} else {
logger.info(
"Rejecting certificate [{}] [{}] for fields [{}] with values [{}]",
certificate.getSubjectX500Principal(),
certificate.getSerialNumber().toString(16),
x509Fields,
values
);
throw new CertificateException(
"Certificate for "
+ certificate.getSubjectX500Principal()
+ " with fields "
+ x509Fields
+ " with values "
+ values
+ " does not match the trusted names "
+ trustRestrictions.getTrustedNames()
);
}
}
private boolean verifyCertificateNames(Set<String> names) {
for (Predicate<String> trust : trustRestrictions.getTrustedNames()) {
final Optional<String> match = names.stream().filter(trust).findFirst();
if (match.isPresent()) {
logger.debug("Name [{}] matches trusted pattern [{}]", match.get(), trust);
return true;
}
}
return false;
}
private Set<String> readX509Certificate(X509Certificate certificate) throws CertificateParsingException {
Collection<List<?>> sans = getSubjectAlternativeNames(certificate);
Set<String> values = new HashSet<>();
if (x509Fields.contains(X509Field.SAN_DNS)) {
Set<String> dnsNames = sans.stream()
.filter(pair -> ((Integer) pair.get(0)).intValue() == SAN_CODE_DNS)
.map(pair -> pair.get(1))
.map(Object::toString)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
values.addAll(dnsNames);
}
if (x509Fields.contains(X509Field.SAN_OTHERNAME_COMMONNAME)) {
Set<String> otherNames = sans.stream()
.filter(pair -> ((Integer) pair.get(0)).intValue() == SAN_CODE_OTHERNAME)
.map(pair -> pair.get(1))
.map(value -> decodeDerValue((byte[]) value, certificate))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
values.addAll(otherNames);
}
return values;
}
/**
* Decodes the otherName CN from the certificate
*
* @param value The DER Encoded Subject Alternative Name
* @param certificate The certificate
* @return the CN or null if it could not be parsed
*/
private static String decodeDerValue(byte[] value, X509Certificate certificate) {
try {
DerParser parser = new DerParser(value);
DerParser.Asn1Object seq = parser.readAsn1Object();
parser = seq.getParser();
String id = parser.readAsn1Object().getOid();
if (CN_OID.equals(id)) {
// Get the DER object with explicit 0 tag
DerParser.Asn1Object cnObject = parser.readAsn1Object();
parser = cnObject.getParser();
// The JRE's handling of OtherNames is buggy.
// The internal sun classes go to a lot of trouble to parse the GeneralNames into real object
// And then java.security.cert.X509Certificate just turns them back into bytes
// But in doing so, it ends up wrapping the "other name" bytes with a second tag
// Specifically: sun.security.x509.OtherName(DerValue) never decodes the tagged "nameValue"
// But: sun.security.x509.OtherName.encode() wraps the nameValue in a DER Tag.
// So, there's a good chance that our tagged nameValue contains... a tagged name value.
DerParser.Asn1Object innerObject = parser.readAsn1Object();
if (innerObject.isConstructed()) {
innerObject = innerObject.getParser().readAsn1Object();
}
logger.trace("Read innermost ASN.1 Object with type code [{}]", innerObject.getType());
String cn = innerObject.getString();
logger.trace("Read cn [{}] from ASN1Sequence [{}]", cn, seq);
return cn;
} else {
logger.debug(
"Certificate [{}] has 'otherName' [{}] with unsupported object-id [{}]",
certificate.getSubjectX500Principal(),
seq,
id
);
return null;
}
} catch (IOException e) {
logger.warn("Failed to read 'otherName' from certificate [{}]", certificate.getSubjectX500Principal());
return null;
}
}
private static Collection<List<?>> getSubjectAlternativeNames(X509Certificate certificate) throws CertificateParsingException {
final Collection<List<?>> sans = certificate.getSubjectAlternativeNames();
logger.trace("Certificate [{}] has subject alternative names [{}]", certificate.getSubjectX500Principal(), sans);
return sans == null ? Collections.emptyList() : sans;
}
}
| RestrictedTrustManager |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AndLobTest.java | {
"start": 2204,
"end": 2333
} | class ____ {
@Id
private Integer id;
@Lob
@Convert(converter = ConverterImpl.class)
private String status;
}
}
| EntityImpl |
java | micronaut-projects__micronaut-core | router/src/main/java/io/micronaut/web/router/DefaultErrorRouteInfo.java | {
"start": 1408,
"end": 4654
} | class ____<T, R> extends DefaultRequestMatcher<T, R> implements ErrorRouteInfo<T, R> {
@Nullable
private final Class<?> originatingType;
private final Class<? extends Throwable> exceptionType;
private final ConversionService conversionService;
public DefaultErrorRouteInfo(@Nullable Class<?> originatingType,
Class<? extends Throwable> exceptionType,
MethodExecutionHandle<T, R> targetMethod,
@Nullable
String bodyArgumentName,
@Nullable
Argument<?> bodyArgument,
List<MediaType> consumesMediaTypes,
List<MediaType> producesMediaTypes,
List<Predicate<HttpRequest<?>>> predicates,
ConversionService conversionService,
MessageBodyHandlerRegistry messageBodyHandlerRegistry) {
super(targetMethod, bodyArgument, bodyArgumentName, consumesMediaTypes, producesMediaTypes, true, true, predicates, messageBodyHandlerRegistry);
this.originatingType = originatingType;
this.exceptionType = exceptionType;
this.conversionService = conversionService;
}
@Override
public Class<?> originatingType() {
return originatingType;
}
@Override
public Class<? extends Throwable> exceptionType() {
return exceptionType;
}
@Override
public Optional<RouteMatch<R>> match(Class<?> originatingClass, Throwable exception) {
if (originatingClass == originatingType && exceptionType.isInstance(exception)) {
return Optional.of(new ErrorRouteMatch<>(exception, this, conversionService));
}
return Optional.empty();
}
@Override
public Optional<RouteMatch<R>> match(Throwable exception) {
if (originatingType == null && exceptionType.isInstance(exception)) {
return Optional.of(new ErrorRouteMatch<>(exception, this, conversionService));
}
return Optional.empty();
}
@Override
@NonNull
public HttpStatus findStatus(HttpStatus defaultStatus) {
return super.findStatus(defaultStatus == null ? HttpStatus.INTERNAL_SERVER_ERROR : defaultStatus);
}
@Override
public int hashCode() {
return ObjectUtils.hash(super.hashCode(), exceptionType, originatingType);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
DefaultErrorRouteInfo that = (DefaultErrorRouteInfo) o;
return exceptionType.equals(that.exceptionType) &&
Objects.equals(originatingType, that.originatingType);
}
@Override
public String toString() {
return ' ' + exceptionType.getSimpleName()
+ " -> " + getTargetMethod().getDeclaringType().getSimpleName()
+ '#' + getTargetMethod();
}
}
| DefaultErrorRouteInfo |
java | apache__camel | components/camel-google/camel-google-drive/src/generated/java/org/apache/camel/component/google/drive/internal/DriveRepliesApiMethod.java | {
"start": 660,
"end": 2754
} | enum ____ implements ApiMethod {
CREATE(
com.google.api.services.drive.Drive.Replies.Create.class,
"create",
arg("fileId", String.class),
arg("commentId", String.class),
arg("content", com.google.api.services.drive.model.Reply.class)),
DELETE(
com.google.api.services.drive.Drive.Replies.Delete.class,
"delete",
arg("fileId", String.class),
arg("commentId", String.class),
arg("replyId", String.class)),
GET(
com.google.api.services.drive.Drive.Replies.Get.class,
"get",
arg("fileId", String.class),
arg("commentId", String.class),
arg("replyId", String.class),
setter("includeDeleted", Boolean.class)),
LIST(
com.google.api.services.drive.Drive.Replies.List.class,
"list",
arg("fileId", String.class),
arg("commentId", String.class),
setter("includeDeleted", Boolean.class),
setter("pageSize", Integer.class),
setter("pageToken", String.class)),
UPDATE(
com.google.api.services.drive.Drive.Replies.Update.class,
"update",
arg("fileId", String.class),
arg("commentId", String.class),
arg("replyId", String.class),
arg("content", com.google.api.services.drive.model.Reply.class));
private final ApiMethod apiMethod;
DriveRepliesApiMethod(Class<?> resultType, String name, ApiMethodArg... args) {
this.apiMethod = new ApiMethodImpl(Replies.class, resultType, name, args);
}
@Override
public String getName() { return apiMethod.getName(); }
@Override
public Class<?> getResultType() { return apiMethod.getResultType(); }
@Override
public List<String> getArgNames() { return apiMethod.getArgNames(); }
@Override
public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); }
@Override
public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); }
@Override
public Method getMethod() { return apiMethod.getMethod(); }
}
| DriveRepliesApiMethod |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_dubbo_long.java | {
"start": 194,
"end": 468
} | class ____ extends TestCase {
public void test_0() throws Exception {
Long val = 2345L;
String text = JSON.toJSONString(val, SerializerFeature.WriteClassName);
Assert.assertEquals(val, JSON.parseObject(text, long.class));
}
}
| Bug_for_dubbo_long |
java | quarkusio__quarkus | independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartGenerationTest.java | {
"start": 961,
"end": 3284
} | class ____ {
private static final Path testDirPath = Paths.get("target/jbang-codestart-gen-test");
@BeforeAll
static void setUp() throws IOException {
SnapshotTesting.deleteTestDirectory(testDirPath.toFile());
}
@Test
void generateDefaultProject(TestInfo testInfo) throws Throwable {
final QuarkusJBangCodestartProjectInput input = QuarkusJBangCodestartProjectInput.builder()
.putData(QUARKUS_BOM_GROUP_ID, "io.quarkus")
.putData(QUARKUS_BOM_ARTIFACT_ID, "quarkus-bom")
.putData(QUARKUS_BOM_VERSION, "999-MOCK")
// define the version here as it is now autodetecting the best LTS version at runtime
// and we want a static version for the snapshots
.addData(NestedMaps.unflatten(Map.of("java.version", "11")))
.build();
final Path projectDir = testDirPath.resolve("default");
getCatalog().createProject(input).generate(projectDir);
assertThatDirectoryTreeMatchSnapshots(testInfo, projectDir);
assertThatMatchSnapshot(testInfo, projectDir, "src/main.java");
}
@Test
void generatePicocliProject(TestInfo testInfo) throws Throwable {
final QuarkusJBangCodestartProjectInput input = QuarkusJBangCodestartProjectInput.builder()
.addCodestart("jbang-picocli-code")
.putData(QUARKUS_BOM_GROUP_ID, "io.quarkus")
.putData(QUARKUS_BOM_ARTIFACT_ID, "quarkus-bom")
.putData(QUARKUS_BOM_VERSION, "999-MOCK")
// define the version here as it is now autodetecting the best LTS version at runtime
// and we want a static version for the snapshots
.addData(NestedMaps.unflatten(Map.of("java.version", "11")))
.build();
final Path projectDir = testDirPath.resolve("picocli");
getCatalog().createProject(input).generate(projectDir);
assertThatDirectoryTreeMatchSnapshots(testInfo, projectDir);
assertThatMatchSnapshot(testInfo, projectDir, "src/main.java");
}
private QuarkusJBangCodestartCatalog getCatalog() throws IOException {
return QuarkusJBangCodestartCatalog.fromBaseCodestartsResources(MessageWriter.info());
}
}
| QuarkusJBangCodestartGenerationTest |
java | spring-projects__spring-framework | spring-webmvc/src/main/java/org/springframework/web/servlet/resource/EncodedResourceResolver.java | {
"start": 2049,
"end": 6282
} | class ____ extends AbstractResourceResolver {
/**
* The default content codings.
*/
public static final List<String> DEFAULT_CODINGS = Arrays.asList("br", "gzip");
private final List<String> contentCodings = new ArrayList<>(DEFAULT_CODINGS);
private final Map<String, String> extensions = new LinkedHashMap<>();
public EncodedResourceResolver() {
this.extensions.put("gzip", ".gz");
this.extensions.put("br", ".br");
}
/**
* Configure the supported content codings in order of preference. The first
* coding that is present in the {@literal "Accept-Encoding"} header for a
* given request, and that has a file present with the associated extension,
* is used.
* <p><strong>Note:</strong> Each coding must be associated with a file
* extension via {@link #registerExtension} or {@link #setExtensions}. Also,
* customizations to the list of codings here should be matched by
* customizations to the same list in {@link CachingResourceResolver} to
* ensure encoded variants of a resource are cached under separate keys.
* <p>By default this property is set to {@literal ["br", "gzip"]}.
* @param codings one or more supported content codings
*/
public void setContentCodings(List<String> codings) {
Assert.notEmpty(codings, "At least one content coding expected");
this.contentCodings.clear();
this.contentCodings.addAll(codings);
}
/**
* Return a read-only list with the supported content codings.
*/
public List<String> getContentCodings() {
return Collections.unmodifiableList(this.contentCodings);
}
/**
* Configure mappings from content codings to file extensions. A dot "."
* will be prepended in front of the extension value if not present.
* <p>By default this is configured with {@literal ["br" -> ".br"]} and
* {@literal ["gzip" -> ".gz"]}.
* @param extensions the extensions to use.
* @see #registerExtension(String, String)
*/
public void setExtensions(Map<String, String> extensions) {
extensions.forEach(this::registerExtension);
}
/**
* Return a read-only map with coding-to-extension mappings.
*/
public Map<String, String> getExtensions() {
return Collections.unmodifiableMap(this.extensions);
}
/**
* Java config friendly alternative to {@link #setExtensions(Map)}.
* @param coding the content coding
* @param extension the associated file extension
*/
public void registerExtension(String coding, String extension) {
this.extensions.put(coding, (extension.startsWith(".") ? extension : "." + extension));
}
@Override
protected @Nullable Resource resolveResourceInternal(@Nullable HttpServletRequest request, String requestPath,
List<? extends Resource> locations, ResourceResolverChain chain) {
Resource resource = chain.resolveResource(request, requestPath, locations);
if (resource == null || request == null) {
return resource;
}
String acceptEncoding = getAcceptEncoding(request);
if (acceptEncoding == null) {
return resource;
}
for (String coding : this.contentCodings) {
if (acceptEncoding.contains(coding)) {
try {
String extension = getExtension(coding);
Resource encoded = new EncodedResource(resource, coding, extension);
if (encoded.exists()) {
return encoded;
}
}
catch (IOException ex) {
if (logger.isTraceEnabled()) {
logger.trace("No " + coding + " resource for [" + resource.getFilename() + "]", ex);
}
}
}
}
return resource;
}
private @Nullable String getAcceptEncoding(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
return (header != null ? header.toLowerCase(Locale.ROOT) : null);
}
private String getExtension(String coding) {
String extension = this.extensions.get(coding);
if (extension == null) {
throw new IllegalStateException("No file extension associated with content coding " + coding);
}
return extension;
}
@Override
protected @Nullable String resolveUrlPathInternal(String resourceUrlPath,
List<? extends Resource> locations, ResourceResolverChain chain) {
return chain.resolveUrlPath(resourceUrlPath, locations);
}
/**
* An encoded {@link HttpResource}.
*/
static final | EncodedResourceResolver |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/bucket/terms/heuristic/MutualInformationTests.java | {
"start": 896,
"end": 3007
} | class ____ extends AbstractNXYSignificanceHeuristicTestCase {
@Override
protected SignificanceHeuristic getHeuristic(boolean includeNegatives, boolean backgroundIsSuperset) {
return new MutualInformation(includeNegatives, backgroundIsSuperset);
}
@Override
public void testAssertions() {
testBackgroundAssertions(new MutualInformation(true, true), new MutualInformation(true, false));
}
public void testScoreMutual() {
SignificanceHeuristic heuristic = new MutualInformation(true, true);
assertThat(heuristic.getScore(1, 1, 1, 3), greaterThan(0.0));
assertThat(heuristic.getScore(1, 1, 2, 3), lessThan(heuristic.getScore(1, 1, 1, 3)));
assertThat(heuristic.getScore(2, 2, 2, 4), equalTo(1.0));
assertThat(heuristic.getScore(0, 2, 2, 4), equalTo(1.0));
assertThat(heuristic.getScore(2, 2, 4, 4), equalTo(0.0));
assertThat(heuristic.getScore(1, 2, 2, 4), equalTo(0.0));
assertThat(heuristic.getScore(3, 6, 9, 18), equalTo(0.0));
double score = 0.0;
try {
long a = randomLong();
long b = randomLong();
long c = randomLong();
long d = randomLong();
score = heuristic.getScore(a, b, c, d);
} catch (IllegalArgumentException e) {}
assertThat(score, lessThanOrEqualTo(1.0));
assertThat(score, greaterThanOrEqualTo(0.0));
heuristic = new MutualInformation(false, true);
assertThat(heuristic.getScore(0, 1, 2, 3), equalTo(Double.NEGATIVE_INFINITY));
heuristic = new MutualInformation(true, false);
score = heuristic.getScore(2, 3, 1, 4);
assertThat(score, greaterThanOrEqualTo(0.0));
assertThat(score, lessThanOrEqualTo(1.0));
score = heuristic.getScore(1, 4, 2, 3);
assertThat(score, greaterThanOrEqualTo(0.0));
assertThat(score, lessThanOrEqualTo(1.0));
score = heuristic.getScore(1, 3, 4, 4);
assertThat(score, greaterThanOrEqualTo(0.0));
assertThat(score, lessThanOrEqualTo(1.0));
}
}
| MutualInformationTests |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/internal/util/NativeTypesTest.java | {
"start": 504,
"end": 19315
} | class ____ {
@Test
public void testIsNumber() {
assertFalse( NativeTypes.isNumber( null ) );
assertFalse( NativeTypes.isNumber( Object.class ) );
assertFalse( NativeTypes.isNumber( String.class ) );
assertTrue( NativeTypes.isNumber( double.class ) );
assertTrue( NativeTypes.isNumber( Double.class ) );
assertTrue( NativeTypes.isNumber( long.class ) );
assertTrue( NativeTypes.isNumber( Long.class ) );
assertTrue( NativeTypes.isNumber( BigDecimal.class ) );
assertTrue( NativeTypes.isNumber( BigInteger.class ) );
}
/**
* checkout https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*
* The following example shows other ways you can use the underscore in numeric literals:
*/
@Test
public void testUnderscorePlacement1() {
assertThat( getLiteral( long.class.getCanonicalName(), "1234_5678_9012_3456L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "999_99_9999L" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "3.14_15F" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xFF_EC_DE_5EL" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xCAFE_BABEL" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x7fff_ffff_ffff_ffffL" ) ).isNotNull();
assertThat( getLiteral( byte.class.getCanonicalName(), "0b0010_0101" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b11010010_01101001_10010100_10010010L" ) )
.isNotNull();
}
/**
* checkout https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*
* You can place underscores only between digits; you cannot place underscores in the following places:
* <ol>
* <li>At the beginning or end of a number</li>
* <li>Adjacent to a decimal point in a floating point literal</li>
* <li>Prior to an F or L suffix</li>
* <li>In positions where a string of digits is expected</li>
* </ol>
* The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric
* literals:
*/
@Test
public void testUnderscorePlacement2() {
// Invalid: cannot put underscores
// adjacent to a decimal point
assertThat( getLiteral( float.class.getCanonicalName(), "3_.1415F" ) ).isNull();
// Invalid: cannot put underscores
// adjacent to a decimal point
assertThat( getLiteral( float.class.getCanonicalName(), "3._1415F" ) ).isNull();
// Invalid: cannot put underscores
// prior to an L suffix
assertThat( getLiteral( long.class.getCanonicalName(), "999_99_9999_L" ) ).isNull();
// OK (decimal literal)
assertThat( getLiteral( int.class.getCanonicalName(), "5_2" ) ).isNotNull();
// Invalid: cannot put underscores
// At the end of a literal
assertThat( getLiteral( int.class.getCanonicalName(), "52_" ) ).isNull();
// OK (decimal literal)
assertThat( getLiteral( int.class.getCanonicalName(), "5_______2" ) ).isNotNull();
// Invalid: cannot put underscores
// in the 0x radix prefix
assertThat( getLiteral( int.class.getCanonicalName(), "0_x52" ) ).isNull();
// Invalid: cannot put underscores
// at the beginning of a number
assertThat( getLiteral( int.class.getCanonicalName(), "0x_52" ) ).isNull();
// OK (hexadecimal literal)
assertThat( getLiteral( int.class.getCanonicalName(), "0x5_2" ) ).isNotNull();
// Invalid: cannot put underscores
// at the end of a number
assertThat( getLiteral( int.class.getCanonicalName(), "0x52_" ) ).isNull();
}
/**
* checkout https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*
* The following example shows other ways you can use the underscore in numeric literals:
*/
@Test
public void testIntegerLiteralFromJLS() {
// largest positive int: dec / octal / int / binary
assertThat( getLiteral( int.class.getCanonicalName(), "2147483647" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "2147483647" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x7fff_ffff" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0177_7777_7777" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0b0111_1111_1111_1111_1111_1111_1111_1111" ) )
.isNotNull();
// most negative int: dec / octal / int / binary
// NOTE parseInt should be changed to parseUnsignedInt in Java, than the - sign can dissapear (java8)
// and the function will be true to what the compiler shows.
assertThat( getLiteral( int.class.getCanonicalName(), "-2147483648" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x8000_0000" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0200_0000_0000" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0b1000_0000_0000_0000_0000_0000_0000_0000" ) )
.isNotNull();
// -1 representation int: dec / octal / int / binary
assertThat( getLiteral( int.class.getCanonicalName(), "-1" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0xffff_ffff" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0377_7777_7777" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0b1111_1111_1111_1111_1111_1111_1111_1111" ) )
.isNotNull();
// largest positive long: dec / octal / int / binary
assertThat( getLiteral( long.class.getCanonicalName(), "9223372036854775807L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x7fff_ffff_ffff_ffffL" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "07_7777_7777_7777_7777_7777L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_"
+ "1111_1111_1111_1111_1111_1111L" ) ).isNotNull();
// most negative long: dec / octal / int / binary
assertThat( getLiteral( long.class.getCanonicalName(), "-9223372036854775808L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x8000_0000_0000_0000L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "010_0000_0000_0000_0000_0000L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_"
+ "0000_0000_0000_0000_0000_0000L" ) ).isNotNull();
// -1 representation long: dec / octal / int / binary
assertThat( getLiteral( long.class.getCanonicalName(), "-1L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xffff_ffff_ffff_ffffL" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "017_7777_7777_7777_7777_7777L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0b1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_"
+ "1111_1111_1111_1111_1111_1111L" ) ).isNotNull();
// some examples of ints
assertThat( getLiteral( int.class.getCanonicalName(), "0" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "2" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0372" ) ).isNotNull();
//assertThat( getLiteral( int.class.getCanonicalName(), "0xDada_Cafe" ) ).isNotNull(); java8
assertThat( getLiteral( int.class.getCanonicalName(), "1996" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x00_FF__00_FF" ) ).isNotNull();
// some examples of longs
assertThat( getLiteral( long.class.getCanonicalName(), "0777l" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0x100000000L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "2_147_483_648L" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xC0B0L" ) ).isNotNull();
}
/**
* checkout https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*
* The following example shows other ways you can use the underscore in numeric literals:
*/
@Test
public void testFloatingPointLiteralFromJLS() {
// The largest positive finite literal of type float is 3.4028235e38f.
assertThat( getLiteral( float.class.getCanonicalName(), "3.4028235e38f" ) ).isNotNull();
// The smallest positive finite non-zero literal of type float is 1.40e-45f.
assertThat( getLiteral( float.class.getCanonicalName(), "1.40e-45f" ) ).isNotNull();
// The largest positive finite literal of type double is 1.7976931348623157e308.
assertThat( getLiteral( double.class.getCanonicalName(), "1.7976931348623157e308" ) ).isNotNull();
// The smallest positive finite non-zero literal of type double is 4.9e-324
assertThat( getLiteral( double.class.getCanonicalName(), "4.9e-324" ) ).isNotNull();
// some floats
assertThat( getLiteral( float.class.getCanonicalName(), "3.1e1F" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "2.f" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), ".3f" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "0f" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "3.14f" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "6.022137e+23f" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "-3.14f" ) ).isNotNull();
// some doubles
assertThat( getLiteral( double.class.getCanonicalName(), "1e1" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "1e+1" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "2." ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), ".3" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0.0" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "3.14" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "-3.14" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "1e-9D" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "1e137" ) ).isNotNull();
// too large (infinitve)
assertThat( getLiteral( float.class.getCanonicalName(), "3.4028235e38f" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "1.7976931348623157e308" ) ).isNotNull();
// too large (infinitve)
assertThat( getLiteral( float.class.getCanonicalName(), "3.4028235e39f" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "1.7976931348623159e308" ) ).isNull();
// small
assertThat( getLiteral( float.class.getCanonicalName(), "1.40e-45f" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "0x1.0p-149" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9e-324" ) ).isNotNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0x0.001P-1062d" ) ).isNotNull();
// too small
assertThat( getLiteral( float.class.getCanonicalName(), "1.40e-46f" ) ).isNull();
assertThat( getLiteral( float.class.getCanonicalName(), "0x1.0p-150" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9e-325" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0x0.001p-1063d" ) ).isNull();
}
/**
* checkout https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*
* The following example shows other ways you can use the underscore in numeric literals:
*/
@Test
public void testBooleanLiteralFromJLS() {
assertThat( getLiteral( boolean.class.getCanonicalName(), "true" ) ).isNotNull();
assertThat( getLiteral( boolean.class.getCanonicalName(), "false" ) ).isNotNull();
assertThat( getLiteral( boolean.class.getCanonicalName(), "FALSE" ) ).isNull();
}
/**
* checkout https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
*
* The following example shows other ways you can use the underscore in numeric literals:
*/
@Test
public void testCharLiteralFromJLS() {
assertThat( getLiteral( char.class.getCanonicalName(), "'a'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'%'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\t'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\\'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\''" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\u03a9'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\uFFFF'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'\177'" ) ).isNotNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'Ω'" ) ).isNotNull();
}
@Test
public void testShortAndByte() {
assertThat( getLiteral( short.class.getCanonicalName(), "0xFE" ) ).isNotNull();
// some examples of ints
assertThat( getLiteral( byte.class.getCanonicalName(), "0" ) ).isNotNull();
assertThat( getLiteral( byte.class.getCanonicalName(), "2" ) ).isNotNull();
assertThat( getLiteral( byte.class.getCanonicalName(), "127" ) ).isNotNull();
assertThat( getLiteral( byte.class.getCanonicalName(), "-128" ) ).isNotNull();
assertThat( getLiteral( short.class.getCanonicalName(), "1996" ) ).isNotNull();
assertThat( getLiteral( short.class.getCanonicalName(), "-1996" ) ).isNotNull();
}
@Test
public void testMiscellaneousErroneousPatterns() {
assertThat( getLiteral( int.class.getCanonicalName(), "1F" ) ).isNull();
assertThat( getLiteral( float.class.getCanonicalName(), "1D" ) ).isNull();
assertThat( getLiteral( int.class.getCanonicalName(), "_1" ) ).isNull();
assertThat( getLiteral( int.class.getCanonicalName(), "1_" ) ).isNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0x_1" ) ).isNull();
assertThat( getLiteral( int.class.getCanonicalName(), "0_x1" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9e_-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9_e-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4._9e-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4_.9e-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "_4.9e-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9E-3_" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9E_-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9E-_3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9E+-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9E+_3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "4.9_E-3" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0x0.001_P-10d" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0x0.001P_-10d" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0x0.001_p-10d" ) ).isNull();
assertThat( getLiteral( double.class.getCanonicalName(), "0x0.001p_-10d" ) ).isNull();
}
@Test
public void testNegatives() {
assertThat( getLiteral( int.class.getCanonicalName(), "-0xffaa" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "-0377_7777" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "-0b1111_1111" ) ).isNotNull();
}
@Test
public void testFaultyChar() {
assertThat( getLiteral( char.class.getCanonicalName(), "''" ) ).isNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'a" ) ).isNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'aa" ) ).isNull();
assertThat( getLiteral( char.class.getCanonicalName(), "a'" ) ).isNull();
assertThat( getLiteral( char.class.getCanonicalName(), "aa'" ) ).isNull();
assertThat( getLiteral( char.class.getCanonicalName(), "'" ) ).isNull();
assertThat( getLiteral( char.class.getCanonicalName(), "a" ) ).isNull();
}
@Test
public void testFloatWithLongLiteral() {
assertThat( getLiteral( float.class.getCanonicalName(), "156L" ) ).isNotNull();
assertThat( getLiteral( float.class.getCanonicalName(), "156l" ) ).isNotNull();
}
@Test
public void testLongPrimitivesWithLongSuffix() {
assertThat( getLiteral( long.class.getCanonicalName(), "156l" ) ).isNotNull();
assertThat( getLiteral( long.class.getCanonicalName(), "156L" ) ).isNotNull();
}
@Test
public void testIntPrimitiveWithLongSuffix() {
assertThat( getLiteral( int.class.getCanonicalName(), "156l" ) ).isNull();
assertThat( getLiteral( int.class.getCanonicalName(), "156L" ) ).isNull();
}
@Test
public void testTooBigIntegersAndBigLongs() {
assertThat( getLiteral( int.class.getCanonicalName(), "0xFFFF_FFFF_FFFF" ) ).isNull();
assertThat( getLiteral( long.class.getCanonicalName(), "0xFFFF_FFFF_FFFF_FFFF_FFFF" ) ).isNull();
}
@Test
public void testNonSupportedPrimitiveType() {
assertThat( getLiteral( void.class.getCanonicalName(), "0xFFFF_FFFF_FFFF" ) ).isNull();
}
private static Class<?> getLiteral(String className, String literal) {
try {
return NativeTypes.getLiteral( className, literal );
}
catch ( IllegalArgumentException ex ) {
return null;
}
}
}
| NativeTypesTest |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java | {
"start": 3404,
"end": 4555
} | class ____ not. Note that the latter will only work if the target class
* does not have final methods, as a dynamic subclass will be created at runtime.
*
* <p>It's possible to cast a proxy obtained from this factory to {@link Advised},
* or to obtain the ProxyFactoryBean reference and programmatically manipulate it.
* This won't work for existing prototype references, which are independent. However,
* it will work for prototypes subsequently obtained from the factory. Changes to
* interception will work immediately on singletons (including existing references).
* However, to change interfaces or a target it's necessary to obtain a new instance
* from the factory. This means that singleton instances obtained from the factory
* do not have the same object identity. However, they do have the same interceptors
* and target, and changing any reference will change all objects.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see #setInterceptorNames
* @see #setProxyInterfaces
* @see org.aopalliance.intercept.MethodInterceptor
* @see org.springframework.aop.Advisor
* @see Advised
*/
@SuppressWarnings("serial")
public | if |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayAutoTypeTest2.java | {
"start": 1535,
"end": 1804
} | class ____ {
public int id;
}
@JSONType(typeName = "B", orders = {"name", "id"}
, serialzeFeatures = {SerializerFeature.BeanToArray, SerializerFeature.WriteClassName}
, parseFeatures = Feature.SupportArrayToBean)
public static | A |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/fs/TestSymlinkHdfsDisable.java | {
"start": 1286,
"end": 2698
} | class ____ {
@Test
@Timeout(value = 60)
public void testSymlinkHdfsDisable() throws Exception {
Configuration conf = new HdfsConfiguration();
// disable symlink resolution
conf.setBoolean(
CommonConfigurationKeys.FS_CLIENT_RESOLVE_REMOTE_SYMLINKS_KEY, false);
// spin up minicluster, get dfs and filecontext
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
DistributedFileSystem dfs = cluster.getFileSystem();
FileContext fc = FileContext.getFileContext(cluster.getURI(0), conf);
// Create test files/links
FileContextTestHelper helper = new FileContextTestHelper(
"/tmp/TestSymlinkHdfsDisable");
Path root = helper.getTestRootPath(fc);
Path target = new Path(root, "target");
Path link = new Path(root, "link");
DFSTestUtil.createFile(dfs, target, 4096, (short)1, 0xDEADDEAD);
fc.createSymlink(target, link, false);
// Try to resolve links with FileSystem and FileContext
try {
fc.open(link);
fail("Expected error when attempting to resolve link");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("resolution is disabled", e);
}
try {
dfs.open(link);
fail("Expected error when attempting to resolve link");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("resolution is disabled", e);
}
}
}
| TestSymlinkHdfsDisable |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/inference/SecretSettings.java | {
"start": 657,
"end": 807
} | interface ____ extends ToXContentObject, VersionedNamedWriteable {
SecretSettings newSecretSettings(Map<String, Object> newSecrets);
}
| SecretSettings |
java | elastic__elasticsearch | test/framework/src/test/java/org/elasticsearch/test/XContentTestUtilsTests.java | {
"start": 1538,
"end": 11710
} | class ____ extends ESTestCase {
public void testGetInsertPaths() throws IOException {
XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject();
{
builder.field("field1", "value");
builder.startArray("list1");
{
builder.value(0);
builder.value(1);
builder.startObject();
builder.endObject();
builder.value(3);
builder.startObject();
builder.endObject();
}
builder.endArray();
builder.startObject("inner1");
{
builder.field("inner1field1", "value");
builder.startObject("inn.er2");
{
builder.field("inner2field1", "value");
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
try (
XContentParser parser = XContentHelper.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
BytesReference.bytes(builder),
builder.contentType()
)
) {
parser.nextToken();
List<String> insertPaths = XContentTestUtils.getInsertPaths(parser, new ArrayDeque<>());
assertEquals(5, insertPaths.size());
assertThat(insertPaths, hasItem(equalTo("")));
assertThat(insertPaths, hasItem(equalTo("list1.2")));
assertThat(insertPaths, hasItem(equalTo("list1.4")));
assertThat(insertPaths, hasItem(equalTo("inner1")));
assertThat(insertPaths, hasItem(equalTo("inner1.inn\\.er2")));
}
}
@SuppressWarnings("unchecked")
public void testInsertIntoXContent() throws IOException {
XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject();
builder.endObject();
builder = XContentTestUtils.insertIntoXContent(
XContentType.JSON.xContent(),
BytesReference.bytes(builder),
Collections.singletonList(""),
() -> "inn.er1",
() -> new HashMap<>()
);
builder = XContentTestUtils.insertIntoXContent(
XContentType.JSON.xContent(),
BytesReference.bytes(builder),
Collections.singletonList(""),
() -> "field1",
() -> "value1"
);
builder = XContentTestUtils.insertIntoXContent(
XContentType.JSON.xContent(),
BytesReference.bytes(builder),
Collections.singletonList("inn\\.er1"),
() -> "inner2",
() -> new HashMap<>()
);
builder = XContentTestUtils.insertIntoXContent(
XContentType.JSON.xContent(),
BytesReference.bytes(builder),
Collections.singletonList("inn\\.er1"),
() -> "field2",
() -> "value2"
);
try (
XContentParser parser = XContentHelper.createParser(
NamedXContentRegistry.EMPTY,
DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
BytesReference.bytes(builder),
builder.contentType()
)
) {
Map<String, Object> map = parser.map();
assertEquals(2, map.size());
assertEquals("value1", map.get("field1"));
assertThat(map.get("inn.er1"), instanceOf(Map.class));
Map<String, Object> innerMap = (Map<String, Object>) map.get("inn.er1");
assertEquals(2, innerMap.size());
assertEquals("value2", innerMap.get("field2"));
assertThat(innerMap.get("inner2"), instanceOf(Map.class));
assertEquals(0, ((Map<String, Object>) innerMap.get("inner2")).size());
}
}
@SuppressWarnings("unchecked")
public void testInsertRandomXContent() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
{
builder.startObject("foo");
{
builder.field("bar", 1);
}
builder.endObject();
builder.startObject("foo1");
{
builder.startObject("foo2");
{
builder.field("buzz", 1);
}
builder.endObject();
}
builder.endObject();
builder.field("foo3", 2);
builder.startArray("foo4");
{
builder.startObject();
{
builder.field("foo5", 1);
}
builder.endObject();
}
builder.endArray();
}
builder.endObject();
Map<String, Object> resultMap;
try (
XContentParser parser = createParser(
XContentType.JSON.xContent(),
insertRandomFields(builder.contentType(), BytesReference.bytes(builder), null, random())
)
) {
resultMap = parser.map();
}
assertEquals(5, resultMap.keySet().size());
assertEquals(2, ((Map<String, Object>) resultMap.get("foo")).keySet().size());
Map<String, Object> foo1 = (Map<String, Object>) resultMap.get("foo1");
assertEquals(2, foo1.keySet().size());
assertEquals(2, ((Map<String, Object>) foo1.get("foo2")).keySet().size());
List<Object> foo4List = (List<Object>) resultMap.get("foo4");
assertEquals(1, foo4List.size());
assertEquals(2, ((Map<String, Object>) foo4List.get(0)).keySet().size());
Predicate<String> pathsToExclude = path -> path.endsWith("foo1");
try (
XContentParser parser = createParser(
XContentType.JSON.xContent(),
insertRandomFields(builder.contentType(), BytesReference.bytes(builder), pathsToExclude, random())
)
) {
resultMap = parser.map();
}
assertEquals(5, resultMap.keySet().size());
assertEquals(2, ((Map<String, Object>) resultMap.get("foo")).keySet().size());
foo1 = (Map<String, Object>) resultMap.get("foo1");
assertEquals(1, foo1.keySet().size());
assertEquals(2, ((Map<String, Object>) foo1.get("foo2")).keySet().size());
foo4List = (List<Object>) resultMap.get("foo4");
assertEquals(1, foo4List.size());
assertEquals(2, ((Map<String, Object>) foo4List.get(0)).keySet().size());
pathsToExclude = path -> path.contains("foo1");
try (
XContentParser parser = createParser(
XContentType.JSON.xContent(),
insertRandomFields(builder.contentType(), BytesReference.bytes(builder), pathsToExclude, random())
)
) {
resultMap = parser.map();
}
assertEquals(5, resultMap.keySet().size());
assertEquals(2, ((Map<String, Object>) resultMap.get("foo")).keySet().size());
foo1 = (Map<String, Object>) resultMap.get("foo1");
assertEquals(1, foo1.keySet().size());
assertEquals(1, ((Map<String, Object>) foo1.get("foo2")).keySet().size());
foo4List = (List<Object>) resultMap.get("foo4");
assertEquals(1, foo4List.size());
assertEquals(2, ((Map<String, Object>) foo4List.get(0)).keySet().size());
}
public void testDifferenceBetweenMapsIgnoringArrayOrder() {
var map1 = Map.of("foo", List.of(1, 2, 3), "bar", Map.of("a", 2, "b", List.of(3, 2, 1)), "baz", List.of(3, 2, 1, "test"));
var map2 = Map.of("foo", List.of(3, 2, 1), "bar", Map.of("b", List.of(3, 1, 2), "a", 2), "baz", List.of(1, "test", 2, 3));
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2), nullValue());
}
public void testDifferenceBetweenMapsIgnoringArrayOrder_WithFilter_Object() {
var map1 = Map.of("foo", List.of(1, 2, 3), "bar", Map.of("a", 2, "b", List.of(3, 2, 1)), "different", Map.of("a", 1, "x", 8));
var map2 = Map.of(
"foo",
List.of(3, 2, 1),
"bar",
Map.of("b", List.of(3, 1, 2), "a", 2),
"different",
Map.of("a", 1, "x", "different value")
);
assertThat(
differenceBetweenMapsIgnoringArrayOrder(map1, map2),
equalTo("/different/x: the elements don't match: [8] != [different value]")
);
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.equals("/different/x") == false), nullValue());
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.equals("/different") == false), nullValue());
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.isEmpty() == false), nullValue());
}
public void testDifferenceBetweenMapsIgnoringArrayOrder_WithFilter_Array() {
var map1 = Map.of(
"foo",
List.of(1, 2, 3),
"bar",
Map.of("a", 2, "b", List.of(3, 2, 1)),
"different",
List.of(3, Map.of("x", 10), 1)
);
var map2 = Map.of(
"foo",
List.of(3, 2, 1),
"bar",
Map.of("b", List.of(3, 1, 2), "a", 2),
"different",
List.of(3, Map.of("x", 5), 1)
);
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2), equalTo("/different/*: the second element is not a map (got 1)"));
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.equals("/different/*/x") == false), nullValue());
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.equals("/different/*") == false), nullValue());
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.equals("/different") == false), nullValue());
assertThat(differenceBetweenMapsIgnoringArrayOrder(map1, map2, path -> path.isEmpty() == false), nullValue());
}
}
| XContentTestUtilsTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/graph/AbstractEntityGraphTest.java | {
"start": 765,
"end": 3267
} | class ____ {
protected <T> RootGraphImplementor<T> parseGraph(Class<T> entityType, String graphString, EntityManagerFactoryScope scope) {
return scope.fromEntityManager( entityManager ->
(RootGraphImplementor<T>) GraphParser.parse( entityType, graphString, entityManager )
);
}
protected <T> RootGraphImplementor<GraphParsingTestEntity> parseGraph(String graphString, EntityManagerFactoryScope scope) {
return parseGraph( GraphParsingTestEntity.class, graphString, scope );
}
private <C extends Collection<?>> void assertNullOrEmpty(C collection) {
if ( collection != null ) {
assertThat( collection).hasSize( 0 );
}
}
protected <M extends Map<?, ?>> void assertNullOrEmpty(M map) {
if ( map != null ) {
assertThat( map.size()).isEqualTo( 0 );
}
}
protected void assertBasicAttributes(EntityGraph<?> graph, String... names) {
assertThat( graph ).isNotNull();
assertBasicAttributes( graph.getAttributeNodes(), names );
}
protected void assertBasicAttributes(Subgraph<?> graph, String... names) {
assertThat( graph ).isNotNull();
assertBasicAttributes( graph.getAttributeNodes(), names );
}
private void assertBasicAttributes(List<AttributeNode<?>> attrs, String... names) {
if ( (names == null) || (names.length == 0) ) {
assertNullOrEmpty( attrs );
}
else {
assertThat( attrs ).isNotNull();
assertThat( names.length).isLessThanOrEqualTo( attrs.size() );
for ( String name : names ) {
AttributeNode<?> node = null;
for ( AttributeNode<?> candidate : attrs ) {
if ( candidate.getAttributeName().equals( name ) ) {
node = candidate;
break;
}
}
assertThat( node ).isNotNull();
assertNullOrEmpty( node.getKeySubgraphs() );
assertNullOrEmpty( node.getSubgraphs() );
}
}
}
protected AttributeNode<?> getAttributeNodeByName(EntityGraph<?> graph, String name, boolean required) {
return getAttributeNodeByName( graph.getAttributeNodes(), name, required );
}
protected AttributeNode<?> getAttributeNodeByName(Subgraph<?> graph, String name, boolean required) {
return getAttributeNodeByName( graph.getAttributeNodes(), name, required );
}
private AttributeNode<?> getAttributeNodeByName(List<AttributeNode<?>> attrs, String name, boolean required) {
for ( AttributeNode<?> attr : attrs ) {
if ( name.equals( attr.getAttributeName() ) ) {
return attr;
}
}
if ( required ) {
fail( "Required attribute not found." );
}
return null;
}
}
| AbstractEntityGraphTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/JSONReaderTest_object_object.java | {
"start": 224,
"end": 2275
} | class ____ extends TestCase {
String text = "{\"f0\":{},\"f1\":{},\"f2\":{},\"f3\":{},\"f4\":{}, " + //
"\"f5\":{},\"f6\":{},\"f7\":{},\"f8\":{},\"f9\":{}}";
public void test_read() throws Exception {
JSONReader reader = new JSONReader(new StringReader(text));
reader.startObject();
int count = 0;
while (reader.hasNext()) {
String key = (String) reader.readObject();
Object value = reader.readObject();
Assert.assertNotNull(key);
Assert.assertNotNull(value);
count++;
}
Assert.assertEquals(10, count);
reader.endObject();
reader.close();
}
public void test_read_1() throws Exception {
JSONReader reader = new JSONReader(new JSONScanner(text));
reader.startObject();
int count = 0;
while (reader.hasNext()) {
String key = (String) reader.readObject();
Object value = reader.readObject();
Assert.assertNotNull(key);
Assert.assertNotNull(value);
count++;
}
Assert.assertEquals(10, count);
reader.endObject();
reader.close();
}
public void test_read_2() throws Exception {
JSONReader reader = new JSONReader(new JSONScanner("{{}:{},{}:{}}"));
reader.startObject();
Assert.assertTrue(reader.hasNext());
reader.startObject();
reader.endObject();
reader.startObject();
reader.endObject();
Assert.assertTrue(reader.hasNext());
reader.startObject();
reader.endObject();
reader.startObject();
reader.endObject();
Assert.assertFalse(reader.hasNext());
reader.endObject();
Exception error = null;
try {
reader.hasNext();
} catch (Exception ex) {
error = ex;
}
Assert.assertNotNull(error);
reader.close();
}
}
| JSONReaderTest_object_object |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/indexing/IterationResult.java | {
"start": 480,
"end": 553
} | interface ____ the implementation and the generic indexer.
*/
public | between |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/jira/JiraActionFactory.java | {
"start": 647,
"end": 1468
} | class ____ extends ActionFactory {
private final TextTemplateEngine templateEngine;
private final JiraService jiraService;
public JiraActionFactory(TextTemplateEngine templateEngine, JiraService jiraService) {
super(LogManager.getLogger(ExecutableJiraAction.class));
this.templateEngine = templateEngine;
this.jiraService = jiraService;
}
@Override
public ExecutableJiraAction parseExecutable(String watchId, String actionId, XContentParser parser) throws IOException {
JiraAction action = JiraAction.parse(watchId, actionId, parser);
jiraService.getAccount(action.getAccount()); // for validation -- throws exception if account not present
return new ExecutableJiraAction(action, actionLogger, jiraService, templateEngine);
}
}
| JiraActionFactory |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/producer/RequestFutureHolder.java | {
"start": 1549,
"end": 4476
} | class ____ {
private static final Logger log = LoggerFactory.getLogger(RequestFutureHolder.class);
private static final RequestFutureHolder INSTANCE = new RequestFutureHolder();
private ConcurrentHashMap<String, RequestResponseFuture> requestFutureTable = new ConcurrentHashMap<>();
private final Set<DefaultMQProducerImpl> producerSet = new HashSet<>();
private ScheduledExecutorService scheduledExecutorService = null;
public ConcurrentHashMap<String, RequestResponseFuture> getRequestFutureTable() {
return requestFutureTable;
}
private void scanExpiredRequest() {
final List<RequestResponseFuture> rfList = new LinkedList<>();
Iterator<Map.Entry<String, RequestResponseFuture>> it = requestFutureTable.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, RequestResponseFuture> next = it.next();
RequestResponseFuture rep = next.getValue();
if (rep.isTimeout()) {
it.remove();
rfList.add(rep);
log.warn("remove timeout request, CorrelationId={}" + rep.getCorrelationId());
}
}
for (RequestResponseFuture rf : rfList) {
try {
Throwable cause = new RequestTimeoutException(ClientErrorCode.REQUEST_TIMEOUT_EXCEPTION, "request timeout, no reply message.");
rf.setCause(cause);
rf.executeRequestCallback();
} catch (Throwable e) {
log.warn("scanResponseTable, operationComplete Exception", e);
}
}
}
public synchronized void startScheduledTask(DefaultMQProducerImpl producer) {
this.producerSet.add(producer);
if (null == scheduledExecutorService) {
this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl("RequestHouseKeepingService"));
this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
RequestFutureHolder.getInstance().scanExpiredRequest();
} catch (Throwable e) {
log.error("scan RequestFutureTable exception", e);
}
}
}, 1000 * 3, 1000, TimeUnit.MILLISECONDS);
}
}
public synchronized void shutdown(DefaultMQProducerImpl producer) {
this.producerSet.remove(producer);
if (this.producerSet.size() <= 0 && null != this.scheduledExecutorService) {
ScheduledExecutorService executorService = this.scheduledExecutorService;
this.scheduledExecutorService = null;
executorService.shutdown();
}
}
private RequestFutureHolder() {}
public static RequestFutureHolder getInstance() {
return INSTANCE;
}
}
| RequestFutureHolder |
java | elastic__elasticsearch | x-pack/plugin/ql/src/test/java/org/elasticsearch/xpack/ql/tree/NodeTests.java | {
"start": 2521,
"end": 3330
} | class ____ extends Node<Dummy> {
private final String thing;
public Dummy(Source source, List<Dummy> children, String thing) {
super(source, children);
this.thing = thing;
}
public String thing() {
return thing;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != getClass()) {
return false;
}
Dummy other = (Dummy) obj;
return thing.equals(other.thing) && children().equals(other.children());
}
@Override
public int hashCode() {
return Objects.hash(thing, children());
}
}
public static | Dummy |
java | apache__camel | components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/internal/BoxEventLogsManagerApiMethod.java | {
"start": 673,
"end": 1779
} | enum ____ implements ApiMethod {
GET_ENTERPRISE_EVENTS(
java.util.List.class,
"getEnterpriseEvents",
arg("position", String.class),
arg("after", java.util.Date.class),
arg("before", java.util.Date.class),
arg("types", new com.box.sdk.BoxEvent.EventType[0].getClass()));
private final ApiMethod apiMethod;
BoxEventLogsManagerApiMethod(Class<?> resultType, String name, ApiMethodArg... args) {
this.apiMethod = new ApiMethodImpl(BoxEventLogsManager.class, resultType, name, args);
}
@Override
public String getName() { return apiMethod.getName(); }
@Override
public Class<?> getResultType() { return apiMethod.getResultType(); }
@Override
public List<String> getArgNames() { return apiMethod.getArgNames(); }
@Override
public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); }
@Override
public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); }
@Override
public Method getMethod() { return apiMethod.getMethod(); }
}
| BoxEventLogsManagerApiMethod |
java | apache__rocketmq | common/src/test/java/org/apache/rocketmq/common/UtilAllTest.java | {
"start": 7304,
"end": 9804
} | class ____ extends DemoConfig {
private String subField0 = "0";
public boolean subField1 = true;
public String getSubField0() {
return subField0;
}
public void setSubField0(String subField0) {
this.subField0 = subField0;
}
public boolean isSubField1() {
return subField1;
}
public void setSubField1(boolean subField1) {
this.subField1 = subField1;
}
}
@Test
public void testCleanBuffer() {
UtilAll.cleanBuffer(null);
UtilAll.cleanBuffer(ByteBuffer.allocateDirect(10));
UtilAll.cleanBuffer(ByteBuffer.allocateDirect(0));
UtilAll.cleanBuffer(ByteBuffer.allocate(10));
}
@Test
public void testCalculateFileSizeInPath() throws Exception {
/**
* testCalculateFileSizeInPath
* - file_0
* - dir_1
* - file_1_0
* - file_1_1
* - dir_1_2
* - file_1_2_0
* - dir_2
*/
File baseFile = tempDir.getRoot();
// test empty path
assertEquals(0, UtilAll.calculateFileSizeInPath(baseFile));
File file0 = new File(baseFile, "file_0");
assertTrue(file0.createNewFile());
writeFixedBytesToFile(file0, 1313);
assertEquals(1313, UtilAll.calculateFileSizeInPath(baseFile));
// build a file tree like above
File dir1 = new File(baseFile, "dir_1");
dir1.mkdirs();
File file10 = new File(dir1, "file_1_0");
File file11 = new File(dir1, "file_1_1");
File dir12 = new File(dir1, "dir_1_2");
dir12.mkdirs();
File file120 = new File(dir12, "file_1_2_0");
File dir2 = new File(baseFile, "dir_2");
dir2.mkdirs();
// write all file with 1313 bytes data
assertTrue(file10.createNewFile());
writeFixedBytesToFile(file10, 1313);
assertTrue(file11.createNewFile());
writeFixedBytesToFile(file11, 1313);
assertTrue(file120.createNewFile());
writeFixedBytesToFile(file120, 1313);
assertEquals(1313 * 4, UtilAll.calculateFileSizeInPath(baseFile));
}
private void writeFixedBytesToFile(File file, int size) throws Exception {
FileOutputStream outputStream = new FileOutputStream(file);
byte[] bytes = new byte[size];
outputStream.write(bytes, 0, size);
outputStream.close();
}
}
| DemoSubConfig |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/cglib/transform/impl/FieldProvider.java | {
"start": 721,
"end": 972
} | interface ____ {
String[] getFieldNames();
Class[] getFieldTypes();
void setField(int index, Object value);
Object getField(int index);
void setField(String name, Object value);
Object getField(String name);
}
| FieldProvider |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/OverriddenSQLDeleteAllAnnotation.java | {
"start": 878,
"end": 2375
} | class ____
extends AbstractOverrider<SQLDeleteAll>
implements DialectOverride.SQLDeleteAll, DialectOverrider<SQLDeleteAll> {
private SQLDeleteAll override;
/**
* Used in creating dynamic annotation instances (e.g. from XML)
*/
public OverriddenSQLDeleteAllAnnotation(ModelsContext sourceModelContext) {
}
/**
* Used in creating annotation instances from JDK variant
*/
public OverriddenSQLDeleteAllAnnotation(
DialectOverride.SQLDeleteAll annotation,
ModelsContext sourceModelContext) {
dialect( annotation.dialect() );
before( annotation.before() );
sameOrAfter( annotation.sameOrAfter() );
override( extractJdkValue( annotation, DIALECT_OVERRIDE_SQL_DELETE_ALL, "override", sourceModelContext ) );
}
/**
* Used in creating annotation instances from Jandex variant
*/
public OverriddenSQLDeleteAllAnnotation(
Map<String, Object> attributeValues,
ModelsContext sourceModelContext) {
super( attributeValues, DIALECT_OVERRIDE_SQL_DELETE_ALL, sourceModelContext );
override( (SQLDeleteAll) attributeValues.get( "override" ) );
}
@Override
public AnnotationDescriptor<SQLDeleteAll> getOverriddenDescriptor() {
return HibernateAnnotations.SQL_DELETE_ALL;
}
@Override
public SQLDeleteAll override() {
return override;
}
public void override(SQLDeleteAll value) {
this.override = value;
}
@Override
public Class<? extends Annotation> annotationType() {
return DialectOverride.SQLDeleteAll.class;
}
}
| OverriddenSQLDeleteAllAnnotation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.