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
bumptech__glide
integration/recyclerview/src/main/java/com/bumptech/glide/integration/recyclerview/RecyclerToListViewScrollListener.java
{ "start": 552, "end": 2421 }
class ____ extends RecyclerView.OnScrollListener { public static final int UNKNOWN_SCROLL_STATE = Integer.MIN_VALUE; private final AbsListView.OnScrollListener scrollListener; private int lastFirstVisible = -1; private int lastVisibleCount = -1; private int lastItemCount = -1; public RecyclerToListViewScrollListener(@NonNull AbsListView.OnScrollListener scrollListener) { this.scrollListener = scrollListener; } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { int listViewState; switch (newState) { case RecyclerView.SCROLL_STATE_DRAGGING: listViewState = ListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL; break; case RecyclerView.SCROLL_STATE_IDLE: listViewState = ListView.OnScrollListener.SCROLL_STATE_IDLE; break; case RecyclerView.SCROLL_STATE_SETTLING: listViewState = ListView.OnScrollListener.SCROLL_STATE_FLING; break; default: listViewState = UNKNOWN_SCROLL_STATE; } scrollListener.onScrollStateChanged(null /*view*/, listViewState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); int firstVisible = layoutManager.findFirstVisibleItemPosition(); int visibleCount = Math.abs(firstVisible - layoutManager.findLastVisibleItemPosition()); int itemCount = recyclerView.getAdapter().getItemCount(); if (firstVisible != lastFirstVisible || visibleCount != lastVisibleCount || itemCount != lastItemCount) { scrollListener.onScroll(null, firstVisible, visibleCount, itemCount); lastFirstVisible = firstVisible; lastVisibleCount = visibleCount; lastItemCount = itemCount; } } }
RecyclerToListViewScrollListener
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/InitializeInline.java
{ "start": 1982, "end": 3699 }
class ____ extends BugChecker implements VariableTreeMatcher { @Override public Description matchVariable(VariableTree tree, VisitorState state) { Tree declarationParent = state.getPath().getParentPath().getLeaf(); if (declarationParent instanceof ClassTree) { return NO_MATCH; } VarSymbol symbol = getSymbol(tree); if (!isConsideredFinal(symbol)) { return NO_MATCH; } List<TreePath> assignments = new ArrayList<>(); new TreePathScanner<Void, Void>() { @Override public Void visitAssignment(AssignmentTree node, Void unused) { if (symbol.equals(getSymbol(node.getVariable()))) { assignments.add(getCurrentPath()); } return super.visitAssignment(node, null); } }.scan(state.getPath().getParentPath(), null); if (assignments.size() != 1) { return NO_MATCH; } TreePath soleAssignmentPath = getOnlyElement(assignments); Tree grandParent = soleAssignmentPath.getParentPath().getParentPath().getLeaf(); if (!(soleAssignmentPath.getParentPath().getLeaf() instanceof StatementTree && grandParent.equals(declarationParent))) { return NO_MATCH; } ModifiersTree modifiersTree = tree.getModifiers(); String modifiers = modifiersTree == null || state.getEndPosition(modifiersTree) == Position.NOPOS ? "" : (state.getSourceForNode(modifiersTree) + " "); return describeMatch( tree, SuggestedFix.builder() .replace(tree, "") .prefixWith( soleAssignmentPath.getLeaf(), modifiers + state.getSourceForNode(tree.getType()) + " ") .build()); } }
InitializeInline
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/io/parsing/Symbol.java
{ "start": 15951, "end": 16703 }
class ____ extends IntCheckAction { public final boolean noAdjustments; public final Object[] adjustments; @Deprecated public EnumAdjustAction(int rsymCount, Object[] adjustments) { super(rsymCount); this.adjustments = adjustments; boolean noAdj = true; if (adjustments != null) { int count = Math.min(rsymCount, adjustments.length); noAdj = (adjustments.length <= rsymCount); for (int i = 0; noAdj && i < count; i++) noAdj &= ((adjustments[i] instanceof Integer) && i == (Integer) adjustments[i]); } this.noAdjustments = noAdj; } } public static WriterUnionAction writerUnionAction() { return new WriterUnionAction(); } public static
EnumAdjustAction
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/multiplepersistenceunits/MultiplePersistenceUnitsImportSqlHotReloadScriptTest.java
{ "start": 866, "end": 2361 }
class ____ { @RegisterExtension final static QuarkusDevModeTest TEST = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addPackage(Plane.class.getPackage().getName()) .addPackage(SharedEntity.class.getPackage().getName()) .addPackage(User.class.getPackage().getName()) .addPackage(OtherUserInSubPackage.class.getPackage().getName()) .addClass(MultiplePersistenceUnitsSqlLoadScriptTestResource.class) .addAsResource("application-multiple-persistence-units-annotations.properties", "application.properties") .addAsResource("import-sharedentity.sql", "import.sql")); @Test public void testImportSqlScriptHotReload() { String expectedName = "import.sql load script entity"; assertBodyIs(expectedName); String hotReloadExpectedName = "modified import.sql load script entity"; TEST.modifyResourceFile("import.sql", new Function<String, String>() { @Override public String apply(String s) { return s.replace(expectedName, hotReloadExpectedName); } }); assertBodyIs(hotReloadExpectedName); } private void assertBodyIs(String expectedBody) { RestAssured.when().get("/multiple-persistence-units/orm-sql-load-script/2").then().body(is(expectedBody)); } }
MultiplePersistenceUnitsImportSqlHotReloadScriptTest
java
apache__flink
flink-core/src/test/java/org/apache/flink/util/jackson/JacksonMapperFactoryTest.java
{ "start": 1596, "end": 5693 }
class ____ { @Test void testCreateObjectMapperReturnDistinctMappers() { final ObjectMapper mapper1 = JacksonMapperFactory.createObjectMapper(); final ObjectMapper mapper2 = JacksonMapperFactory.createObjectMapper(); assertThat(mapper1).isNotSameAs(mapper2); } @Test void testCreateCsvMapperReturnDistinctMappers() { final CsvMapper mapper1 = JacksonMapperFactory.createCsvMapper(); final CsvMapper mapper2 = JacksonMapperFactory.createCsvMapper(); assertThat(mapper1).isNotSameAs(mapper2); } @Test void testObjectMapperOptionalSupportedEnabled() throws Exception { final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper(); assertThat(mapper.writeValueAsString(new TypeWithOptional(Optional.of("value")))) .isEqualTo("{\"data\":\"value\"}"); assertThat(mapper.writeValueAsString(new TypeWithOptional(Optional.empty()))) .isEqualTo("{\"data\":null}"); assertThat(mapper.readValue("{\"data\":\"value\"}", TypeWithOptional.class).data) .contains("value"); assertThat(mapper.readValue("{\"data\":null}", TypeWithOptional.class).data).isEmpty(); assertThat(mapper.readValue("{}", TypeWithOptional.class).data).isEmpty(); } @Test void testCsvMapperOptionalSupportedEnabled() throws Exception { final CsvMapper mapper = JacksonMapperFactory.createCsvMapper() // ensures symmetric read/write behavior for empty optionals/strings // ensures: Optional.empty() --write--> "" --read--> Optional.empty() // otherwise: Optional.empty() --write--> "" --read--> Optional("") // we should consider enabling this by default, but it unfortunately // also affects String parsing without Optionals (i.e., prior code) .enable(CsvParser.Feature.EMPTY_STRING_AS_NULL); final ObjectWriter writer = mapper.writerWithSchemaFor(TypeWithOptional.class); assertThat(writer.writeValueAsString(new TypeWithOptional(Optional.of("value")))) .isEqualTo("value\n"); assertThat(writer.writeValueAsString(new TypeWithOptional(Optional.empty()))) .isEqualTo("\n"); final ObjectReader reader = mapper.readerWithSchemaFor(TypeWithOptional.class); assertThat(reader.readValue("value\n", TypeWithOptional.class).data).contains("value"); assertThat(reader.readValue("null\n", TypeWithOptional.class).data).contains("null"); assertThat(reader.readValue("\n", TypeWithOptional.class).data).isEmpty(); } @Test void testObjectMappeDateTimeSupportedEnabled() throws Exception { final ObjectMapper mapper = JacksonMapperFactory.createObjectMapper(); final String instantString = "2022-08-07T12:00:33.107787800Z"; final Instant instant = Instant.parse(instantString); final String instantJson = String.format("{\"data\":\"%s\"}", instantString); assertThat(mapper.writeValueAsString(new TypeWithInstant(instant))).isEqualTo(instantJson); assertThat(mapper.readValue(instantJson, TypeWithInstant.class).data).isEqualTo(instant); } @Test void testCsvMapperDateTimeSupportedEnabled() throws Exception { final CsvMapper mapper = JacksonMapperFactory.createCsvMapper(); final String instantString = "2022-08-07T12:00:33.107787800Z"; final Instant instant = Instant.parse(instantString); final String instantCsv = String.format("\"%s\"\n", instantString); final ObjectWriter writer = mapper.writerWithSchemaFor(TypeWithInstant.class); assertThat(writer.writeValueAsString(new TypeWithInstant(instant))).isEqualTo(instantCsv); final ObjectReader reader = mapper.readerWithSchemaFor(TypeWithInstant.class); assertThat(reader.readValue(instantCsv, TypeWithInstant.class).data).isEqualTo(instant); } public static
JacksonMapperFactoryTest
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java
{ "start": 25202, "end": 25722 }
interface ____ { ExtendWithFoo[] value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) // Intentionally NOT @Inherited in order to ensure that the algorithm for // findRepeatableAnnotations() in fact lives up to the claims in the // Javadoc regarding searching for repeatable annotations with implicit // "inheritance" if the repeatable annotation is @Inherited but the // custom composed annotation is not @Inherited. // @Inherited @ExtendWith("bar") @
FooExtensions
java
netty__netty
example/src/main/java/io/netty/example/http/helloworld/HttpHelloWorldServerHandler.java
{ "start": 1649, "end": 3218 }
class ____ extends SimpleChannelInboundHandler<HttpObject> { private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK, Unpooled.wrappedBuffer(CONTENT)); response.headers() .set(CONTENT_TYPE, TEXT_PLAIN) .setInt(CONTENT_LENGTH, response.content().readableBytes()); if (keepAlive) { if (!req.protocolVersion().isKeepAliveDefault()) { response.headers().set(CONNECTION, KEEP_ALIVE); } } else { // Tell the client we're going to close the connection. response.headers().set(CONNECTION, CLOSE); } ChannelFuture f = ctx.write(response); if (!keepAlive) { f.addListener(ChannelFutureListener.CLOSE); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
HttpHelloWorldServerHandler
java
apache__flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/AbstractInput.java
{ "start": 1879, "end": 4362 }
class ____<IN, OUT> implements Input<IN>, KeyContextHandler, AsyncKeyOrderedProcessing { /** * {@code KeySelector} for extracting a key from an element being processed. This is used to * scope keyed state to a key. This is null if the operator is not a keyed operator. * * <p>This is for elements from the first input. */ @Nullable protected final KeySelector<?, ?> stateKeySelector; protected final AbstractStreamOperatorV2<OUT> owner; protected final int inputId; protected final Output<StreamRecord<OUT>> output; public AbstractInput(AbstractStreamOperatorV2<OUT> owner, int inputId) { checkArgument(inputId > 0, "Inputs are index from 1"); this.owner = owner; this.inputId = inputId; this.stateKeySelector = owner.config.getStatePartitioner(inputId - 1, owner.getUserCodeClassloader()); this.output = owner.output; } @Override public void processWatermark(Watermark mark) throws Exception { owner.reportWatermark(mark, inputId); } @Override public void processLatencyMarker(LatencyMarker latencyMarker) throws Exception { owner.reportOrForwardLatencyMarker(latencyMarker); } @Override public void processWatermarkStatus(WatermarkStatus watermarkStatus) throws Exception { owner.processWatermarkStatus(watermarkStatus, inputId); } @Override public void setKeyContextElement(StreamRecord record) throws Exception { owner.internalSetKeyContextElement(record, stateKeySelector); } @Override public void processRecordAttributes(RecordAttributes recordAttributes) throws Exception { owner.processRecordAttributes(recordAttributes, inputId); } @Override public boolean hasKeyContext() { return stateKeySelector != null; } @Internal @Override public final boolean isAsyncKeyOrderedProcessingEnabled() { return (owner instanceof AsyncKeyOrderedProcessingOperator) && ((AsyncKeyOrderedProcessingOperator) owner).isAsyncKeyOrderedProcessingEnabled(); } @Internal @Override public final ThrowingConsumer<StreamRecord<IN>, Exception> getRecordProcessor(int inputId) { return AsyncKeyOrderedProcessing.makeRecordProcessor( (AsyncKeyOrderedProcessingOperator) owner, (KeySelector) stateKeySelector, this::processElement); } }
AbstractInput
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/ComposedMessageProcessorTest.java
{ "start": 4595, "end": 5003 }
class ____ { private OrderItemHelper() { } // START SNIPPET: e4 public static boolean isWidget(@Body OrderItem orderItem) { return orderItem.type.equals("widget"); } // END SNIPPET: e4 } /** * Bean that checks whether the specified number of widgets can be ordered */ // START SNIPPET: e5 public static final
OrderItemHelper
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/type/classreading/MetadataReaderFactory.java
{ "start": 863, "end": 1125 }
interface ____ {@link MetadataReader} instances. * Allows for caching a MetadataReader per original resource. * * @author Juergen Hoeller * @author Brian Clozel * @since 2.5 * @see SimpleMetadataReaderFactory * @see CachingMetadataReaderFactory */ public
for
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/nestedresulthandler_gh1551/ProductResp.java
{ "start": 746, "end": 1535 }
class ____ { private String id; private String code; private String name; private List<ProductSku> skus; private ProductInfo productInfo; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<ProductSku> getSkus() { return skus; } public void setSkus(List<ProductSku> skus) { this.skus = skus; } public ProductInfo getProductInfo() { return productInfo; } public void setProductInfo(ProductInfo productInfo) { this.productInfo = productInfo; } }
ProductResp
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/produce/function/ArgumentsValidator.java
{ "start": 538, "end": 1677 }
interface ____ { /** * Perform validation that may be done using the {@link SqmTypedNode} tree and assigned Java types. * * @since 7.0 */ default void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, BindingContext bindingContext) { validate( arguments, functionName, bindingContext.getTypeConfiguration() ); } /** * Perform validation that may be done using the {@link SqmTypedNode} tree and assigned Java types. * * @deprecated Implement {@link #validate(List, String, BindingContext)} instead */ @Deprecated(since = "7.0", forRemoval = true) default void validate(List<? extends SqmTypedNode<?>> arguments, String functionName, TypeConfiguration typeConfiguration) { throw new UnsupportedOperationException( "Deprecated operation not implemented" ); } /** * Pretty-print the signature of the argument list. */ default String getSignature() { return "( ... )"; } /** * Perform validation that requires the {@link SqlAstNode} tree and assigned JDBC types. */ default void validateSqlTypes(List<? extends SqlAstNode> arguments, String functionName) {} }
ArgumentsValidator
java
processing__processing4
app/src/processing/app/syntax/InputHandler.java
{ "start": 17341, "end": 19125 }
class ____ implements ActionListener { private boolean select; public end(boolean select) { this.select = select; } public void actionPerformed(ActionEvent evt) { JEditTextArea textArea = getTextArea(evt); int caret = textArea.getCaretPosition(); int caretLine = textArea.getCaretLine(); int lastOfLine = textArea.getLineStopOffset(caretLine) - 1; int lastNonWhiteSpaceOfLine = textArea.getLineStopNonWhiteSpaceOffset(caretLine) - 1; int lastVisibleLine = textArea.getFirstLine() + textArea.getVisibleLines(); if (lastVisibleLine >= textArea.getLineCount()) { lastVisibleLine = Math.min(textArea.getLineCount() - 1, lastVisibleLine); } else { lastVisibleLine -= (textArea.getElectricScroll() + 1); } int lastVisible = textArea.getLineStopOffset(lastVisibleLine) - 1; int lastDocument = textArea.getDocumentLength(); if (caret == lastDocument && !Preferences.getBoolean(CONTEXT_AWARE_HOME_END)) { textArea.getToolkit().beep(); return; } else if (!Boolean.TRUE.equals(textArea.getClientProperty(SMART_HOME_END_PROPERTY))) { if (!Preferences.getBoolean(CONTEXT_AWARE_HOME_END) || caret == lastNonWhiteSpaceOfLine) { caret = lastOfLine; } else { caret = lastNonWhiteSpaceOfLine; } } else if (caret == lastVisible) { caret = lastDocument; } else if (caret == lastOfLine) { caret = lastVisible; } else { caret = lastOfLine; } if (select) { textArea.select(textArea.getMarkPosition(),caret); } else { textArea.setCaretPosition(caret); } } } public static
end
java
spring-projects__spring-security
buildSrc/src/main/java/lock/GlobalLockPlugin.java
{ "start": 113, "end": 372 }
class ____ implements Plugin<Project> { @Override public void apply(Project project) { project.getTasks().register("writeLocks", GlobalLockTask.class, (writeAll) -> { writeAll.setDescription("Writes the locks for all projects"); }); } }
GlobalLockPlugin
java
quarkusio__quarkus
test-framework/security/src/main/java/io/quarkus/test/security/AttributeType.java
{ "start": 153, "end": 1598 }
enum ____ { LONG { @Override Object convert(String value) { return Long.valueOf(value); } }, INTEGER { @Override Object convert(String value) { return Integer.valueOf(value); } }, BOOLEAN { @Override Object convert(String value) { return Boolean.valueOf(value); } }, STRING { @Override Object convert(String value) { return value; } }, STRING_SET { /** * Returns a Set of String values, parsed from the given value. * * @param value a comma separated list of values */ @Override Object convert(String value) { return Set.of(value.split(",")); } }, JSON_ARRAY { @Override Object convert(String value) { try (JsonReader reader = Json.createReader(new StringReader(value))) { return reader.readArray(); } } }, JSON_OBJECT { @Override Object convert(String value) { try (JsonReader reader = Json.createReader(new StringReader(value))) { return reader.readObject(); } } }, DEFAULT { @Override Object convert(String value) { return value; } }; abstract Object convert(String value); }
AttributeType
java
apache__camel
components/camel-kubernetes/src/main/java/org/apache/camel/component/openshift/deploymentconfigs/OpenshiftDeploymentConfigsComponent.java
{ "start": 1113, "end": 1433 }
class ____ extends AbstractKubernetesComponent { @Override protected OpenshiftDeploymentConfigsEndpoint doCreateEndpoint( String uri, String remaining, KubernetesConfiguration config) { return new OpenshiftDeploymentConfigsEndpoint(uri, this, config); } }
OpenshiftDeploymentConfigsComponent
java
redisson__redisson
redisson/src/main/java/org/redisson/client/protocol/CommandData.java
{ "start": 1085, "end": 3280 }
class ____<T, R> implements QueueCommand { final CompletableFuture<R> promise; RedisCommand<T> command; final Object[] params; final Codec codec; final MultiDecoder<Object> messageDecoder; public CommandData(CompletableFuture<R> promise, Codec codec, RedisCommand<T> command, Object[] params) { this(promise, null, codec, command, params); } public CommandData(CompletableFuture<R> promise, MultiDecoder<Object> messageDecoder, Codec codec, RedisCommand<T> command, Object[] params) { this.promise = promise; this.command = command; this.params = params; this.codec = codec; this.messageDecoder = messageDecoder; } public RedisCommand<T> getCommand() { return command; } public Object[] getParams() { return params; } public MultiDecoder<Object> getMessageDecoder() { return messageDecoder; } public CompletableFuture<R> getPromise() { return promise; } public Throwable cause() { try { promise.getNow(null); return null; } catch (CompletionException e) { return e.getCause(); } catch (CancellationException e) { return e; } } public boolean isSuccess() { return promise.isDone() && !promise.isCompletedExceptionally(); } public boolean tryFailure(Throwable cause) { return promise.completeExceptionally(cause); } public Codec getCodec() { return codec; } @Override public String toString() { return "CommandData [command=" + LogHelper.toString(this) + ", codec=" + codec + "]"; } @Override public List<CommandData<Object, Object>> getPubSubOperations() { if (RedisCommands.PUBSUB_COMMANDS.contains(getCommand().getName())) { return Collections.singletonList((CommandData<Object, Object>) this); } return Collections.emptyList(); } public boolean isBlockingCommand() { return command.isBlockingCommand(); } @Override public boolean isExecuted() { return promise.isDone(); } }
CommandData
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AtmosphereWebsocketEndpointBuilderFactory.java
{ "start": 36733, "end": 47330 }
interface ____ extends EndpointProducerBuilder { default AdvancedAtmosphereWebsocketEndpointProducerBuilder advanced() { return (AdvancedAtmosphereWebsocketEndpointProducerBuilder) this; } /** * If this option is false the Servlet will disable the HTTP streaming * and set the content-length header on the response. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common * * @param chunked the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder chunked(boolean chunked) { doSetProperty("chunked", chunked); return this; } /** * If this option is false the Servlet will disable the HTTP streaming * and set the content-length header on the response. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common * * @param chunked the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder chunked(String chunked) { doSetProperty("chunked", chunked); return this; } /** * Determines whether or not the raw input stream is cached or not. The * Camel consumer (camel-servlet, camel-jetty etc.) will by default * cache the input stream to support reading it multiple times to ensure * it Camel can retrieve all data from the stream. However you can set * this option to true when you for example need to access the raw * stream, such as streaming it directly to a file or other persistent * store. DefaultHttpBinding will copy the request input stream into a * stream cache and put it into message body if this option is false to * support reading the stream multiple times. If you use Servlet to * bridge/proxy an endpoint then consider enabling this option to * improve performance, in case you do not need to read the message * payload multiple times. The producer (camel-http) will by default * cache the response body stream. If setting this option to true, then * the producers will not cache the response body stream but use the * response stream as-is (the stream can only be read once) as the * message body. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param disableStreamCache the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder disableStreamCache(boolean disableStreamCache) { doSetProperty("disableStreamCache", disableStreamCache); return this; } /** * Determines whether or not the raw input stream is cached or not. The * Camel consumer (camel-servlet, camel-jetty etc.) will by default * cache the input stream to support reading it multiple times to ensure * it Camel can retrieve all data from the stream. However you can set * this option to true when you for example need to access the raw * stream, such as streaming it directly to a file or other persistent * store. DefaultHttpBinding will copy the request input stream into a * stream cache and put it into message body if this option is false to * support reading the stream multiple times. If you use Servlet to * bridge/proxy an endpoint then consider enabling this option to * improve performance, in case you do not need to read the message * payload multiple times. The producer (camel-http) will by default * cache the response body stream. If setting this option to true, then * the producers will not cache the response body stream but use the * response stream as-is (the stream can only be read once) as the * message body. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param disableStreamCache the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder disableStreamCache(String disableStreamCache) { doSetProperty("disableStreamCache", disableStreamCache); return this; } /** * Whether to send to all (broadcast) or send to a single receiver. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param sendToAll the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder sendToAll(boolean sendToAll) { doSetProperty("sendToAll", sendToAll); return this; } /** * Whether to send to all (broadcast) or send to a single receiver. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param sendToAll the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder sendToAll(String sendToAll) { doSetProperty("sendToAll", sendToAll); return this; } /** * If enabled and an Exchange failed processing on the consumer side, * and if the caused Exception was send back serialized in the response * as a application/x-java-serialized-object content type. On the * producer side the exception will be deserialized and thrown as is, * instead of the HttpOperationFailedException. The caused exception is * required to be serialized. This is by default turned off. If you * enable this then be aware that Java will deserialize the incoming * data from the request to Java and that can be a potential security * risk. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param transferException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder transferException(boolean transferException) { doSetProperty("transferException", transferException); return this; } /** * If enabled and an Exchange failed processing on the consumer side, * and if the caused Exception was send back serialized in the response * as a application/x-java-serialized-object content type. On the * producer side the exception will be deserialized and thrown as is, * instead of the HttpOperationFailedException. The caused exception is * required to be serialized. This is by default turned off. If you * enable this then be aware that Java will deserialize the incoming * data from the request to Java and that can be a potential security * risk. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param transferException the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder transferException(String transferException) { doSetProperty("transferException", transferException); return this; } /** * To enable streaming to send data as multiple text fragments. * * The option is a: <code>boolean</code> type. * * Default: false * Group: common * * @param useStreaming the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder useStreaming(boolean useStreaming) { doSetProperty("useStreaming", useStreaming); return this; } /** * To enable streaming to send data as multiple text fragments. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: common * * @param useStreaming the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder useStreaming(String useStreaming) { doSetProperty("useStreaming", useStreaming); return this; } /** * If the option is true, HttpProducer will ignore the Exchange.HTTP_URI * header, and use the endpoint's URI for request. You may also set the * option throwExceptionOnFailure to be false to let the HttpProducer * send all the fault response back. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer * * @param bridgeEndpoint the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder bridgeEndpoint(boolean bridgeEndpoint) { doSetProperty("bridgeEndpoint", bridgeEndpoint); return this; } /** * If the option is true, HttpProducer will ignore the Exchange.HTTP_URI * header, and use the endpoint's URI for request. You may also set the * option throwExceptionOnFailure to be false to let the HttpProducer * send all the fault response back. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer * * @param bridgeEndpoint the value to set * @return the dsl builder */ default AtmosphereWebsocketEndpointProducerBuilder bridgeEndpoint(String bridgeEndpoint) { doSetProperty("bridgeEndpoint", bridgeEndpoint); return this; } } /** * Advanced builder for endpoint producers for the Atmosphere Websocket component. */ public
AtmosphereWebsocketEndpointProducerBuilder
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/lookup/JndiRestrictedLookupTest.java
{ "start": 4671, "end": 5177 }
class ____ implements Referenceable { String fruit; public Fruit(final String f) { fruit = f; } public Reference getReference() { return new Reference( Fruit.class.getName(), new StringRefAddr("fruit", fruit), JndiExploit.class.getName(), null); // factory location } public String toString() { return fruit; } } static
Fruit
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/id/IntegralDataTypeHolder.java
{ "start": 414, "end": 5157 }
interface ____ extends Serializable { /** * Initialize the internal value from the given primitive long. * * @param value The primitive integral value. * * @return {@code this}, for method chaining */ IntegralDataTypeHolder initialize(long value); /** * Initialize the internal value from the given result set, using the specified default value * if we could not get a value from the result set (aka result was null). * * @param resultSet The JDBC result set * @param defaultValue The default value to use if we did not get a result set value. * * @return {@code this}, for method chaining * * @throws SQLException Any exception from accessing the result set */ IntegralDataTypeHolder initialize(ResultSet resultSet, long defaultValue) throws SQLException; /** * Bind this holder's internal value to the given result set. * * @param preparedStatement The JDBC prepared statement * @param position The position at which to bind * * @throws SQLException Any exception from accessing the statement */ void bind(PreparedStatement preparedStatement, int position) throws SQLException; /** * Equivalent to a ++ operation * * @return {@code this}, for method chaining */ IntegralDataTypeHolder increment(); /** * Perform an addition * * @param addend The value to add to this integral. * * @return {@code this}, for method chaining */ IntegralDataTypeHolder add(long addend); /** * Equivalent to a -- operation * * @return {@code this}, for method chaining */ IntegralDataTypeHolder decrement(); /** * Perform a subtraction * * @param subtrahend The value to subtract from this integral. * * @return {@code this}, for method chaining */ IntegralDataTypeHolder subtract(long subtrahend); /** * Perform a multiplication. * * @param factor The factor by which to multiple this integral * * @return {@code this}, for method chaining */ IntegralDataTypeHolder multiplyBy(IntegralDataTypeHolder factor); /** * Perform a multiplication. * * @param factor The factor by which to multiple this integral * * @return {@code this}, for method chaining */ IntegralDataTypeHolder multiplyBy(long factor); /** * Perform an equality comparison check * * @param other The other value to check against our internal state * * @return True if the two are equal */ boolean eq(IntegralDataTypeHolder other); /** * Perform an equality comparison check * * @param other The other value to check against our internal state * * @return True if the two are equal */ boolean eq(long other); /** * Perform a "less than" comparison check. We check to see if our value is less than * the incoming value... * * @param other The other value to check against our internal state * * @return True if our value is less than the 'other' value. */ boolean lt(IntegralDataTypeHolder other); /** * Perform a "less than" comparison check. We check to see if our value is less than * the incoming value... * * @param other The other value to check against our internal state * * @return True if our value is less than the 'other' value. */ boolean lt(long other); /** * Perform a "greater than" comparison check. We check to see if our value is greater * than the incoming value... * * @param other The other value to check against our internal state * * @return True if our value is greater than the 'other' value. */ boolean gt(IntegralDataTypeHolder other); /** * Perform a "greater than" comparison check. We check to see if our value is greater * than the incoming value... * * @param other The other value to check against our internal state * * @return True if our value is greater than the 'other' value. */ boolean gt(long other); /** * Make a copy of this holder. * * @return The copy. */ IntegralDataTypeHolder copy(); /** * Return the internal value. * * @return The current internal value */ Number makeValue(); /** * Increment the internal state, but return the pre-incremented value. * * @return The pre-incremented internal value */ Number makeValueThenIncrement(); /** * Increment the internal state by the given addend, but return the pre-incremented value. * * @param addend The value to be added to our internal state * * @return The pre-incremented internal value */ Number makeValueThenAdd(long addend); /** * Convert the internal value to {@code long}. */ long toLong(); /** * Convert the internal value to {@link BigInteger}. */ BigInteger toBigInteger(); /** * Convert the internal value to {@link BigDecimal}. */ BigDecimal toBigDecimal(); }
IntegralDataTypeHolder
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/support/MutableSortDefinition.java
{ "start": 1095, "end": 5086 }
class ____ implements SortDefinition, Serializable { private String property = ""; private boolean ignoreCase = true; private boolean ascending = true; private boolean toggleAscendingOnProperty = false; /** * Create an empty MutableSortDefinition, * to be populated via its bean properties. * @see #setProperty * @see #setIgnoreCase * @see #setAscending */ public MutableSortDefinition() { } /** * Copy constructor: create a new MutableSortDefinition * that mirrors the given sort definition. * @param source the original sort definition */ public MutableSortDefinition(SortDefinition source) { this.property = source.getProperty(); this.ignoreCase = source.isIgnoreCase(); this.ascending = source.isAscending(); } /** * Create a MutableSortDefinition for the given settings. * @param property the property to compare * @param ignoreCase whether upper and lower case in String values should be ignored * @param ascending whether to sort ascending (true) or descending (false) */ public MutableSortDefinition(String property, boolean ignoreCase, boolean ascending) { this.property = property; this.ignoreCase = ignoreCase; this.ascending = ascending; } /** * Create a new MutableSortDefinition. * @param toggleAscendingOnSameProperty whether to toggle the ascending flag * if the same property gets set again (that is, {@code setProperty} gets * called with already set property name again). */ public MutableSortDefinition(boolean toggleAscendingOnSameProperty) { this.toggleAscendingOnProperty = toggleAscendingOnSameProperty; } /** * Set the property to compare. * <p>If the property was the same as the current, the sort is reversed if * "toggleAscendingOnProperty" is activated, else simply ignored. * @see #setToggleAscendingOnProperty */ public void setProperty(String property) { if (!StringUtils.hasLength(property)) { this.property = ""; } else { // Implicit toggling of ascending? if (isToggleAscendingOnProperty()) { this.ascending = (!property.equals(this.property) || !this.ascending); } this.property = property; } } @Override public String getProperty() { return this.property; } /** * Set whether upper and lower case in String values should be ignored. */ public void setIgnoreCase(boolean ignoreCase) { this.ignoreCase = ignoreCase; } @Override public boolean isIgnoreCase() { return this.ignoreCase; } /** * Set whether to sort ascending (true) or descending (false). */ public void setAscending(boolean ascending) { this.ascending = ascending; } @Override public boolean isAscending() { return this.ascending; } /** * Set whether to toggle the ascending flag if the same property gets set again * (that is, {@link #setProperty} gets called with already set property name again). * <p>This is particularly useful for parameter binding through a web request, * where clicking on the field header again might be supposed to trigger a * resort for the same field but opposite order. */ public void setToggleAscendingOnProperty(boolean toggleAscendingOnProperty) { this.toggleAscendingOnProperty = toggleAscendingOnProperty; } /** * Return whether to toggle the ascending flag if the same property gets set again * (that is, {@code setProperty} gets called with already set property name again). */ public boolean isToggleAscendingOnProperty() { return this.toggleAscendingOnProperty; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof SortDefinition that && getProperty().equals(that.getProperty()) && isAscending() == that.isAscending() && isIgnoreCase() == that.isIgnoreCase())); } @Override public int hashCode() { int hashCode = getProperty().hashCode(); hashCode = 29 * hashCode + (isIgnoreCase() ? 1 : 0); hashCode = 29 * hashCode + (isAscending() ? 1 : 0); return hashCode; } }
MutableSortDefinition
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrar.java
{ "start": 4505, "end": 5457 }
class ____ implements Filter { private static final int METHOD_NOT_ALLOWED = 405; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest httpRequest && response instanceof HttpServletResponse httpResponse) { doFilter(httpRequest, httpResponse, chain); } else { throw new ServletException(); } } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (isReadOnlyAccessMethod(request)) { chain.doFilter(request, response); } else { response.sendError(METHOD_NOT_ALLOWED); } } private boolean isReadOnlyAccessMethod(HttpServletRequest request) { return READ_ONLY_ACCESS_REQUEST_METHODS.contains(request.getMethod().toUpperCase(Locale.ROOT)); } } }
ReadOnlyAccessFilter
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/io/schubfach/FloatToDecimal.java
{ "start": 1808, "end": 19721 }
class ____ { /* For full details about this code see the following references: [1] Giulietti, "The Schubfach way to render doubles", https://drive.google.com/open?id=1luHhyQF9zKlM8yJ1nebU0OgVYhfC6CBN [2] IEEE Computer Society, "IEEE Standard for Floating-Point Arithmetic" [3] Bouvier & Zimmermann, "Division-Free Binary-to-Decimal Conversion" Divisions are avoided altogether for the benefit of those architectures that do not provide specific machine instructions or where they are slow. This is discussed in section 10 of [1]. */ // Sources with the license are here: https://github.com/c4f7fcce9cb06515/Schubfach/blob/3c92d3c9b1fead540616c918cdfef432bca53dfa/todec/src/math/FloatToDecimal.java // The precision in bits. public static final int P = 24; // Exponent width in bits. private static final int W = (Float.SIZE - 1) - (P - 1); // Minimum value of the exponent: -(2^(W-1)) - P + 3. public static final int Q_MIN = (-1 << W - 1) - P + 3; // Maximum value of the exponent: 2^(W-1) - P. public static final int Q_MAX = (1 << W - 1) - P; // 10^(E_MIN - 1) <= MIN_VALUE < 10^E_MIN public static final int E_MIN = -44; // 10^(E_MAX - 1) <= MAX_VALUE < 10^E_MAX public static final int E_MAX = 39; // Threshold to detect tiny values, as in section 8.1.1 of [1] public static final int C_TINY = 8; // The minimum and maximum k, as in section 8 of [1] public static final int K_MIN = -45; public static final int K_MAX = 31; // H is as in section 8 of [1]. public static final int H = 9; // Minimum value of the significand of a normal value: 2^(P-1). private static final int C_MIN = 1 << P - 1; // Mask to extract the biased exponent. private static final int BQ_MASK = (1 << W) - 1; // Mask to extract the fraction bits. private static final int T_MASK = (1 << P - 1) - 1; // Used in rop(). private static final long MASK_32 = (1L << 32) - 1; // Used for left-to-tight digit extraction. private static final int MASK_28 = (1 << 28) - 1; private static final int NON_SPECIAL = 0; private static final int PLUS_ZERO = 1; private static final int MINUS_ZERO = 2; private static final int PLUS_INF = 3; private static final int MINUS_INF = 4; private static final int NAN = 5; /* Room for the longer of the forms -ddddd.dddd H + 2 characters -0.00ddddddddd H + 5 characters -d.ddddddddE-ee H + 6 characters where there are H digits d */ public final int MAX_CHARS = H + 6; // Numerical results are created here... private final byte[] bytes = new byte[MAX_CHARS]; // Index into buf of rightmost valid character. private int index; private FloatToDecimal() { } /** * Returns a string rendering of the {@code float} argument. * * <p>The characters of the result are all drawn from the ASCII set. * <ul> * <li> Any NaN, whether quiet or signaling, is rendered as * {@code "NaN"}, regardless of the sign bit. * <li> The infinities +&infin; and -&infin; are rendered as * {@code "Infinity"} and {@code "-Infinity"}, respectively. * <li> The positive and negative zeroes are rendered as * {@code "0.0"} and {@code "-0.0"}, respectively. * <li> A finite negative {@code v} is rendered as the sign * '{@code -}' followed by the rendering of the magnitude -{@code v}. * <li> A finite positive {@code v} is rendered in two stages: * <ul> * <li> <em>Selection of a decimal</em>: A well-defined * decimal <i>d</i><sub><code>v</code></sub> is selected * to represent {@code v}. * <li> <em>Formatting as a string</em>: The decimal * <i>d</i><sub><code>v</code></sub> is formatted as a string, * either in plain or in computerized scientific notation, * depending on its value. * </ul> * </ul> * * <p>A <em>decimal</em> is a number of the form * <i>d</i>&times;10<sup><i>i</i></sup> * for some (unique) integers <i>d</i> &gt; 0 and <i>i</i> such that * <i>d</i> is not a multiple of 10. * These integers are the <em>significand</em> and * the <em>exponent</em>, respectively, of the decimal. * The <em>length</em> of the decimal is the (unique) * integer <i>n</i> meeting * 10<sup><i>n</i>-1</sup> &le; <i>d</i> &lt; 10<sup><i>n</i></sup>. * * <p>The decimal <i>d</i><sub><code>v</code></sub> * for a finite positive {@code v} is defined as follows: * <ul> * <li>Let <i>R</i> be the set of all decimals that round to {@code v} * according to the usual round-to-closest rule of * IEEE 754 floating-point arithmetic. * <li>Let <i>m</i> be the minimal length over all decimals in <i>R</i>. * <li>When <i>m</i> &ge; 2, let <i>T</i> be the set of all decimals * in <i>R</i> with length <i>m</i>. * Otherwise, let <i>T</i> be the set of all decimals * in <i>R</i> with length 1 or 2. * <li>Define <i>d</i><sub><code>v</code></sub> as * the decimal in <i>T</i> that is closest to {@code v}. * Or if there are two such decimals in <i>T</i>, * select the one with the even significand (there is exactly one). * </ul> * * <p>The (uniquely) selected decimal <i>d</i><sub><code>v</code></sub> * is then formatted. * * <p>Let <i>d</i>, <i>i</i> and <i>n</i> be the significand, exponent and * length of <i>d</i><sub><code>v</code></sub>, respectively. * Further, let <i>e</i> = <i>n</i> + <i>i</i> - 1 and let * <i>d</i><sub>1</sub>&hellip;<i>d</i><sub><i>n</i></sub> * be the usual decimal expansion of the significand. * Note that <i>d</i><sub>1</sub> &ne; 0 &ne; <i>d</i><sub><i>n</i></sub>. * <ul> * <li>Case -3 &le; <i>e</i> &lt; 0: * <i>d</i><sub><code>v</code></sub> is formatted as * <code>0.0</code>&hellip;<code>0</code><!-- * --><i>d</i><sub>1</sub>&hellip;<i>d</i><sub><i>n</i></sub>, * where there are exactly -(<i>n</i> + <i>i</i>) zeroes between * the decimal point and <i>d</i><sub>1</sub>. * For example, 123 &times; 10<sup>-4</sup> is formatted as * {@code 0.0123}. * <li>Case 0 &le; <i>e</i> &lt; 7: * <ul> * <li>Subcase <i>i</i> &ge; 0: * <i>d</i><sub><code>v</code></sub> is formatted as * <i>d</i><sub>1</sub>&hellip;<i>d</i><sub><i>n</i></sub><!-- * --><code>0</code>&hellip;<code>0.0</code>, * where there are exactly <i>i</i> zeroes * between <i>d</i><sub><i>n</i></sub> and the decimal point. * For example, 123 &times; 10<sup>2</sup> is formatted as * {@code 12300.0}. * <li>Subcase <i>i</i> &lt; 0: * <i>d</i><sub><code>v</code></sub> is formatted as * <i>d</i><sub>1</sub>&hellip;<!-- * --><i>d</i><sub><i>n</i>+<i>i</i></sub>.<!-- * --><i>d</i><sub><i>n</i>+<i>i</i>+1</sub>&hellip;<!-- * --><i>d</i><sub><i>n</i></sub>. * There are exactly -<i>i</i> digits to the right of * the decimal point. * For example, 123 &times; 10<sup>-1</sup> is formatted as * {@code 12.3}. * </ul> * <li>Case <i>e</i> &lt; -3 or <i>e</i> &ge; 7: * computerized scientific notation is used to format * <i>d</i><sub><code>v</code></sub>. * Here <i>e</i> is formatted as by {@link Integer#toString(int)}. * <ul> * <li>Subcase <i>n</i> = 1: * <i>d</i><sub><code>v</code></sub> is formatted as * <i>d</i><sub>1</sub><code>.0E</code><i>e</i>. * For example, 1 &times; 10<sup>23</sup> is formatted as * {@code 1.0E23}. * <li>Subcase <i>n</i> &gt; 1: * <i>d</i><sub><code>v</code></sub> is formatted as * <i>d</i><sub>1</sub><code>.</code><i>d</i><sub>2</sub><!-- * -->&hellip;<i>d</i><sub><i>n</i></sub><code>E</code><i>e</i>. * For example, 123 &times; 10<sup>-21</sup> is formatted as * {@code 1.23E-19}. * </ul> * </ul> * * @param v the {@code float} to be rendered. * @return a string rendering of the argument. */ public static String toString(float v) { return new FloatToDecimal().toDecimalString(v); } private String toDecimalString(float v) { switch (toDecimal(v)) { case NON_SPECIAL: return charsToString(); case PLUS_ZERO: return "0.0"; case MINUS_ZERO: return "-0.0"; case PLUS_INF: return "Infinity"; case MINUS_INF: return "-Infinity"; default: return "NaN"; } } /* Returns PLUS_ZERO iff v is 0.0 MINUS_ZERO iff v is -0.0 PLUS_INF iff v is POSITIVE_INFINITY MINUS_INF iff v is NEGATIVE_INFINITY NAN iff v is NaN */ private int toDecimal(float v) { /* For full details see references [2] and [1]. For finite v != 0, determine integers c and q such that |v| = c 2^q and Q_MIN <= q <= Q_MAX and either 2^(P-1) <= c < 2^P (normal) or 0 < c < 2^(P-1) and q = Q_MIN (subnormal) */ int bits = floatToRawIntBits(v); int t = bits & T_MASK; int bq = (bits >>> P - 1) & BQ_MASK; if (bq < BQ_MASK) { index = -1; if (bits < 0) { append('-'); } if (bq != 0) { // normal value. Here mq = -q int mq = -Q_MIN + 1 - bq; int c = C_MIN | t; // The fast path discussed in section 8.2 of [1]. if (0 < mq & mq < P) { int f = c >> mq; if (f << mq == c) { return toChars(f, 0); } } return toDecimal(-mq, c, 0); } if (t != 0) { // subnormal value return t < C_TINY ? toDecimal(Q_MIN, 10 * t, -1) : toDecimal(Q_MIN, t, 0); } return bits == 0 ? PLUS_ZERO : MINUS_ZERO; } if (t != 0) { return NAN; } return bits > 0 ? PLUS_INF : MINUS_INF; } private int toDecimal(int q, int c, int dk) { /* The skeleton corresponds to figure 4 of [1]. The efficient computations are those summarized in figure 7. Also check the appendix. Here's a correspondence between Java names and names in [1], expressed as approximate LaTeX source code and informally. Other names are identical. cb: \bar{c} "c-bar" cbr: \bar{c}_r "c-bar-r" cbl: \bar{c}_l "c-bar-l" vb: \bar{v} "v-bar" vbr: \bar{v}_r "v-bar-r" vbl: \bar{v}_l "v-bar-l" rop: r_o' "r-o-prime" */ int out = c & 0x1; long cb = c << 2; long cbr = cb + 2; long cbl; int k; /* flog10pow2(e) = floor(log_10(2^e)) flog10threeQuartersPow2(e) = floor(log_10(3/4 2^e)) flog2pow10(e) = floor(log_2(10^e)) */ if (c != C_MIN | q == Q_MIN) { // regular spacing cbl = cb - 2; k = flog10pow2(q); } else { // irregular spacing0 cbl = cb - 1; k = flog10threeQuartersPow2(q); } int h = q + flog2pow10(-k) + 33; // g is as in the appendix long g = g1(k) + 1; int vb = rop(g, cb << h); int vbl = rop(g, cbl << h); int vbr = rop(g, cbr << h); int s = vb >> 2; if (s >= 100) { /* For n = 9, m = 1 the table in section 10 of [1] shows s' = floor(s / 10) = floor(s 1_717_986_919 / 2^34) sp10 = 10 s' tp10 = 10 t' upin iff u' = sp10 10^k in Rv wpin iff w' = tp10 10^k in Rv See section 9.4 of [1]. */ int sp10 = 10 * (int) (s * 1_717_986_919L >>> 34); int tp10 = sp10 + 10; boolean upin = vbl + out <= sp10 << 2; boolean wpin = (tp10 << 2) + out <= vbr; if (upin != wpin) { return toChars(upin ? sp10 : tp10, k); } } /* 10 <= s < 100 or s >= 100 and u', w' not in Rv uin iff u = s 10^k in Rv win iff w = t 10^k in Rv See section 9.4 of [1]. */ int t = s + 1; boolean uin = vbl + out <= s << 2; boolean win = (t << 2) + out <= vbr; if (uin != win) { // Exactly one of u or w lies in Rv. return toChars(uin ? s : t, k + dk); } /* Both u and w lie in Rv: determine the one closest to v. See section 9.4 of [1]. */ int cmp = vb - (s + t << 1); return toChars(cmp < 0 || cmp == 0 && (s & 0x1) == 0 ? s : t, k + dk); } /* Computes rop(cp g 2^(-95)) See appendix and figure 8 of [1]. */ private static int rop(long g, long cp) { long x1 = multiplyHigh(g, cp); long vbp = x1 >>> 31; return (int) (vbp | (x1 & MASK_32) + MASK_32 >>> 32); } /* Formats the decimal f 10^e. */ private int toChars(int f, int e) { /* For details not discussed here see section 10 of [1]. Determine len such that 10^(len-1) <= f < 10^len */ int len = flog10pow2(Integer.SIZE - numberOfLeadingZeros(f)); if (f >= pow10(len)) { len += 1; } /* Let fp and ep be the original f and e, respectively. Transform f and e to ensure 10^(H-1) <= f < 10^H fp 10^ep = f 10^(e-H) = 0.f 10^e */ f *= pow10(H - len); e += len; /* The toChars?() methods perform left-to-right digits extraction using ints, provided that the arguments are limited to 8 digits. Therefore, split the H = 9 digits of f into: h = the most significant digit of f l = the last 8, least significant digits of f For n = 9, m = 8 the table in section 10 of [1] shows floor(f / 10^8) = floor(1_441_151_881 f / 2^57) */ int h = (int) (f * 1_441_151_881L >>> 57); int l = f - 100_000_000 * h; if (0 < e && e <= 7) { return toChars1(h, l, e); } if (-3 < e && e <= 0) { return toChars2(h, l, e); } return toChars3(h, l, e); } private int toChars1(int h, int l, int e) { /* 0 < e <= 7: plain format without leading zeroes. Left-to-right digits extraction: algorithm 1 in [3], with b = 10, k = 8, n = 28. */ appendDigit(h); int y = y(l); int t; int i = 1; for (; i < e; ++i) { t = 10 * y; appendDigit(t >>> 28); y = t & MASK_28; } append('.'); for (; i <= 8; ++i) { t = 10 * y; appendDigit(t >>> 28); y = t & MASK_28; } removeTrailingZeroes(); return NON_SPECIAL; } private int toChars2(int h, int l, int e) { // -3 < e <= 0: plain format with leading zeroes. appendDigit(0); append('.'); for (; e < 0; ++e) { appendDigit(0); } appendDigit(h); append8Digits(l); removeTrailingZeroes(); return NON_SPECIAL; } private int toChars3(int h, int l, int e) { // -3 >= e | e > 7: computerized scientific notation appendDigit(h); append('.'); append8Digits(l); removeTrailingZeroes(); exponent(e - 1); return NON_SPECIAL; } private void append8Digits(int m) { /* Left-to-right digits extraction: algorithm 1 in [3], with b = 10, k = 8, n = 28. */ int y = y(m); for (int i = 0; i < 8; ++i) { int t = 10 * y; appendDigit(t >>> 28); y = t & MASK_28; } } private void removeTrailingZeroes() { while (bytes[index] == '0') { --index; } // ... but do not remove the one directly to the right of '.' if (bytes[index] == '.') { ++index; } } private int y(int a) { /* Algorithm 1 in [3] needs computation of floor((a + 1) 2^n / b^k) - 1 with a < 10^8, b = 10, k = 8, n = 28. Noting that (a + 1) 2^n <= 10^8 2^28 < 10^17 For n = 17, m = 8 the table in section 10 of [1] leads to: */ return (int) (multiplyHigh( (long) (a + 1) << 28, 193_428_131_138_340_668L) >>> 20) - 1; } private void exponent(int e) { append('E'); if (e < 0) { append('-'); e = -e; } if (e < 10) { appendDigit(e); return; } /* For n = 2, m = 1 the table in section 10 of [1] shows floor(e / 10) = floor(103 e / 2^10) */ int d = e * 103 >>> 10; appendDigit(d); appendDigit(e - 10 * d); } private void append(int c) { bytes[++index] = (byte) c; } private void appendDigit(int d) { bytes[++index] = (byte) ('0' + d); } // Using the deprecated constructor enhances performance. @SuppressWarnings("deprecation") private String charsToString() { return new String(bytes, 0, 0, index + 1); } }
FloatToDecimal
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/SftpPublicKeyAcceptedAlgorithmsIT.java
{ "start": 1184, "end": 2810 }
class ____ extends SftpServerTestSupport { @Test public void testSingleKey() throws Exception { final MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBodyAndHeader("sftp://admin@localhost:{{ftp.server.port}}/{{ftp.root.dir}}/publicKeyAcceptedAlgorithms" + "?password=admin" + "&publicKeyAcceptedAlgorithms=rsa-sha2-512", "a", Exchange.FILE_NAME, "a.txt"); mock.assertIsSatisfied(); } @Test public void testMultipleKey() throws Exception { final MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBodyAndHeader("sftp://admin@localhost:{{ftp.server.port}}/{{ftp.root.dir}}/publicKeyAcceptedAlgorithms" + "?password=admin" + "&publicKeyAcceptedAlgorithms=rsa-sha2-512,not-supported-key", "a", Exchange.FILE_NAME, "a.txt"); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(getFtpUrl()).routeId("myRoute").to("mock:result"); } }; } protected String getFtpUrl() { return "sftp://admin@localhost:{{ftp.server.port}}/{{ftp.root.dir}}/publicKeyAcceptedAlgorithms/?password=admin" + "&noop=true"; } }
SftpPublicKeyAcceptedAlgorithmsIT
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/diff/ChangeDelta.java
{ "start": 1029, "end": 2145 }
class ____<T> extends Delta<T> { /** * Creates a change delta with the two given chunks. * @param original The original chunk. Must not be {@code null}. * @param revised The original chunk. Must not be {@code null}. */ public ChangeDelta(Chunk<T> original, Chunk<T> revised) { super(original, revised); } /** * {@inheritDoc} */ @Override public void applyTo(List<T> target) throws IllegalStateException { verify(target); int position = getOriginal().getPosition(); int size = getOriginal().size(); for (int i = 0; i < size; i++) { target.remove(position); } int i = 0; for (T line : getRevised().getLines()) { target.add(position + i, line); i++; } } /** * {@inheritDoc} */ @Override public void verify(List<T> target) throws IllegalStateException { getOriginal().verify(target); checkState(getOriginal().getPosition() <= target.size(), "Incorrect patch for delta: delta original position > target size"); } @Override public TYPE getType() { return Delta.TYPE.CHANGE; } }
ChangeDelta
java
apache__spark
sql/hive/src/test/java/org/apache/spark/sql/hive/execution/UDFToIntIntMap.java
{ "start": 948, "end": 1166 }
class ____ extends UDF { public Map<Integer, Integer> evaluate(Object o) { return new HashMap<Integer, Integer>() { { put(1, 1); put(2, 1); put(3, 1); } }; } }
UDFToIntIntMap
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/jaxrs/LocationUtil.java
{ "start": 450, "end": 2783 }
class ____ { static URI determineLocation(URI location) { if (!location.isAbsolute()) { // FIXME: this leaks server stuff onto the client ResteasyReactiveRequestContext request = CurrentRequestManager.get(); if (request != null) { location = getUri(location.toString(), request, true); } } return location; } static URI getUri(String path, ResteasyReactiveRequestContext request, boolean usePrefix) { try { String prefix = usePrefix ? determinePrefix(request.serverRequest(), request.getDeployment()) : ""; // Spec says relative to request, but TCK tests relative to Base URI, so we do that if (!path.startsWith("/")) { path = "/" + path; } return new URI(request.getScheme(), request.getAuthority(), null, null, null).resolve(prefix + path); } catch (URISyntaxException e) { throw new RuntimeException(e); } } private static String determinePrefix(ServerHttpRequest serverHttpRequest, Deployment deployment) { String prefix = ""; if (deployment != null) { // prefix is already sanitised prefix = deployment.getPrefix(); } ForwardedInfo forwardedInfo = serverHttpRequest.getForwardedInfo(); if (forwardedInfo != null) { if ((forwardedInfo.getPrefix() != null) && !forwardedInfo.getPrefix().isEmpty()) { String forwardedPrefix = forwardedInfo.getPrefix(); if (!forwardedPrefix.startsWith("/")) { forwardedPrefix = "/" + forwardedPrefix; } prefix = forwardedPrefix + prefix; } } if (prefix.endsWith("/")) { prefix = prefix.substring(0, prefix.length() - 1); } return prefix; } static URI determineContentLocation(URI location) { if (!location.isAbsolute()) { ResteasyReactiveRequestContext request = CurrentRequestManager.get(); if (request != null) { // FIXME: this leaks server stuff onto the client location = getUri(location.toString(), request, false); } } return location; } }
LocationUtil
java
elastic__elasticsearch
x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/cluster/metadata/MetadataMigrateToDataTiersRoutingService.java
{ "start": 3548, "end": 49716 }
class ____ { public static final String DEFAULT_NODE_ATTRIBUTE_NAME = "data"; private static final Logger logger = LogManager.getLogger(MetadataMigrateToDataTiersRoutingService.class); private MetadataMigrateToDataTiersRoutingService() {} /** * Migrates the elasticsearch abstractions to use data tiers for allocation routing. * This will: * - remove the given V1 index template if it exists. * * - loop through the existing ILM policies and look at the configured {@link AllocateAction}s. If they define *any* routing rules * based on the provided node attribute name (we look at include, exclude, and require rules) *ALL* the rules in the allocate action * will be removed. All the rules are removed in order to allow for ILM to inject the {@link MigrateAction}. * So for eg. this action: * allocate { * number_of_replicas: 0, * require: {data: warm}, * include: {rack: one} * } * will become * allocate { * number_of_replicas: 0 * } * Note that if the `allocate` action doesn't define any `number_of_replicas` it will be removed completely from the migrated policy. * As part of migrating the ILM policies we also update the cached phase definition for the managed indices to reflect the migrated * policy phase. * * - loop through all the indices convert the index.routing.allocation.require.{nodeAttrName} or * index.routing.allocation.include.{nodeAttrName} setting (if present) to the corresponding data tier `_tier_preference` routing. * We are only able to convert the `frozen`, `cold`, `warm`, or `hot` setting values to the `_tier_preference`. If other * configuration values are present eg ("the_warm_nodes") the index will not be migrated. * If the require or include setting is successfully migrated to _tier_preference, all the **other** routing settings for the * provided attribute are also removed (if present). * Eg. if we manage to migrate the `index.routing.allocation.require.data` setting, but the index also has configured * `index.routing.allocation.include.data` and `index.routing.allocation.exclude.data`, the * migrated settings will contain `index.routing.allocation.include._tier_preference` configured to the corresponding * `index.routing.allocation.require.data` value, with `index.routing.allocation.include.data` and * `index.routing.allocation.exclude.data` being removed. * Settings: * { * index.routing.allocation.require.data: "warm", * index.routing.allocation.include.data: "rack1", * index.routing.allocation.exclude.data: "rack2,rack3" * } * will be migrated to: * { * index.routing.allocation.include._tier_preference: "data_warm,data_hot" * } * * If both the `index.routing.allocation.require.data` and `index.routing.allocation.include.data` settings are configured to * recognized values the coldest one will be converted to the corresponding `_tier_preference` configuration. * Eg. the following configuration: * { * index.routing.allocation.require.data: "warm", * index.routing.allocation.include.data: "cold", * index.routing.allocation.exclude.data: "rack2,rack3" * } * will be migrated to: * { * index.routing.allocation.include._tier_preference: "data_cold,data_warm,data_hot" * } * * - loop through the existing legacy, composable, and component templates and remove all the custom attribute routing settings for * the configured @param nodeAttrName, if any of the index.routing.allocation.require.{nodeAttrName} or index.routing.allocation * .include.{nodeAttrName} settings are presents in the template (irrespective of what they are configured to, we do not inspect the * values in this case). * Eg. this legacy template: * { * "order": 0, * "index_patterns": [ * "*" * ], * "settings": { * "index": { * "routing": { * "allocation": { * "require": { * "data": "hot" * }, * "include": { * "data": "rack1" * }, * "exclude": { * "data": "bad_rack" * } * } * } * } * }, * "mappings": {}, * "aliases": {} * } * will be migrated to * { * "order": 0, * "index_patterns": [ * "*" * ], * "settings": {}, * "mappings": {}, * "aliases": {} * } * * Same pattern applies to composable and component templates. * * If no @param nodeAttrName is provided "data" will be used. * If no @param indexTemplateToDelete is provided, no index templates will be deleted. * * This returns a new {@link ClusterState} representing the migrated state that is ready to use data tiers for index and * ILM routing allocations. It also returns a summary of the affected abstractions encapsulated in {@link MigratedEntities} */ public static Tuple<ClusterState, MigratedEntities> migrateToDataTiersRouting( ProjectState currentState, @Nullable String nodeAttrName, @Nullable String indexTemplateToDelete, NamedXContentRegistry xContentRegistry, Client client, XPackLicenseState licenseState, boolean dryRun ) { ProjectMetadata currentProjectMetadata = currentState.metadata(); if (dryRun == false) { IndexLifecycleMetadata currentMetadata = currentProjectMetadata.custom(IndexLifecycleMetadata.TYPE); if (currentMetadata != null && currentILMMode(currentProjectMetadata) != STOPPED) { throw new IllegalStateException( "stop ILM before migrating to data tiers, current state is [" + currentILMMode(currentProjectMetadata) + "]" ); } } @NotMultiProjectCapable // We're doing something fishy here by updating the Metadata even though we're inside the scope of a single // project. This is generally not correct, but since ILM is not properly project-aware, we're making an exception here. Metadata.Builder mb = Metadata.builder(currentState.cluster().metadata()); ProjectMetadata.Builder newProjectMetadataBuilder = ProjectMetadata.builder(currentProjectMetadata); // remove ENFORCE_DEFAULT_TIER_PREFERENCE from the persistent settings Settings.Builder persistentSettingsBuilder = Settings.builder().put(mb.persistentSettings()); persistentSettingsBuilder.remove(ENFORCE_DEFAULT_TIER_PREFERENCE); mb.persistentSettings(persistentSettingsBuilder.build()); // and remove it from the transient settings, just in case it was there Settings.Builder transientSettingsBuilder = Settings.builder().put(mb.transientSettings()); transientSettingsBuilder.remove(ENFORCE_DEFAULT_TIER_PREFERENCE); mb.transientSettings(transientSettingsBuilder.build()); String removedIndexTemplateName = null; if (Strings.hasText(indexTemplateToDelete)) { if (currentProjectMetadata.templates().containsKey(indexTemplateToDelete)) { newProjectMetadataBuilder.removeTemplate(indexTemplateToDelete); logger.debug("removing legacy template [{}]", indexTemplateToDelete); removedIndexTemplateName = indexTemplateToDelete; } else { logger.debug("legacy template [{}] does not exist", indexTemplateToDelete); } } String attribute = nodeAttrName; if (Strings.isNullOrEmpty(nodeAttrName)) { attribute = DEFAULT_NODE_ATTRIBUTE_NAME; } List<String> migratedPolicies = migrateIlmPolicies( newProjectMetadataBuilder, currentProjectMetadata, attribute, xContentRegistry, client, licenseState ); // Creating an intermediary project metadata as when migrating policy we also update the cached phase definition stored in the // index metadata so the ProjectMetadata.Builder will probably contain an already updated view over the indices metadata which we // don't want to lose when migrating the index settings ProjectMetadata intermediateProjectMetadata = newProjectMetadataBuilder.build(); newProjectMetadataBuilder = ProjectMetadata.builder(intermediateProjectMetadata); List<String> migratedIndices = migrateIndices(newProjectMetadataBuilder, intermediateProjectMetadata, attribute); MigratedTemplates migratedTemplates = migrateIndexAndComponentTemplates( newProjectMetadataBuilder, intermediateProjectMetadata, attribute ); return Tuple.tuple( ClusterState.builder(currentState.cluster()).metadata(mb).putProjectMetadata(newProjectMetadataBuilder).build(), new MigratedEntities(removedIndexTemplateName, migratedIndices, migratedPolicies, migratedTemplates) ); } /** * Iterate through the existing ILM policies and look at the configured {@link AllocateAction}s. If they define *any* routing rules * based on the provided node attribute name (we look at include, exclude, and require rules) *ALL* the rules in the allocate * action will be removed. All the rules are removed in order to allow for ILM to inject the {@link MigrateAction}. * This also iterates through all the indices that are executing a given *migrated* policy and refreshes the cached phase definition * for each of these managed indices. */ static List<String> migrateIlmPolicies( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, String nodeAttrName, NamedXContentRegistry xContentRegistry, Client client, XPackLicenseState licenseState ) { IndexLifecycleMetadata currentLifecycleMetadata = projectMetadata.custom(IndexLifecycleMetadata.TYPE); if (currentLifecycleMetadata == null) { return List.of(); } List<String> migratedPolicies = new ArrayList<>(); Map<String, LifecyclePolicyMetadata> currentPolicies = currentLifecycleMetadata.getPolicyMetadatas(); SortedMap<String, LifecyclePolicyMetadata> newPolicies = new TreeMap<>(currentPolicies); for (Map.Entry<String, LifecyclePolicyMetadata> policyMetadataEntry : currentPolicies.entrySet()) { LifecyclePolicy newLifecyclePolicy = migrateSingleILMPolicy(nodeAttrName, policyMetadataEntry.getValue().getPolicy()); if (newLifecyclePolicy != null) { // we updated at least one phase long nextVersion = policyMetadataEntry.getValue().getVersion() + 1L; LifecyclePolicyMetadata newPolicyMetadata = new LifecyclePolicyMetadata( newLifecyclePolicy, policyMetadataEntry.getValue().getHeaders(), nextVersion, Instant.now().toEpochMilli() ); LifecyclePolicyMetadata oldPolicyMetadata = newPolicies.put(policyMetadataEntry.getKey(), newPolicyMetadata); assert oldPolicyMetadata != null : "we must only update policies, not create new ones, but " + policyMetadataEntry.getKey() + " didn't exist"; refreshCachedPhases( projectMetadataBuilder, projectMetadata, oldPolicyMetadata, newPolicyMetadata, xContentRegistry, client, licenseState ); migratedPolicies.add(policyMetadataEntry.getKey()); } } if (migratedPolicies.size() > 0) { IndexLifecycleMetadata newMetadata = new IndexLifecycleMetadata(newPolicies, currentILMMode(projectMetadata)); projectMetadataBuilder.putCustom(IndexLifecycleMetadata.TYPE, newMetadata); } return migratedPolicies; } /** * Refreshed the cached ILM phase definition for the indices managed by the migrated policy. */ static void refreshCachedPhases( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, LifecyclePolicyMetadata oldPolicyMetadata, LifecyclePolicyMetadata newPolicyMetadata, NamedXContentRegistry xContentRegistry, Client client, XPackLicenseState licenseState ) { // this performs a walk through the managed indices and safely updates the cached phase (ie. for the phases we did not // remove the allocate action) updateIndicesForPolicy( projectMetadataBuilder, projectMetadata, xContentRegistry, client, oldPolicyMetadata.getPolicy(), newPolicyMetadata, licenseState ); LifecyclePolicy newLifecyclePolicy = newPolicyMetadata.getPolicy(); List<String> migratedPhasesWithoutAllocateAction = getMigratedPhasesWithoutAllocateAction( oldPolicyMetadata.getPolicy(), newLifecyclePolicy ); if (migratedPhasesWithoutAllocateAction.size() > 0) { logger.debug( "the updated policy [{}] does not contain the allocate action in phases [{}] anymore", newLifecyclePolicy.getName(), migratedPhasesWithoutAllocateAction ); // if we removed the allocate action in any phase we won't be able to perform a safe update of the ilm cached phase (as // defined by {@link PhaseCacheManagement#isIndexPhaseDefinitionUpdatable} because the number of steps in the new phase is // not the same as in the cached phase) so let's forcefully (and still safely :) ) refresh the cached phase for the managed // indices in these phases. refreshCachedPhaseForPhasesWithoutAllocateAction( projectMetadataBuilder, projectMetadata, oldPolicyMetadata.getPolicy(), newPolicyMetadata, migratedPhasesWithoutAllocateAction, client, licenseState ); } } /** * Refresh the cached phase definition for those indices currently in one of the phases we migrated by removing the allocate action. * This refresh can be executed in two ways, depending where exactly within such a migrated phase is currently the managed index. * 1) if the index is in the allocate action, we'll move the ILM execution state for this index into the first step of the next * action of the phase (note that even if the allocate action was the only action defined in a phase we have a complete action we * inject at the end of every phase) * 2) if the index is anywhere else in the phase, we simply update the cached phase definition to reflect the migrated phase */ private static void refreshCachedPhaseForPhasesWithoutAllocateAction( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, LifecyclePolicy oldPolicy, LifecyclePolicyMetadata newPolicyMetadata, List<String> phasesWithoutAllocateAction, Client client, XPackLicenseState licenseState ) { String policyName = oldPolicy.getName(); final List<IndexMetadata> managedIndices = projectMetadata.indices() .values() .stream() .filter(meta -> policyName.equals(meta.getLifecyclePolicyName())) .toList(); for (IndexMetadata indexMetadata : managedIndices) { LifecycleExecutionState currentExState = indexMetadata.getLifecycleExecutionState(); if (currentExState != null) { Step.StepKey currentStepKey = Step.getCurrentStepKey(currentExState); if (currentStepKey != null && phasesWithoutAllocateAction.contains(currentStepKey.phase())) { // the index is in a phase that doesn't contain the allocate action anymore if (currentStepKey.action().equals(AllocateAction.NAME)) { // this index is in the middle of executing the allocate action - which doesn't exist in the updated policy // anymore so let's try to move the index to the next action LifecycleExecutionState newLifecycleState = moveStateToNextActionAndUpdateCachedPhase( indexMetadata, currentExState, System::currentTimeMillis, oldPolicy, newPolicyMetadata, client, licenseState ); if (currentExState.equals(newLifecycleState) == false) { projectMetadataBuilder.put( IndexMetadata.builder(indexMetadata).putCustom(ILM_CUSTOM_METADATA_KEY, newLifecycleState.asMap()) ); } } else { // if the index is not in the allocate action, we're going to perform a cached phase update (which is "unsafe" by // the rules defined in {@link PhaseCacheManagement#isIndexPhaseDefinitionUpdatable} but in our case it is safe // as the migration would've only removed the allocate action and the current index is not in the middle of // executing the allocate action, we made sure of that) LifecycleExecutionState.Builder updatedState = LifecycleExecutionState.builder(currentExState); PhaseExecutionInfo phaseExecutionInfo = new PhaseExecutionInfo( newPolicyMetadata.getPolicy().getName(), newPolicyMetadata.getPolicy().getPhases().get(currentStepKey.phase()), newPolicyMetadata.getVersion(), newPolicyMetadata.getModifiedDate() ); String newPhaseDefinition = Strings.toString(phaseExecutionInfo, false, false); updatedState.setPhaseDefinition(newPhaseDefinition); logger.debug( "updating the cached phase definition for index [{}], current step [{}] in policy " + "[{}] to [{}]", indexMetadata.getIndex().getName(), currentStepKey, policyName, newPhaseDefinition ); projectMetadataBuilder.put( IndexMetadata.builder(indexMetadata).putCustom(ILM_CUSTOM_METADATA_KEY, updatedState.build().asMap()) ); } } } } } /** * Returns a list of phases that had an allocate action defined in the old policy, but don't have it anymore in the new policy * (ie. they were allocate actions that only specified attribute based routing, without any number of replicas configuration and we * removed them as part of the migration of ILM policies to data tiers in order to allow ILM to inject the migrate action) */ private static List<String> getMigratedPhasesWithoutAllocateAction(LifecyclePolicy oldPolicy, LifecyclePolicy newLifecyclePolicy) { List<String> oldPhasesWithAllocateAction = new ArrayList<>(oldPolicy.getPhases().size()); for (Map.Entry<String, Phase> phaseEntry : oldPolicy.getPhases().entrySet()) { if (phaseEntry.getValue().getActions().containsKey(AllocateAction.NAME)) { oldPhasesWithAllocateAction.add(phaseEntry.getKey()); } } List<String> migratedPhasesWithoutAllocateAction = new ArrayList<>(oldPhasesWithAllocateAction.size()); for (String phaseWithAllocateAction : oldPhasesWithAllocateAction) { Phase phase = newLifecyclePolicy.getPhases().get(phaseWithAllocateAction); assert phase != null : "the migration service should not remove an entire phase altogether"; if (phase.getActions().containsKey(AllocateAction.NAME) == false) { // the updated policy doesn't have the allocate action defined in this phase anymore migratedPhasesWithoutAllocateAction.add(phaseWithAllocateAction); } } return migratedPhasesWithoutAllocateAction; } /** * Migrates a single ILM policy from defining {@link AllocateAction}s in order to configure shard allocation routing based on the * provided node attribute name towards allowing ILM to inject the {@link MigrateAction}. * * Returns the migrated ILM policy. */ @Nullable private static LifecyclePolicy migrateSingleILMPolicy(String nodeAttrName, LifecyclePolicy lifecyclePolicy) { LifecyclePolicy newLifecyclePolicy = null; for (Map.Entry<String, Phase> phaseEntry : lifecyclePolicy.getPhases().entrySet()) { Phase phase = phaseEntry.getValue(); AllocateAction allocateAction = (AllocateAction) phase.getActions().get(AllocateAction.NAME); if (allocateActionDefinesRoutingRules(nodeAttrName, allocateAction)) { Map<String, LifecycleAction> actionMap = new HashMap<>(phase.getActions()); // this phase contains an allocate action that defines a require rule for the attribute name so we'll remove all the // rules to allow for the migrate action to be injected if (allocateAction.getNumberOfReplicas() != null || allocateAction.getTotalShardsPerNode() != null) { // keep the number of replicas configuration and/or the total shards per node configuration AllocateAction updatedAllocateAction = new AllocateAction( allocateAction.getNumberOfReplicas(), allocateAction.getTotalShardsPerNode(), null, null, null ); actionMap.put(allocateAction.getWriteableName(), updatedAllocateAction); logger.debug( "ILM policy [{}], phase [{}]: updated the allocate action to [{}]", lifecyclePolicy.getName(), phase.getName(), allocateAction ); } else { // remove the action altogether actionMap.remove(allocateAction.getWriteableName()); logger.debug("ILM policy [{}], phase [{}]: removed the allocate action", lifecyclePolicy.getName(), phase.getName()); } // we removed the allocate action allocation rules (or the action completely) so let's check if there is an // explicit migrate action that's disabled, and remove it so ILM can inject an enabled one if (actionMap.containsKey(MigrateAction.NAME)) { MigrateAction migrateAction = (MigrateAction) actionMap.get(MigrateAction.NAME); if (migrateAction.isEnabled() == false) { actionMap.remove(MigrateAction.NAME); logger.debug( "ILM policy [{}], phase [{}]: removed the deactivated migrate action", lifecyclePolicy.getName(), phase.getName() ); } } Phase updatedPhase = new Phase(phase.getName(), phase.getMinimumAge(), actionMap); Map<String, Phase> updatedPhases = new HashMap<>( newLifecyclePolicy == null ? lifecyclePolicy.getPhases() : newLifecyclePolicy.getPhases() ); updatedPhases.put(phaseEntry.getKey(), updatedPhase); newLifecyclePolicy = new LifecyclePolicy(lifecyclePolicy.getName(), updatedPhases); } } return newLifecyclePolicy; } /** * Returns true of the provided {@link AllocateAction} defines any index allocation rules. */ static boolean allocateActionDefinesRoutingRules(String nodeAttrName, @Nullable AllocateAction allocateAction) { return allocateAction != null && (allocateAction.getRequire().get(nodeAttrName) != null || allocateAction.getInclude().get(nodeAttrName) != null || allocateAction.getExclude().get(nodeAttrName) != null); } /** * Iterates through the existing indices and migrates them away from using attribute based routing using the provided node * attribute name towards the tier preference routing. * Returns a list of the migrated indices. */ static List<String> migrateIndices( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, String nodeAttrName ) { List<String> migratedIndices = new ArrayList<>(); String nodeAttrIndexRequireRoutingSetting = INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + nodeAttrName; String nodeAttrIndexIncludeRoutingSetting = INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + nodeAttrName; String nodeAttrIndexExcludeRoutingSetting = INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + nodeAttrName; for (var indexMetadata : projectMetadata.indices().values()) { String indexName = indexMetadata.getIndex().getName(); Settings currentSettings = indexMetadata.getSettings(); boolean removeNodeAttrIndexRoutingSettings = true; // migrate using the `require` setting Settings newSettings = maybeMigrateRoutingSettingToTierPreference( nodeAttrIndexRequireRoutingSetting, currentSettings, indexName ); // we possibly migrated the `require` setting, but maybe that attribute was not the coldest configured. // let's try to migrate the `include` setting as well newSettings = maybeMigrateRoutingSettingToTierPreference(nodeAttrIndexIncludeRoutingSetting, newSettings, indexName); if (newSettings.equals(currentSettings)) { removeNodeAttrIndexRoutingSettings = false; // migrating based on the `include` setting was not successful, // so, last stop, we just inject a tier preference regardless of anything else newSettings = migrateToDefaultTierPreference(projectMetadata, indexMetadata); } if (newSettings.equals(currentSettings) == false) { Settings.Builder finalSettings = Settings.builder().put(newSettings); if (removeNodeAttrIndexRoutingSettings) { // we converted either the `require` or the `include` routing setting to tier preference // so let's clear all the routing settings for the given attribute finalSettings.remove(nodeAttrIndexExcludeRoutingSetting); finalSettings.remove(nodeAttrIndexRequireRoutingSetting); finalSettings.remove(nodeAttrIndexIncludeRoutingSetting); } if (SearchableSnapshotsSettings.isPartialSearchableSnapshotIndex(newSettings)) { String configuredTierPreference = null; try { configuredTierPreference = TIER_PREFERENCE_SETTING.get(newSettings); } catch (IllegalArgumentException ignored) { // we'll configure the correct tier preference below } if (configuredTierPreference == null || configuredTierPreference.equals(DATA_FROZEN) == false) { finalSettings.put(TIER_PREFERENCE_SETTING.getKey(), DATA_FROZEN); } } projectMetadataBuilder.put( IndexMetadata.builder(indexMetadata).settings(finalSettings).settingsVersion(indexMetadata.getSettingsVersion() + 1) ); migratedIndices.add(indexMetadata.getIndex().getName()); } } return migratedIndices; } /** * Attempts to migrate the value of the given attribute routing setting to the _tier_preference equivalent. The provided setting * needs to be configured and have one of the supported values (hot, warm, cold, or frozen) in order for the migration to be performed. * If the migration is successful the provided setting will be removed. * * If the migration is **not** executed the current index settings is returned, otherwise the updated settings are returned */ private static Settings maybeMigrateRoutingSettingToTierPreference( String attributeBasedRoutingSettingName, Settings currentIndexSettings, String indexName ) { if (currentIndexSettings.keySet().contains(attributeBasedRoutingSettingName) == false) { return currentIndexSettings; } Settings.Builder newSettingsBuilder = Settings.builder().put(currentIndexSettings); // look at the value, get the correct tiers config and update the settings if (currentIndexSettings.keySet().contains(TIER_PREFERENCE)) { String tierPreferenceConfiguration = currentIndexSettings.get(TIER_PREFERENCE); List<String> tiersConfiguration = DataTier.parseTierList(tierPreferenceConfiguration); if (tiersConfiguration.isEmpty() == false) { String coldestConfiguredTier = tiersConfiguration.get(0); String attributeValue = currentIndexSettings.get(attributeBasedRoutingSettingName); String attributeTierEquivalent = "data_" + attributeValue; if (DataTier.validTierName(attributeTierEquivalent)) { // if the attribute's tier equivalent would be colder than what is currently the coldest tier configured // in the _tier_preference setting, the configured attribute routing is more accurate so we'll update the // tier_preference to reflect this before removing the attribute routing setting. if (DataTier.compare(attributeTierEquivalent, coldestConfiguredTier) < 0) { String newTierPreferenceConfiguration = convertAttributeValueToTierPreference(attributeValue); if (newTierPreferenceConfiguration != null) { logger.debug( "index [{}]: updated the [{}] setting to [{}] as the attribute based routing setting [{}] had " + "the value [{}]", indexName, TIER_PREFERENCE, newTierPreferenceConfiguration, attributeBasedRoutingSettingName, attributeValue ); newSettingsBuilder.put(TIER_PREFERENCE, newTierPreferenceConfiguration); } } } } newSettingsBuilder.remove(attributeBasedRoutingSettingName); logger.debug("index [{}]: removed setting [{}]", indexName, attributeBasedRoutingSettingName); } else { // parse the custom attribute routing into the corresponding tier preference and configure it String attributeValue = currentIndexSettings.get(attributeBasedRoutingSettingName); String convertedTierPreference = convertAttributeValueToTierPreference(attributeValue); if (convertedTierPreference != null) { newSettingsBuilder.put(TIER_PREFERENCE, convertedTierPreference); newSettingsBuilder.remove(attributeBasedRoutingSettingName); logger.debug("index [{}]: removed setting [{}]", indexName, attributeBasedRoutingSettingName); logger.debug("index [{}]: configured setting [{}] to [{}]", indexName, TIER_PREFERENCE, convertedTierPreference); } else { // log warning and do *not* remove setting, return the settings unchanged logger.warn( "index [{}]: could not convert attribute based setting [{}] value of [{}] to a tier preference " + "configuration. the only known values are: {}", indexName, attributeBasedRoutingSettingName, attributeValue, "hot,warm,cold, and frozen" ); return currentIndexSettings; } } return newSettingsBuilder.build(); } static MigratedTemplates migrateIndexAndComponentTemplates( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, String nodeAttrName ) { List<String> migratedLegacyTemplates = migrateLegacyTemplates(projectMetadataBuilder, projectMetadata, nodeAttrName); List<String> migratedComposableTemplates = migrateComposableTemplates(projectMetadataBuilder, projectMetadata, nodeAttrName); List<String> migratedComponentTemplates = migrateComponentTemplates(projectMetadataBuilder, projectMetadata, nodeAttrName); return new MigratedTemplates(migratedLegacyTemplates, migratedComposableTemplates, migratedComponentTemplates); } static List<String> migrateLegacyTemplates( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, String nodeAttrName ) { String requireRoutingSetting = INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + nodeAttrName; String includeRoutingSetting = INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + nodeAttrName; String excludeRoutingSetting = INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + nodeAttrName; List<String> migratedLegacyTemplates = new ArrayList<>(); for (var template : projectMetadata.templates().entrySet()) { IndexTemplateMetadata templateMetadata = template.getValue(); if (templateMetadata.settings().keySet().contains(requireRoutingSetting) || templateMetadata.settings().keySet().contains(includeRoutingSetting)) { IndexTemplateMetadata.Builder templateMetadataBuilder = new IndexTemplateMetadata.Builder(templateMetadata); Settings.Builder settingsBuilder = Settings.builder().put(templateMetadata.settings()); settingsBuilder.remove(requireRoutingSetting); settingsBuilder.remove(includeRoutingSetting); settingsBuilder.remove(excludeRoutingSetting); templateMetadataBuilder.settings(settingsBuilder); projectMetadataBuilder.put(templateMetadataBuilder); migratedLegacyTemplates.add(template.getKey()); } } return migratedLegacyTemplates; } static List<String> migrateComposableTemplates( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, String nodeAttrName ) { String requireRoutingSetting = INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + nodeAttrName; String includeRoutingSetting = INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + nodeAttrName; String excludeRoutingSetting = INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + nodeAttrName; List<String> migratedComposableTemplates = new ArrayList<>(); for (Map.Entry<String, ComposableIndexTemplate> templateEntry : projectMetadata.templatesV2().entrySet()) { ComposableIndexTemplate composableTemplate = templateEntry.getValue(); if (composableTemplate.template() != null && composableTemplate.template().settings() != null) { Settings settings = composableTemplate.template().settings(); if (settings.keySet().contains(requireRoutingSetting) || settings.keySet().contains(includeRoutingSetting)) { Template currentInnerTemplate = composableTemplate.template(); ComposableIndexTemplate.Builder migratedComposableTemplateBuilder = ComposableIndexTemplate.builder(); Settings.Builder settingsBuilder = Settings.builder().put(settings); settingsBuilder.remove(requireRoutingSetting); settingsBuilder.remove(includeRoutingSetting); settingsBuilder.remove(excludeRoutingSetting); Template migratedInnerTemplate = Template.builder(currentInnerTemplate).settings(settingsBuilder).build(); migratedComposableTemplateBuilder.indexPatterns(composableTemplate.indexPatterns()); migratedComposableTemplateBuilder.template(migratedInnerTemplate); migratedComposableTemplateBuilder.componentTemplates(composableTemplate.composedOf()); migratedComposableTemplateBuilder.priority(composableTemplate.priority()); migratedComposableTemplateBuilder.version(composableTemplate.version()); migratedComposableTemplateBuilder.metadata(composableTemplate.metadata()); migratedComposableTemplateBuilder.dataStreamTemplate(composableTemplate.getDataStreamTemplate()); migratedComposableTemplateBuilder.allowAutoCreate(composableTemplate.getAllowAutoCreate()); migratedComposableTemplateBuilder.ignoreMissingComponentTemplates( composableTemplate.getIgnoreMissingComponentTemplates() ); migratedComposableTemplateBuilder.createdDate(composableTemplate.createdDateMillis().orElse(null)); migratedComposableTemplateBuilder.modifiedDate(composableTemplate.modifiedDateMillis().orElse(null)); projectMetadataBuilder.put(templateEntry.getKey(), migratedComposableTemplateBuilder.build()); migratedComposableTemplates.add(templateEntry.getKey()); } } } return migratedComposableTemplates; } static List<String> migrateComponentTemplates( ProjectMetadata.Builder projectMetadataBuilder, ProjectMetadata projectMetadata, String nodeAttrName ) { String requireRoutingSetting = INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + nodeAttrName; String includeRoutingSetting = INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + nodeAttrName; String excludeRoutingSetting = INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + nodeAttrName; List<String> migratedComponentTemplates = new ArrayList<>(); for (Map.Entry<String, ComponentTemplate> componentEntry : projectMetadata.componentTemplates().entrySet()) { ComponentTemplate componentTemplate = componentEntry.getValue(); if (componentTemplate.template() != null && componentTemplate.template().settings() != null) { Settings settings = componentTemplate.template().settings(); if (settings.keySet().contains(requireRoutingSetting) || settings.keySet().contains(includeRoutingSetting)) { Template currentInnerTemplate = componentTemplate.template(); Settings.Builder settingsBuilder = Settings.builder().put(settings); settingsBuilder.remove(requireRoutingSetting); settingsBuilder.remove(includeRoutingSetting); settingsBuilder.remove(excludeRoutingSetting); Template migratedInnerTemplate = Template.builder(currentInnerTemplate).settings(settingsBuilder).build(); ComponentTemplate migratedComponentTemplate = new ComponentTemplate( migratedInnerTemplate, componentTemplate.version(), componentTemplate.metadata(), componentTemplate.deprecated(), componentTemplate.createdDateMillis().orElse(null), componentTemplate.modifiedDateMillis().orElse(null) ); projectMetadataBuilder.put(componentEntry.getKey(), migratedComponentTemplate); migratedComponentTemplates.add(componentEntry.getKey()); } } } return migratedComponentTemplates; } private static Settings migrateToDefaultTierPreference(ProjectMetadata projectMetadata, IndexMetadata indexMetadata) { Settings currentIndexSettings = indexMetadata.getSettings(); List<String> tierPreference = DataTier.parseTierList(DataTier.TIER_PREFERENCE_SETTING.get(currentIndexSettings)); if (tierPreference.isEmpty() == false) { return currentIndexSettings; } Settings.Builder newSettingsBuilder = Settings.builder().put(currentIndexSettings); String indexName = indexMetadata.getIndex().getName(); boolean isDataStream = projectMetadata.findDataStreams(indexName).isEmpty() == false; String convertedTierPreference = isDataStream ? DataTier.DATA_HOT : DataTier.DATA_CONTENT; if (SearchableSnapshotsSettings.isSearchableSnapshotStore(indexMetadata.getSettings())) { if (SearchableSnapshotsSettings.isPartialSearchableSnapshotIndex(indexMetadata.getSettings())) { // partially mounted index convertedTierPreference = MountSearchableSnapshotRequest.Storage.SHARED_CACHE.defaultDataTiersPreference(); } else { // fully mounted index convertedTierPreference = MountSearchableSnapshotRequest.Storage.FULL_COPY.defaultDataTiersPreference(); } } newSettingsBuilder.put(TIER_PREFERENCE, convertedTierPreference); logger.debug("index [{}]: configured setting [{}] to [{}]", indexName, TIER_PREFERENCE, convertedTierPreference); return newSettingsBuilder.build(); } /** * Converts the provided node attribute value to the corresponding `_tier_preference` configuration. * Known (and convertible) attribute values are: * * hot * * warm * * cold * * frozen * and the corresponding tier preference setting values are, respectively: * * data_hot * * data_warm,data_hot * * data_cold,data_warm,data_hot * * data_frozen,data_cold,data_warm,data_hot * <p> * This returns `null` if an unknown attribute value is received. */ @Nullable static String convertAttributeValueToTierPreference(String nodeAttributeValue) { String targetTier = "data_" + nodeAttributeValue; // handle the `content` accidental node attribute value which would match a data tier but doesn't fall into the hot/warm/cold // (given we're _migrating_ to data tiers we won't catch this accidental tier which didn't exist as a concept before the // formalisation of data tiers) if (DataTier.validTierName(targetTier) == false || targetTier.equals(DataTier.DATA_CONTENT)) { return null; } return DataTier.getPreferredTiersConfiguration(targetTier); } /** * Represents the elasticsearch abstractions that were, in some way, migrated such that the system is managing indices lifecycles and * allocations using data tiers. */ public record MigratedEntities( @Nullable String removedIndexTemplateName, List<String> migratedIndices, List<String> migratedPolicies, MigratedTemplates migratedTemplates ) { public MigratedEntities( @Nullable String removedIndexTemplateName, List<String> migratedIndices, List<String> migratedPolicies, MigratedTemplates migratedTemplates ) { this.removedIndexTemplateName = removedIndexTemplateName; this.migratedIndices = Collections.unmodifiableList(migratedIndices); this.migratedPolicies = Collections.unmodifiableList(migratedPolicies); this.migratedTemplates = migratedTemplates; } } /** * Represents the legacy, composable, and component templates that were migrated away from shard allocation settings based on custom * node attributes. */ public record MigratedTemplates( List<String> migratedLegacyTemplates, List<String> migratedComposableTemplates, List<String> migratedComponentTemplates ) { public MigratedTemplates( List<String> migratedLegacyTemplates, List<String> migratedComposableTemplates, List<String> migratedComponentTemplates ) { this.migratedLegacyTemplates = Collections.unmodifiableList(migratedLegacyTemplates); this.migratedComposableTemplates = Collections.unmodifiableList(migratedComposableTemplates); this.migratedComponentTemplates = Collections.unmodifiableList(migratedComponentTemplates); } } }
MetadataMigrateToDataTiersRoutingService
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/util/StreamTaskUtil.java
{ "start": 1105, "end": 1530 }
class ____ { public static void waitTaskIsRunning( StreamTask<?, ?> task, CompletableFuture<Void> taskInvocation) throws InterruptedException, ExecutionException { while (!task.isRunning()) { if (taskInvocation.isDone()) { taskInvocation.get(); fail("Task has stopped"); } Thread.sleep(10L); } } }
StreamTaskUtil
java
apache__flink
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/dql/SqlUnloadModule.java
{ "start": 1313, "end": 2239 }
class ____ extends SqlCall { public static final SqlSpecialOperator OPERATOR = new SqlSpecialOperator("UNLOAD MODULE", SqlKind.OTHER); private final SqlIdentifier moduleName; public SqlUnloadModule(SqlParserPos pos, SqlIdentifier moduleName) { super(pos); this.moduleName = moduleName; } @Override public SqlOperator getOperator() { return OPERATOR; } @Override public List<SqlNode> getOperandList() { return ImmutableNullableList.of(moduleName); } @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { writer.keyword("UNLOAD"); writer.keyword("MODULE"); moduleName.unparse(writer, leftPrec, rightPrec); } public SqlIdentifier getModuleName() { return moduleName; } public String moduleName() { return moduleName.getSimple(); } }
SqlUnloadModule
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMethodMappingNamingStrategyTests.java
{ "start": 1167, "end": 2314 }
class ____ { @Test void getNameExplicit() { Method method = ClassUtils.getMethod(TestController.class, "handle"); HandlerMethod handlerMethod = new HandlerMethod(new TestController(), method); @SuppressWarnings("deprecation") RequestMappingInfo rmi = new RequestMappingInfo("foo", null, null, null, null, null, null, null, null); HandlerMethodMappingNamingStrategy<RequestMappingInfo> strategy = new RequestMappingInfoHandlerMethodMappingNamingStrategy(); assertThat(strategy.getName(handlerMethod, rmi)).isEqualTo("foo"); } @Test void getNameConvention() { Method method = ClassUtils.getMethod(TestController.class, "handle"); HandlerMethod handlerMethod = new HandlerMethod(new TestController(), method); @SuppressWarnings("deprecation") RequestMappingInfo rmi = new RequestMappingInfo(null, null, null, null, null, null, null, null); HandlerMethodMappingNamingStrategy<RequestMappingInfo> strategy = new RequestMappingInfoHandlerMethodMappingNamingStrategy(); assertThat(strategy.getName(handlerMethod, rmi)).isEqualTo("TC#handle"); } private static
RequestMappingInfoHandlerMethodMappingNamingStrategyTests
java
spring-projects__spring-security
ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java
{ "start": 930, "end": 1820 }
class ____ { @Test public void returnsNullForUnrecognisedOID() { PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory(); Control wrongCtrl = mock(Control.class); given(wrongCtrl.getID()).willReturn("wrongId"); assertThat(ctrlFactory.getControlInstance(wrongCtrl)).isNull(); } @Test public void returnsControlForCorrectOID() { PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory(); Control control = mock(Control.class); given(control.getID()).willReturn(PasswordPolicyControl.OID); given(control.getEncodedValue()).willReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL); Control result = ctrlFactory.getControlInstance(control); assertThat(result).isNotNull(); assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue()); } }
PasswordPolicyControlFactoryTests
java
apache__camel
components/camel-mybatis/src/main/java/org/apache/camel/component/mybatis/MyBatisBeanEndpoint.java
{ "start": 2572, "end": 2941 }
class ____. */ public void setBeanName(String beanName) { this.beanName = beanName; } public String getMethodName() { return methodName; } /** * Name of the method on the bean that has the SQL query to be executed. */ public void setMethodName(String methodName) { this.methodName = methodName; } }
name
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/execution/librarycache/LibraryCacheManager.java
{ "start": 3802, "end": 3917 }
interface ____ extends ClassLoaderHandle { /** * Releases the lease to the user code
ClassLoaderLease
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/dev/devservices/ImageName.java
{ "start": 2217, "end": 2696 }
class ____ permits Version.Tag, Version.Sha256, Version.Any { public final String version; public Version(String version) { this.version = version; } public String getVersion() { return version; } public String getSeparator() { return ":"; } @Override public String toString() { return version + getSeparator(); } private static final
Version
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/DefaultJobTable.java
{ "start": 7617, "end": 8146 }
class ____ { // The unique id used for identifying the job manager private final ResourceID resourceID; // Gateway to the job master private final JobMasterGateway jobMasterGateway; // Task manager actions with respect to the connected job manager private final TaskManagerActions taskManagerActions; // Checkpoint responder for the specific job manager private final CheckpointResponder checkpointResponder; // GlobalAggregateManager
EstablishedConnection
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/internal/JpaMetamodelPopulationSetting.java
{ "start": 381, "end": 899 }
enum ____ { ENABLED, DISABLED, IGNORE_UNSUPPORTED; public static JpaMetamodelPopulationSetting parse(String setting) { return switch ( setting.toLowerCase(Locale.ROOT) ) { case "enabled" -> ENABLED; case "disabled" -> DISABLED; default -> IGNORE_UNSUPPORTED; }; } public static JpaMetamodelPopulationSetting determineJpaMetaModelPopulationSetting(Map<String, Object> settings) { return parse( getString( JPA_METAMODEL_POPULATION, settings, "ignoreUnsupported" ) ); } }
JpaMetamodelPopulationSetting
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/counters/CounterGroupFactory.java
{ "start": 2182, "end": 2949 }
class ____ and the version when changed. addFrameworkGroup(TaskCounter.class); addFrameworkGroup(JobCounter.class); } // Initialize the framework counter group mapping private synchronized <T extends Enum<T>> void addFrameworkGroup(final Class<T> cls) { updateFrameworkGroupMapping(cls); fmap.put(cls.getName(), newFrameworkGroupFactory(cls)); } // Update static mappings (c2i, i2s) of framework groups private static synchronized void updateFrameworkGroupMapping(Class<?> cls) { String name = cls.getName(); Integer i = s2i.get(name); if (i != null) return; i2s.add(name); s2i.put(name, i2s.size() - 1); } /** * Required override to return a new framework group factory * @param <T> type of the counter
here
java
apache__camel
components/camel-google/camel-google-mail/src/main/java/org/apache/camel/component/google/mail/stream/GoogleMailStreamComponent.java
{ "start": 1412, "end": 4023 }
class ____ extends HealthCheckComponent { @Metadata(label = "advanced") private Gmail client; @Metadata(label = "advanced") private GoogleMailClientFactory clientFactory; @Metadata(label = "advanced") private GoogleMailStreamConfiguration configuration; public GoogleMailStreamComponent() { this(null); } public GoogleMailStreamComponent(CamelContext context) { super(context); this.configuration = new GoogleMailStreamConfiguration(); } public Gmail getClient(GoogleMailStreamConfiguration googleMailConfiguration) { if (client == null) { if (googleMailConfiguration.getClientSecret() != null) { client = getClientFactory().makeClient(googleMailConfiguration.getClientId(), googleMailConfiguration.getClientSecret(), googleMailConfiguration.getScopesAsList(), googleMailConfiguration.getApplicationName(), googleMailConfiguration.getRefreshToken(), googleMailConfiguration.getAccessToken()); } else if (googleMailConfiguration.getServiceAccountKey() != null) { client = getClientFactory().makeClient(getCamelContext(), googleMailConfiguration.getServiceAccountKey(), googleMailConfiguration.getScopesAsList(), googleMailConfiguration.getApplicationName(), googleMailConfiguration.getDelegate()); } } return client; } /** * The client Factory */ public GoogleMailClientFactory getClientFactory() { if (clientFactory == null) { clientFactory = new BatchGoogleMailClientFactory(); } return clientFactory; } public GoogleMailStreamConfiguration getConfiguration() { return configuration; } /** * The configuration */ public void setConfiguration(GoogleMailStreamConfiguration configuration) { this.configuration = configuration; } public void setClientFactory(GoogleMailClientFactory clientFactory) { this.clientFactory = clientFactory; } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { final GoogleMailStreamConfiguration configuration = this.configuration.copy(); configuration.setIndex(remaining); GoogleMailStreamEndpoint endpoint = new GoogleMailStreamEndpoint(uri, this, configuration); setProperties(endpoint, parameters); return endpoint; } }
GoogleMailStreamComponent
java
apache__dubbo
dubbo-compatible/src/test/java/org/apache/dubbo/metadata/rest/StandardRestService.java
{ "start": 1369, "end": 3319 }
class ____ implements RestService { @Override @Path("param") @GET public String param(@QueryParam("param") String param) { return param; } @Override @Path("params") @POST public String params(@QueryParam("a") int a, @QueryParam("b") String b) { return a + b; } @Override @Path("headers") @GET public String headers( @HeaderParam("h") String header, @HeaderParam("h2") String header2, @QueryParam("v") Integer param) { String result = header + " , " + header2 + " , " + param; return result; } @Override @Path("path-variables/{p1}/{p2}") @GET public String pathVariables( @PathParam("p1") String path1, @PathParam("p2") String path2, @QueryParam("v") String param) { String result = path1 + " , " + path2 + " , " + param; return result; } // @CookieParam does not support : https://github.com/OpenFeign/feign/issues/913 // @CookieValue also does not support @Override @Path("form") @POST public String form(@FormParam("f") String form) { return String.valueOf(form); } @Override @Path("request/body/map") @POST @Produces("application/json;charset=UTF-8") public User requestBodyMap(Map<String, Object> data, @QueryParam("param") String param) { User user = new User(); user.setId(((Integer) data.get("id")).longValue()); user.setName((String) data.get("name")); user.setAge((Integer) data.get("age")); return user; } @Path("request/body/user") @POST @Override @Consumes("application/json;charset=UTF-8") public Map<String, Object> requestBodyUser(User user) { Map<String, Object> map = new HashMap<>(); map.put("id", user.getId()); map.put("name", user.getName()); map.put("age", user.getAge()); return map; } }
StandardRestService
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/CompensatedSum.java
{ "start": 1002, "end": 2834 }
class ____ { private static final double NO_CORRECTION = 0.0; private double value; private double delta; /** * Used to calculate sums using the Kahan summation algorithm. * * @param value the sum * @param delta correction term */ public CompensatedSum(double value, double delta) { this.value = value; this.delta = delta; } public CompensatedSum() { this(0, 0); } /** * The value of the sum. */ public double value() { return value; } /** * The correction term. */ public double delta() { return delta; } /** * Increments the Kahan sum by adding a value without a correction term. */ public CompensatedSum add(double value) { return add(value, NO_CORRECTION); } /** * Resets the internal state to use the new value and compensation delta */ public void reset(double value, double delta) { this.value = value; this.delta = delta; } /** * Increments the Kahan sum by adding two sums, and updating the correction term for reducing numeric errors. */ public CompensatedSum add(double value, double delta) { // If the value is Inf or NaN, just add it to the running tally to "convert" to // Inf/NaN. This keeps the behavior bwc from before kahan summing if (Double.isFinite(value) == false) { this.value = value + this.value; } if (Double.isFinite(this.value)) { double correctedSum = value + (this.delta + delta); double updatedValue = this.value + correctedSum; this.delta = correctedSum - (updatedValue - this.value); this.value = updatedValue; } return this; } }
CompensatedSum
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StaticQualifiedUsingExpressionTest.java
{ "start": 8483, "end": 9789 }
class ____ { public static int staticVar1 = 1; public static void staticTestMethod() {} public void test1() { Integer i = Integer.MAX_VALUE; i = Integer.valueOf(10); } public void test2() { int i = staticVar1; i = StaticQualifiedUsingExpressionNegativeCases.staticVar1; } public void test3() { test1(); this.test1(); new StaticQualifiedUsingExpressionNegativeCases().test1(); staticTestMethod(); } public void test4() { Class<?> klass = String[].class; } @SuppressWarnings("static") public void testJavacAltname() { this.staticTestMethod(); } @SuppressWarnings("static-access") public void testEclipseAltname() { this.staticTestMethod(); } }\ """) .doTest(); } @Test public void clash() { refactoringHelper .addInputLines( "a/Lib.java", """ package a; public
StaticQualifiedUsingExpressionNegativeCases
java
alibaba__nacos
sys/src/main/java/com/alibaba/nacos/sys/module/AbstractConsoleModuleStateBuilder.java
{ "start": 801, "end": 1050 }
class ____ implements ModuleStateBuilder { @Override public boolean isMatchDeployment(DeploymentType type) { return DeploymentType.MERGED.equals(type) || DeploymentType.CONSOLE.equals(type); } }
AbstractConsoleModuleStateBuilder
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/OpenTelemetryServiceNameBaseTest.java
{ "start": 686, "end": 1389 }
class ____ { protected static final String SERVICE_NAME = "FrankBullitt"; @Inject TestSpanExporter spanExporter; @Test void testServiceName() { RestAssured.when() .get("/hello").then() .statusCode(200) .body(is("hello")); List<SpanData> spans = spanExporter.getFinishedSpanItems(1); final SpanData server = getSpanByKindAndParentId(spans, SERVER, "0000000000000000"); assertEquals("GET /hello", server.getName()); assertEquals(SERVICE_NAME, server.getResource().getAttribute(AttributeKey.stringKey("service.name"))); } @Path("/hello") public static
OpenTelemetryServiceNameBaseTest
java
apache__hadoop
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/Environment.java
{ "start": 1368, "end": 4133 }
class ____ extends Properties { private static final long serialVersionUID = 1L; public Environment() throws IOException { // Extend this code to fit all operating // environments that you expect to run in // http://lopica.sourceforge.net/os.html String command = null; String OS = System.getProperty("os.name"); String lowerOs = StringUtils.toLowerCase(OS); if (OS.indexOf("Windows") > -1) { command = "cmd /C set"; } else if (lowerOs.indexOf("ix") > -1 || lowerOs.indexOf("linux") > -1 || lowerOs.indexOf("freebsd") > -1 || lowerOs.indexOf("sunos") > -1 || lowerOs.indexOf("solaris") > -1 || lowerOs.indexOf("hp-ux") > -1) { command = "env"; } else if (lowerOs.startsWith("mac os x") || lowerOs.startsWith("darwin")) { command = "env"; } else { // Add others here } if (command == null) { throw new RuntimeException("Operating system " + OS + " not supported by this class"); } // Read the environment variables Process pid = Runtime.getRuntime().exec(command); BufferedReader in = new BufferedReader( new InputStreamReader(pid.getInputStream(), StandardCharsets.UTF_8)); try { while (true) { String line = in.readLine(); if (line == null) break; int p = line.indexOf("="); if (p != -1) { String name = line.substring(0, p); String value = line.substring(p + 1); setProperty(name, value); } } in.close(); in = null; } finally { IOUtils.closeStream(in); } try { pid.waitFor(); } catch (InterruptedException e) { throw new IOException(e.getMessage()); } } // to be used with Runtime.exec(String[] cmdarray, String[] envp) String[] toArray() { String[] arr = new String[super.size()]; Enumeration<Object> it = super.keys(); int i = -1; while (it.hasMoreElements()) { String key = (String) it.nextElement(); String val = (String) get(key); i++; arr[i] = key + "=" + val; } return arr; } public Map<String, String> toMap() { Map<String, String> map = new HashMap<String, String>(); Enumeration<Object> it = super.keys(); while (it.hasMoreElements()) { String key = (String) it.nextElement(); String val = (String) get(key); map.put(key, val); } return map; } public String getHost() { String host = getProperty("HOST"); if (host == null) { // HOST isn't always in the environment try { host = InetAddress.getLocalHost().getHostName(); } catch (IOException io) { io.printStackTrace(); } } return host; } }
Environment
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/aop/scheduled/ScheduledExample.java
{ "start": 750, "end": 1804 }
class ____ { // tag::fixedRate[] @Scheduled(fixedRate = "5m") void everyFiveMinutes() { System.out.println("Executing everyFiveMinutes()"); } // end::fixedRate[] // tag::fixedDelay[] @Scheduled(fixedDelay = "5m") void fiveMinutesAfterLastExecution() { System.out.println("Executing fiveMinutesAfterLastExecution()"); } // end::fixedDelay[] // tag::cron[] @Scheduled(cron = "0 15 10 ? * MON") void everyMondayAtTenFifteenAm() { System.out.println("Executing everyMondayAtTenFifteenAm()"); } // end::cron[] // tag::initialDelay[] @Scheduled(initialDelay = "1m") void onceOneMinuteAfterStartup() { System.out.println("Executing onceOneMinuteAfterStartup()"); } // end::initialDelay[] // tag::configured[] @Scheduled(fixedRate = "${my.task.rate:5m}", initialDelay = "${my.task.delay:1m}") void configuredTask() { System.out.println("Executing configuredTask()"); } // end::configured[] }
ScheduledExample
java
google__dagger
javatests/dagger/hilt/android/AndroidEntryPointBaseClassTest.java
{ "start": 3124, "end": 3195 }
class ____ extends SS {} @AndroidEntryPoint(L.class) public static
SSS
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/TopologyDescription.java
{ "start": 5466, "end": 5736 }
interface ____ extends Node { /** * The names of all connected stores. * @return set of store names */ @SuppressWarnings("unused") Set<String> stores(); } /** * A sink node of a topology. */
Processor
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java
{ "start": 4771, "end": 5438 }
class ____ { * * private ServiceFactory myServiceFactory; * * // actual implementation provided by the Spring container * public void setServiceFactory(ServiceFactory myServiceFactory) { * this.myServiceFactory = myServiceFactory; * } * * public void someBusinessMethod() { * // get a 'fresh', brand new MyService instance * MyService service = this.myServiceFactory.getService(); * // use the service object to effect the business logic... * } *}</pre> * * <p>By way of an example that looks up a bean <b>by name</b>, consider * the following service locator interface. Again, note that this *
MyClientBean
java
google__guava
guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
{ "start": 32876, "end": 33088 }
class ____ { private FactoryMethodReturnsNullButNotAnnotated() {} static FactoryMethodReturnsNullButNotAnnotated returnsNull() { return null; } } static
FactoryMethodReturnsNullButNotAnnotated
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/idgenerator/SequenceGeneratorIncrementTest.java
{ "start": 8456, "end": 8676 }
class ____ { @Id @GeneratedValue(generator = "seq_gen") @SequenceGenerator(name = "seq_gen", allocationSize = 20) private Long id; private String name; } @Entity(name = "TestEntity5") public static
TestEntity4
java
elastic__elasticsearch
distribution/tools/server-cli/src/test/java/org/elasticsearch/server/cli/ServerCliTests.java
{ "start": 19491, "end": 19925 }
interface ____ { void autoconfig(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws UserException; } Consumer<ServerArgs> argsValidator; private final MockServerProcess mockServer = new MockServerProcess(); int mockServerExitCode = 0; AutoConfigMethod autoConfigCallback; private final MockAutoConfigCli AUTO_CONFIG_CLI = new MockAutoConfigCli();
AutoConfigMethod
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/reflect/TypeUtilsTest.java
{ "start": 5638, "end": 5700 }
class ____<B> extends AbstractLangTest { public
TypeUtilsTest
java
quarkusio__quarkus
extensions/undertow/spi/src/main/java/io/quarkus/undertow/deployment/HttpHandlerWrapperBuildItem.java
{ "start": 144, "end": 412 }
class ____ extends MultiBuildItem { private final HandlerWrapper value; public HttpHandlerWrapperBuildItem(HandlerWrapper value) { this.value = value; } public HandlerWrapper getValue() { return value; } }
HttpHandlerWrapperBuildItem
java
apache__flink
flink-architecture-tests/flink-architecture-tests-base/src/main/java/org/apache/flink/architecture/common/Predicates.java
{ "start": 8621, "end": 8907 }
class ____ is empty from: " + fqClassName); } return className; } private Predicates() {} /** * A predicate to determine if a {@link JavaClass} contains one or more {@link JavaField } * matching the supplied predicate. */ private static
name
java
google__dagger
javatests/dagger/hilt/android/processor/internal/aggregateddeps/EarlyEntryPointProcessorTest.java
{ "start": 1506, "end": 2599 }
interface ____ {}"); HiltCompilerTests.hiltCompiler(entryPoint) .compile( subject -> { subject.hasErrorCount(1); subject .hasErrorContaining( "Only one of the following annotations can be used on" + " test.UsedWithEntryPoint: [dagger.hilt.EntryPoint," + " dagger.hilt.android.EarlyEntryPoint]") .onSource(entryPoint) .onLine(11); }); } @Test public void testNotSingletonComponent_fails() { Source entryPoint = HiltCompilerTests.javaSource( "test.NotSingletonComponent", "package test;", "", "import dagger.hilt.android.EarlyEntryPoint;", "import dagger.hilt.android.components.ActivityComponent;", "import dagger.hilt.EntryPoint;", "import dagger.hilt.InstallIn;", "", "@EarlyEntryPoint", "@InstallIn(ActivityComponent.class)", "public
UsedWithEntryPoint
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/WebAppConfigurationNestedTests.java
{ "start": 2357, "end": 2571 }
class ____ { @Test void test(ApplicationContext context) { assertThat(context).isNotInstanceOf(WebApplicationContext.class); } } @Nested @SpringJUnitWebConfig(Config.class)
ConfigOverriddenByDefaultTests
java
grpc__grpc-java
netty/src/test/java/io/grpc/netty/NettyWritableBufferTest.java
{ "start": 967, "end": 1518 }
class ____ extends WritableBufferTestBase { private NettyWritableBuffer buffer; @Before public void setup() { buffer = new NettyWritableBuffer(Unpooled.buffer(100)); } @After public void teardown() { buffer.release(); } @Override protected WritableBuffer buffer() { return buffer; } @Override protected byte[] writtenBytes() { byte[] b = buffer.bytebuf().array(); int fromIdx = buffer.bytebuf().arrayOffset(); return Arrays.copyOfRange(b, fromIdx, buffer.readableBytes()); } }
NettyWritableBufferTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/fs/LimitedConnectionsFileSystem.java
{ "start": 25317, "end": 27263 }
class ____ { /** The tracked stream. */ private final StreamWithTimeout stream; /** * The number of bytes written the last time that the {@link #checkNewBytesAndMark(long)} * method was called. It is important to initialize this with {@code -1} so that the first * check (0 bytes) always appears to have made progress. */ private volatile long lastCheckBytes = -1; /** The timestamp when the last inactivity evaluation was made. */ private volatile long lastCheckTimestampNanos; StreamProgressTracker(StreamWithTimeout stream) { this.stream = stream; } /** Gets the timestamp when the last inactivity evaluation was made. */ public long getLastCheckTimestampNanos() { return lastCheckTimestampNanos; } /** * Checks whether there were new bytes since the last time this method was invoked. This * also sets the given timestamp, to be read via {@link #getLastCheckTimestampNanos()}. * * @return True, if there were new bytes, false if not. */ public boolean checkNewBytesAndMark(long timestamp) throws IOException { // remember the time when checked lastCheckTimestampNanos = timestamp; final long bytesNow = stream.getPos(); if (bytesNow > lastCheckBytes) { lastCheckBytes = bytesNow; return true; } else { return false; } } } // ------------------------------------------------------------------------ /** * A data output stream that wraps a given data output stream and un-registers from a given * connection-limiting file system (via {@link * LimitedConnectionsFileSystem#unregisterOutputStream(OutStream)} upon closing. */ private static final
StreamProgressTracker
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/erroneous/supermappingwithsubclassmapper/ErroneousPropertyMappingTest.java
{ "start": 704, "end": 2090 }
class ____ { @ProcessorTest @WithClasses( ErroneousMapper1.class ) @IssueKey( "598" ) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic( kind = javax.tools.Diagnostic.Kind.ERROR, type = ErroneousMapper1.class, line = 11, messageRegExp = "Can't map property \"UnmappableClass property\" to \"String property\"\\. " + "Consider to declare/implement a mapping method: \"String map\\(UnmappableClass value\\)\"\\. " + "Occured at 'TARGET map\\(SOURCE source\\)' in 'AbstractMapper'\\.") } ) public void testUnmappableSourcePropertyInSuperclass() { } @ProcessorTest @WithClasses( ErroneousMapper2.class ) @IssueKey( "598" ) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic( kind = javax.tools.Diagnostic.Kind.ERROR, type = ErroneousMapper2.class, line = 13, message = "Can't map property \"UnmappableClass property\" to \"String property\". " + "Consider to declare/implement a mapping method: \"String map(UnmappableClass value)\".") } ) public void testMethodOverride() { } }
ErroneousPropertyMappingTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java
{ "start": 21179, "end": 21674 }
class ____ { @Autowired void useAuthenticationManager(AuthenticationConfiguration auth) throws Exception { auth.getAuthenticationManager(); } // Ensures that Sec2822UseAuth is initialized before Sec2822WebSecurity // must have additional GlobalAuthenticationConfigurerAdapter to trigger SEC-2822 @Bean static GlobalAuthenticationConfigurerAdapter bootGlobalAuthenticationConfigurerAdapter() { return new BootGlobalAuthenticationConfigurerAdapter(); } static
Sec2822UseAuth
java
quarkusio__quarkus
integration-tests/spring-web/src/main/java/io/quarkus/it/spring/cache/SpringCacheController.java
{ "start": 333, "end": 720 }
class ____ { final CachedGreetingService cachedGreetingService; public SpringCacheController(CachedGreetingService cachedGreetingService) { this.cachedGreetingService = cachedGreetingService; } @GetMapping(path = "/greet/{name}") public Greeting greet(@PathVariable String name) { return cachedGreetingService.greet(name); } }
SpringCacheController
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/CreatesDuplicateCallHeuristicTest.java
{ "start": 3800, "end": 4506 }
class ____ { // BUG: Diagnostic contains: true Object o1 = target(getFirst(), getSecond()); // BUG: Diagnostic contains: true Object o2 = target(getFirst(), getSecond()); abstract Object getFirst(); abstract Object getSecond(); abstract Object target(Object first, Object second); } """) .doTest(); } @Test public void createsDuplicateCall_returnsTrue_withDuplicateEnclosingMethod() { CompilationTestHelper.newInstance(CreatesDuplicateCallHeuristicChecker.class, getClass()) .addSourceLines( "Test.java", """ abstract
Test
java
apache__camel
components/camel-as2/camel-as2-api/src/main/java/org/apache/camel/component/as2/api/exception/AS2InsufficientSecurityException.java
{ "start": 1021, "end": 1351 }
class ____ extends AS2ErrorDispositionException { public AS2InsufficientSecurityException(String message) { super(message); } @Override public AS2DispositionModifier getDispositionModifier() { return AS2DispositionModifier.ERROR_INSUFFICIENT_MESSAGE_SECURITY; } }
AS2InsufficientSecurityException
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/builtin/AbstractToXmlGregorianCalendar.java
{ "start": 693, "end": 1794 }
class ____ extends BuiltInMethod { private final Type returnType; private final Set<Type> importTypes; private final Type dataTypeFactoryType; public AbstractToXmlGregorianCalendar(TypeFactory typeFactory) { this.returnType = typeFactory.getType( XmlConstants.JAVAX_XML_XML_GREGORIAN_CALENDAR ); this.dataTypeFactoryType = typeFactory.getType( XmlConstants.JAVAX_XML_DATATYPE_FACTORY ); this.importTypes = asSet( returnType, dataTypeFactoryType, typeFactory.getType( XmlConstants.JAVAX_XML_DATATYPE_CONFIGURATION_EXCEPTION ) ); } @Override public Set<Type> getImportTypes() { return importTypes; } @Override public Type getReturnType() { return returnType; } @Override public FieldReference getFieldReference() { return new FinalField( dataTypeFactoryType, "datatypeFactory" ); } @Override public ConstructorFragment getConstructorFragment() { return new NewDatatypeFactoryConstructorFragment( ); } }
AbstractToXmlGregorianCalendar
java
apache__spark
sql/core/src/test/gen-java/org/apache/spark/sql/execution/datasources/parquet/test/avro/CompatibilityTest.java
{ "start": 204, "end": 3057 }
interface ____ { public static final org.apache.avro.Protocol PROTOCOL = org.apache.avro.Protocol.parse("{\"protocol\":\"CompatibilityTest\",\"namespace\":\"org.apache.spark.sql.execution.datasources.parquet.test.avro\",\"types\":[{\"type\":\"enum\",\"name\":\"Suit\",\"symbols\":[\"SPADES\",\"HEARTS\",\"DIAMONDS\",\"CLUBS\"]},{\"type\":\"record\",\"name\":\"ParquetEnum\",\"fields\":[{\"name\":\"suit\",\"type\":\"Suit\"}]},{\"type\":\"record\",\"name\":\"Nested\",\"fields\":[{\"name\":\"nested_ints_column\",\"type\":{\"type\":\"array\",\"items\":\"int\"}},{\"name\":\"nested_string_column\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}}]},{\"type\":\"record\",\"name\":\"AvroPrimitives\",\"fields\":[{\"name\":\"bool_column\",\"type\":\"boolean\"},{\"name\":\"int_column\",\"type\":\"int\"},{\"name\":\"long_column\",\"type\":\"long\"},{\"name\":\"float_column\",\"type\":\"float\"},{\"name\":\"double_column\",\"type\":\"double\"},{\"name\":\"binary_column\",\"type\":\"bytes\"},{\"name\":\"string_column\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"}}]},{\"type\":\"record\",\"name\":\"AvroOptionalPrimitives\",\"fields\":[{\"name\":\"maybe_bool_column\",\"type\":[\"null\",\"boolean\"]},{\"name\":\"maybe_int_column\",\"type\":[\"null\",\"int\"]},{\"name\":\"maybe_long_column\",\"type\":[\"null\",\"long\"]},{\"name\":\"maybe_float_column\",\"type\":[\"null\",\"float\"]},{\"name\":\"maybe_double_column\",\"type\":[\"null\",\"double\"]},{\"name\":\"maybe_binary_column\",\"type\":[\"null\",\"bytes\"]},{\"name\":\"maybe_string_column\",\"type\":[\"null\",{\"type\":\"string\",\"avro.java.string\":\"String\"}]}]},{\"type\":\"record\",\"name\":\"AvroNonNullableArrays\",\"fields\":[{\"name\":\"strings_column\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"avro.java.string\":\"String\"}}},{\"name\":\"maybe_ints_column\",\"type\":[\"null\",{\"type\":\"array\",\"items\":\"int\"}]}]},{\"type\":\"record\",\"name\":\"AvroArrayOfArray\",\"fields\":[{\"name\":\"int_arrays_column\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":\"int\"}}}]},{\"type\":\"record\",\"name\":\"AvroMapOfArray\",\"fields\":[{\"name\":\"string_to_ints_column\",\"type\":{\"type\":\"map\",\"values\":{\"type\":\"array\",\"items\":\"int\"},\"avro.java.string\":\"String\"}}]},{\"type\":\"record\",\"name\":\"ParquetAvroCompat\",\"fields\":[{\"name\":\"strings_column\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"avro.java.string\":\"String\"}}},{\"name\":\"string_to_int_column\",\"type\":{\"type\":\"map\",\"values\":\"int\",\"avro.java.string\":\"String\"}},{\"name\":\"complex_column\",\"type\":{\"type\":\"map\",\"values\":{\"type\":\"array\",\"items\":\"Nested\"},\"avro.java.string\":\"String\"}}]}],\"messages\":{}}"); @SuppressWarnings("all") public
CompatibilityTest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java
{ "start": 38839, "end": 44947 }
class ____ implements Serializable { private static final long serialVersionUID = -8634075037355293699L; private final String loggerFQCN; private final Marker marker; private final Level level; private final String loggerName; // transient since 2.8 private final transient Message message; /** @since 2.8 */ private MarshalledObject<Message> marshalledMessage; /** @since 2.8 */ private String messageString; private final long timeMillis; /** @since 2.11 */ private final int nanoOfMillisecond; private final transient Throwable thrown; private final ThrowableProxy thrownProxy; /** @since 2.7 */ private final StringMap contextData; private final ThreadContext.ContextStack contextStack; /** @since 2.6 */ private final long threadId; private final String threadName; /** @since 2.6 */ private final int threadPriority; private final StackTraceElement source; private final boolean isLocationRequired; private final boolean isEndOfBatch; /** @since 2.4 */ private final transient long nanoTime; public LogEventProxy(final Log4jLogEvent event, final boolean includeLocation) { this.loggerFQCN = event.loggerFqcn; this.marker = event.marker; this.level = event.level; this.loggerName = event.loggerName; this.message = event.message instanceof ReusableMessage ? memento((ReusableMessage) event.message) : event.message; this.timeMillis = event.instant.getEpochMillisecond(); this.nanoOfMillisecond = event.instant.getNanoOfMillisecond(); this.thrown = event.thrown; this.thrownProxy = event.getThrownProxy(); this.contextData = event.contextData; this.contextStack = event.contextStack; this.source = includeLocation ? event.getSource() : event.source; this.threadId = event.getThreadId(); this.threadName = event.getThreadName(); this.threadPriority = event.getThreadPriority(); this.isLocationRequired = includeLocation; this.isEndOfBatch = event.endOfBatch; this.nanoTime = event.nanoTime; } public LogEventProxy(final LogEvent event, final boolean includeLocation) { this.loggerFQCN = event.getLoggerFqcn(); this.marker = event.getMarker(); this.level = event.getLevel(); this.loggerName = event.getLoggerName(); final Message temp = event.getMessage(); message = temp instanceof ReusableMessage ? memento((ReusableMessage) temp) : temp; this.timeMillis = event.getInstant().getEpochMillisecond(); this.nanoOfMillisecond = event.getInstant().getNanoOfMillisecond(); this.thrown = event.getThrown(); this.thrownProxy = event.getThrownProxy(); this.contextData = memento(event.getContextData()); this.contextStack = event.getContextStack(); // In the case `includeLocation` is false, we temporarily disable its computation. if (event.isIncludeLocation() && !includeLocation) { event.setIncludeLocation(false); this.source = event.getSource(); event.setIncludeLocation(true); } else { this.source = event.getSource(); } this.threadId = event.getThreadId(); this.threadName = event.getThreadName(); this.threadPriority = event.getThreadPriority(); this.isLocationRequired = includeLocation; this.isEndOfBatch = event.isEndOfBatch(); this.nanoTime = event.getNanoTime(); } private static Message memento(final ReusableMessage message) { return message.memento(); } private static StringMap memento(final ReadOnlyStringMap data) { final StringMap result = ContextDataFactory.createContextData(); result.putAll(data); return result; } private static MarshalledObject<Message> marshall(final Message msg) { try { return new MarshalledObject<>(msg); } catch (final Exception ex) { return null; } } private void writeObject(final java.io.ObjectOutputStream s) throws IOException { this.messageString = message.getFormattedMessage(); this.marshalledMessage = marshall(message); s.defaultWriteObject(); } /** * Returns a Log4jLogEvent using the data in the proxy. * @return Log4jLogEvent. */ protected Object readResolve() { final Log4jLogEvent result = new Log4jLogEvent( loggerName, marker, loggerFQCN, level, message(), // `thrown` is always null after deserialization thrownProxy != null ? thrownProxy.getThrowable() : null, contextData, contextStack, threadId, threadName, threadPriority, source, timeMillis, nanoOfMillisecond, nanoTime); result.setEndOfBatch(isEndOfBatch); result.setIncludeLocation(isLocationRequired); result.thrownProxy = thrownProxy; return result; } private Message message() { if (marshalledMessage != null) { try { return marshalledMessage.get(); } catch (final Exception ex) { // ignore me } } return new SimpleMessage(messageString); } } }
LogEventProxy
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/SecurityRestFilterTests.java
{ "start": 3707, "end": 16898 }
class ____ extends ESTestCase { private ThreadContext threadContext; private AuthenticationService authcService; private SecondaryAuthenticator secondaryAuthenticator; private RestChannel channel; private SecurityRestFilter filter; private RestHandler restHandler; @Before public void init() throws Exception { authcService = mock(AuthenticationService.class); channel = mock(RestChannel.class); restHandler = mock(RestHandler.class); threadContext = new ThreadContext(Settings.EMPTY); secondaryAuthenticator = new SecondaryAuthenticator(Settings.EMPTY, threadContext, authcService, new AuditTrailService(null, null)); filter = getFilter(NOOP_OPERATOR_PRIVILEGES_SERVICE); } private SecurityRestFilter getFilter(OperatorPrivileges.OperatorPrivilegesService privilegesService) { return new SecurityRestFilter(true, threadContext, secondaryAuthenticator, new AuditTrailService(null, null), privilegesService); } public void testProcess() throws Exception { RestRequest request = mock(RestRequest.class); when(request.getHttpChannel()).thenReturn(mock(HttpChannel.class)); HttpRequest httpRequest = mock(HttpRequest.class); when(request.getHttpRequest()).thenReturn(httpRequest); Authentication authentication = AuthenticationTestHelper.builder().build(); doAnswer((i) -> { @SuppressWarnings("unchecked") ActionListener<Authentication> callback = (ActionListener<Authentication>) i.getArguments()[1]; callback.onResponse(authentication); return Void.TYPE; }).when(authcService).authenticate(eq(httpRequest), anyActionListener()); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); assertThat(future.get(), is(Boolean.TRUE)); verifyNoMoreInteractions(channel); } public void testProcessSecondaryAuthentication() throws Exception { RestRequest request = mock(RestRequest.class); when(channel.request()).thenReturn(request); when(request.getHttpChannel()).thenReturn(mock(HttpChannel.class)); HttpRequest httpRequest = mock(HttpRequest.class); when(request.getHttpRequest()).thenReturn(httpRequest); Authentication primaryAuthentication = AuthenticationTestHelper.builder().build(); doAnswer(i -> { final Object[] arguments = i.getArguments(); @SuppressWarnings("unchecked") ActionListener<Authentication> callback = (ActionListener<Authentication>) arguments[arguments.length - 1]; callback.onResponse(primaryAuthentication); return null; }).when(authcService).authenticate(eq(httpRequest), anyActionListener()); Authentication secondaryAuthentication = AuthenticationTestHelper.builder().build(); doAnswer(i -> { final Object[] arguments = i.getArguments(); @SuppressWarnings("unchecked") ActionListener<Authentication> callback = (ActionListener<Authentication>) arguments[arguments.length - 1]; callback.onResponse(secondaryAuthentication); return null; }).when(authcService).authenticate(eq(httpRequest), eq(false), anyActionListener()); SecurityContext securityContext = new SecurityContext(Settings.EMPTY, threadContext); final String credentials = randomAlphaOfLengthBetween(4, 8) + ":" + randomAlphaOfLengthBetween(4, 12); threadContext.putHeader( SecondaryAuthenticator.SECONDARY_AUTH_HEADER_NAME, "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharset.UTF_8)) ); AtomicReference<SecondaryAuthentication> secondaryAuthRef = new AtomicReference<>(); ActionListener<Boolean> listener = ActionListener.wrap(proceed -> { assertThat(proceed, is(Boolean.TRUE)); secondaryAuthRef.set(securityContext.getSecondaryAuthentication()); }, ex -> { throw new RuntimeException(ex); }); filter.intercept(request, channel, restHandler, listener); verifyNoMoreInteractions(channel); assertThat(secondaryAuthRef.get(), notNullValue()); assertThat(secondaryAuthRef.get().getAuthentication(), sameInstance(secondaryAuthentication)); } public void testProcessWithSecurityDisabled() throws Exception { filter = new SecurityRestFilter(false, threadContext, secondaryAuthenticator, mock(AuditTrailService.class), null); assertEquals(NOOP_OPERATOR_PRIVILEGES_SERVICE, filter.getOperatorPrivilegesService()); RestRequest request = mock(RestRequest.class); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); assertThat(future.get(), is(Boolean.TRUE)); verifyNoMoreInteractions(channel, authcService); } public void testProcessOptionsMethod() throws Exception { FakeRestRequest request = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withMethod(RestRequest.Method.OPTIONS).build(); when(channel.request()).thenReturn(request); when(channel.newErrorBuilder()).thenReturn(JsonXContent.contentBuilder()); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); final ElasticsearchSecurityException ex = expectThrows(ElasticsearchSecurityException.class, future::actionGet); assertThat(ex, TestMatchers.throwableWithMessage(containsString("Cannot dispatch OPTIONS request, as they are not authenticated"))); verifyNoMoreInteractions(restHandler); verifyNoMoreInteractions(authcService); } public void testProcessFiltersBodyCorrectly() throws Exception { FakeRestRequest restRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withContent( new BytesArray("{\"password\": \"" + SecuritySettingsSourceField.TEST_PASSWORD + "\", \"foo\": \"bar\"}"), XContentType.JSON ).build(); when(channel.request()).thenReturn(restRequest); restHandler = new FilteredRestHandler() { @Override public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) {} @Override public Set<String> getFilteredFields() { return Collections.singleton("password"); } }; AuditTrail auditTrail = mock(AuditTrail.class); XPackLicenseState licenseState = TestUtils.newTestLicenseState(); SetOnce<RestRequest> auditTrailRequest = new SetOnce<>(); doAnswer((i) -> { auditTrailRequest.set((RestRequest) i.getArguments()[0]); return Void.TYPE; }).when(auditTrail).authenticationSuccess(any(RestRequest.class)); filter = new SecurityRestFilter( true, threadContext, secondaryAuthenticator, new AuditTrailService(auditTrail, licenseState), NOOP_OPERATOR_PRIVILEGES_SERVICE ); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(restRequest, channel, restHandler, future); assertThat(future.get(), is(Boolean.TRUE)); assertNotEquals(restRequest, auditTrailRequest.get()); assertNotEquals(restRequest.content(), auditTrailRequest.get().content()); Map<String, Object> map; try ( var parser = XContentType.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, auditTrailRequest.get().content().streamInput() ) ) { map = parser.map(); } assertEquals(1, map.size()); assertEquals("bar", map.get("foo")); } public void testSanitizeHeaders() throws Exception { for (boolean failRequest : List.of(true, false)) { threadContext.putHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, randomAlphaOfLengthBetween(1, 10)); RestRequest request = mock(RestRequest.class); when(request.getHttpChannel()).thenReturn(mock(HttpChannel.class)); HttpRequest httpRequest = mock(HttpRequest.class); when(request.getHttpRequest()).thenReturn(httpRequest); Authentication authentication = AuthenticationTestHelper.builder().build(); doAnswer((i) -> { @SuppressWarnings("unchecked") ActionListener<Authentication> callback = (ActionListener<Authentication>) i.getArguments()[1]; if (failRequest) { callback.onFailure(new RuntimeException()); } else { callback.onResponse(authentication); } return Void.TYPE; }).when(authcService).authenticate(eq(httpRequest), anyActionListener()); Set<String> foundKeys = threadContext.getHeaders().keySet(); assertThat(foundKeys, hasItem(UsernamePasswordToken.BASIC_AUTH_HEADER)); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); assertThat(future.get(), is(Boolean.TRUE)); foundKeys = threadContext.getHeaders().keySet(); assertThat(foundKeys, not(hasItem(UsernamePasswordToken.BASIC_AUTH_HEADER))); } } public void testProcessWithWorkflow() throws Exception { final Workflow workflow = randomFrom(WorkflowResolver.allWorkflows()); restHandler = new TestBaseRestHandler(randomFrom(workflow.allowedRestHandlers())); filter = new SecurityRestFilter(true, threadContext, secondaryAuthenticator, new AuditTrailService(null, null), null); RestRequest request = mock(RestRequest.class); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); assertThat(future.get(), is(Boolean.TRUE)); assertThat(WorkflowService.readWorkflowFromThreadContext(threadContext), equalTo(workflow.name())); } public void testProcessWithoutWorkflow() throws Exception { if (randomBoolean()) { String restHandlerName = randomValueOtherThanMany( name -> WorkflowResolver.resolveWorkflowForRestHandler(name) != null, () -> randomAlphaOfLengthBetween(3, 6) ); restHandler = new TestBaseRestHandler(restHandlerName); } else { restHandler = Mockito.mock(RestHandler.class); } filter = new SecurityRestFilter(true, threadContext, secondaryAuthenticator, new AuditTrailService(null, null), null); RestRequest request = mock(RestRequest.class); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); assertThat(future.get(), is(Boolean.TRUE)); assertThat(WorkflowService.readWorkflowFromThreadContext(threadContext), nullValue()); } public void testCheckRest() throws Exception { for (Boolean isOperator : new Boolean[] { Boolean.TRUE, Boolean.FALSE }) { RestRequest request = mock(RestRequest.class); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { SecurityRestFilter filter = getFilter(new OperatorPrivileges.OperatorPrivilegesService() { @Override public void maybeMarkOperatorUser(Authentication authentication, ThreadContext threadContext) {} @Override public ElasticsearchSecurityException check( Authentication authentication, String action, TransportRequest request, ThreadContext threadContext ) { return null; } @Override public boolean checkRest( RestHandler restHandler, RestRequest restRequest, RestChannel restChannel, ThreadContext threadContext ) { return isOperator; } @Override public void maybeInterceptRequest(ThreadContext threadContext, TransportRequest request) {} }); PlainActionFuture<Boolean> future = new PlainActionFuture<>(); filter.intercept(request, channel, restHandler, future); if (isOperator) { assertThat(future.get(), is(Boolean.TRUE)); } else { assertThat(future.get(), is(Boolean.FALSE)); } } } } private
SecurityRestFilterTests
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/config/builder/EngineImpl.java
{ "start": 726, "end": 1846 }
class ____ implements Engine { private final int cylinders; private final String manufacturer; private final CrankShaft crankShaft; private final SparkPlug sparkPlug; EngineImpl(String manufacturer, int cylinders, CrankShaft crankShaft, SparkPlug sparkPlug) { this.crankShaft = crankShaft; this.cylinders = cylinders; this.manufacturer = manufacturer; this.sparkPlug = sparkPlug; } @Override public int getCylinders() { return cylinders; } @Override public String start() { return new StringBuilder() .append(manufacturer) .append(' ') .append("Engine Starting V") .append(cylinders) .append(" [rodLength=") .append(crankShaft.rodLength.orElse(6.0d)) .append(", sparkPlug=") .append(sparkPlug) .append(']').toString(); } static Builder builder() { return new Builder(); } static final
EngineImpl
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/oidc/web/authentication/OidcLogoutAuthenticationSuccessHandler.java
{ "start": 2501, "end": 5507 }
class ____ implements AuthenticationSuccessHandler { private final Log logger = LogFactory.getLog(getClass()); private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private final SecurityContextLogoutHandler securityContextLogoutHandler = new SecurityContextLogoutHandler(); private LogoutHandler logoutHandler = this::performLogout; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { if (!(authentication instanceof OidcLogoutAuthenticationToken)) { if (this.logger.isErrorEnabled()) { this.logger.error(Authentication.class.getSimpleName() + " must be of type " + OidcLogoutAuthenticationToken.class.getName() + " but was " + authentication.getClass().getName()); } OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "Unable to process the OpenID Connect 1.0 RP-Initiated Logout response.", null); throw new OAuth2AuthenticationException(error); } this.logoutHandler.logout(request, response, authentication); sendLogoutRedirect(request, response, authentication); } /** * Sets the {@link LogoutHandler} used for performing logout. * @param logoutHandler the {@link LogoutHandler} used for performing logout */ public void setLogoutHandler(LogoutHandler logoutHandler) { Assert.notNull(logoutHandler, "logoutHandler cannot be null"); this.logoutHandler = logoutHandler; } private void performLogout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { OidcLogoutAuthenticationToken oidcLogoutAuthentication = (OidcLogoutAuthenticationToken) authentication; // Check for active user session if (oidcLogoutAuthentication.isPrincipalAuthenticated()) { this.securityContextLogoutHandler.logout(request, response, (Authentication) oidcLogoutAuthentication.getPrincipal()); } } private void sendLogoutRedirect(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { OidcLogoutAuthenticationToken oidcLogoutAuthentication = (OidcLogoutAuthenticationToken) authentication; String redirectUri = "/"; if (oidcLogoutAuthentication.isAuthenticated() && StringUtils.hasText(oidcLogoutAuthentication.getPostLogoutRedirectUri())) { // Use the `post_logout_redirect_uri` parameter UriComponentsBuilder uriBuilder = UriComponentsBuilder .fromUriString(oidcLogoutAuthentication.getPostLogoutRedirectUri()); if (StringUtils.hasText(oidcLogoutAuthentication.getState())) { uriBuilder.queryParam(OAuth2ParameterNames.STATE, UriUtils.encode(oidcLogoutAuthentication.getState(), StandardCharsets.UTF_8)); } // build(true) -> Components are explicitly encoded redirectUri = uriBuilder.build(true).toUriString(); } this.redirectStrategy.sendRedirect(request, response, redirectUri); } }
OidcLogoutAuthenticationSuccessHandler
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/locking/JoinedInheritancePessimisticLockingTest.java
{ "start": 2992, "end": 3121 }
class ____ extends BaseThing { @Basic(optional = false) @Column(nullable = false) String anotherProp; } }
AnotherConcreteThing
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builder/abstractBuilder/ImmutableProduct.java
{ "start": 622, "end": 992 }
class ____ extends AbstractProductBuilder<ImmutableProduct> { private Integer price; public ImmutableProductBuilder price(Integer price) { this.price = price; return this; } @Override public ImmutableProduct build() { return new ImmutableProduct( this ); } } }
ImmutableProductBuilder
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertContains_at_Index_Test.java
{ "start": 1644, "end": 7416 }
class ____ extends DoubleArraysBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), null, 8d, someIndex())) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_is_empty() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), emptyArray(), 8d, someIndex())) .withMessage(actualIsEmpty()); } @Test void should_throw_error_if_Index_is_null() { assertThatNullPointerException().isThrownBy(() -> arrays.assertContains(someInfo(), actual, 8d, null)) .withMessage("Index should not be null"); } @Test void should_throw_error_if_Index_is_out_of_bounds() { assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> arrays.assertContains(someInfo(), actual, 8d, atIndex(6))) .withMessageContaining("Index should be between <0> and <2> (inclusive) but was:%n <6>".formatted()); } @Test void should_fail_if_actual_does_not_contain_value_at_index() { double value = 6; Index index = atIndex(1); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), actual, value, index)) .withMessage(shouldContainAtIndex(actual, value, index, 8d).create()); } @Test void should_pass_if_actual_contains_value_at_index() { arrays.assertContains(someInfo(), actual, 8d, atIndex(1)); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), null, -8d, someIndex())) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_is_empty_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), emptyArray(), -8d, someIndex())) .withMessage(actualIsEmpty()); } @Test void should_throw_error_if_Index_is_null_whatever_custom_comparison_strategy_is() { assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), actual, -8d, null)) .withMessage("Index should not be null"); } @Test void should_throw_error_if_Index_is_out_of_bounds_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), actual, -8d, atIndex(6))) .withMessageContaining("Index should be between <0> and <2> (inclusive) but was:%n <6>".formatted()); } @Test void should_fail_if_actual_does_not_contain_value_at_index_according_to_custom_comparison_strategy() { double value = 6; Index index = atIndex(1); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertContains(someInfo(), actual, value, index)) .withMessage(shouldContainAtIndex(actual, value, index, 8d, absValueComparisonStrategy).create()); } @Test void should_pass_if_actual_contains_value_at_index_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertContains(someInfo(), actual, -8d, atIndex(1)); } }
DoubleArrays_assertContains_at_Index_Test
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeXAttr.java
{ "start": 1339, "end": 2904 }
class ____ extends FSXAttrBaseTest { private static final Path linkParent = new Path("/symdir1"); private static final Path targetParent = new Path("/symdir2"); private static final Path link = new Path(linkParent, "link"); private static final Path target = new Path(targetParent, "target"); @Test @Timeout(value = 120) public void testXAttrSymlinks() throws Exception { fs.mkdirs(linkParent); fs.mkdirs(targetParent); DFSTestUtil.createFile(fs, target, 1024, (short)3, 0xBEEFl); fs.createSymlink(target, link, false); fs.setXAttr(target, name1, value1); fs.setXAttr(target, name2, value2); Map<String, byte[]> xattrs = fs.getXAttrs(link); assertEquals(xattrs.size(), 2); assertArrayEquals(value1, xattrs.get(name1)); assertArrayEquals(value2, xattrs.get(name2)); fs.setXAttr(link, name3, null); xattrs = fs.getXAttrs(target); assertEquals(xattrs.size(), 3); assertArrayEquals(value1, xattrs.get(name1)); assertArrayEquals(value2, xattrs.get(name2)); assertArrayEquals(new byte[0], xattrs.get(name3)); fs.removeXAttr(link, name1); xattrs = fs.getXAttrs(target); assertEquals(xattrs.size(), 2); assertArrayEquals(value2, xattrs.get(name2)); assertArrayEquals(new byte[0], xattrs.get(name3)); fs.removeXAttr(target, name3); xattrs = fs.getXAttrs(link); assertEquals(xattrs.size(), 1); assertArrayEquals(value2, xattrs.get(name2)); fs.delete(linkParent, true); fs.delete(targetParent, true); } }
TestNameNodeXAttr
java
apache__flink
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/position/SqlTableColumnPosition.java
{ "start": 1529, "end": 3617 }
class ____ extends SqlCall { private static final SqlOperator OPERATOR = new SqlSpecialOperator("SqlTableColumnPosition", SqlKind.OTHER); private final SqlTableColumn column; @Nullable private final SqlLiteral positionSpec; @Nullable private final SqlIdentifier referencedColumn; public SqlTableColumnPosition( SqlParserPos pos, SqlTableColumn column, @Nullable SqlLiteral positionSpec, @Nullable SqlIdentifier referencedColumn) { super(pos); this.column = column; this.positionSpec = positionSpec; this.referencedColumn = referencedColumn; } public boolean isFirstColumn() { return positionSpec != null && positionSpec.getValueAs(SqlColumnPosSpec.class) == SqlColumnPosSpec.FIRST; } public boolean isAfterReferencedColumn() { return positionSpec != null && positionSpec.getValueAs(SqlColumnPosSpec.class) == SqlColumnPosSpec.AFTER && referencedColumn != null; } public SqlTableColumn getColumn() { return column; } public SqlLiteral getPositionSpec() { return positionSpec; } @Nullable public SqlIdentifier getAfterReferencedColumn() { return referencedColumn; } @Nonnull @Override public SqlOperator getOperator() { return OPERATOR; } @Nonnull @Override public List<SqlNode> getOperandList() { return ImmutableNullableList.of(column, positionSpec, referencedColumn); } @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { column.unparse(writer, leftPrec, rightPrec); if (isFirstColumn()) { positionSpec.unparse(writer, leftPrec, rightPrec); } else if (isAfterReferencedColumn()) { positionSpec.unparse(writer, leftPrec, rightPrec); referencedColumn.unparse(writer, leftPrec, rightPrec); } else { // default no refer other column } } }
SqlTableColumnPosition
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/impl/TaskQueue.java
{ "start": 9524, "end": 9757 }
class ____ implements Task { private final Runnable runnable; private final Executor exec; public ExecuteTask(Runnable runnable, Executor exec) { this.runnable = runnable; this.exec = exec; } } }
ExecuteTask
java
elastic__elasticsearch
benchmarks/src/main/java/org/elasticsearch/benchmark/index/mapper/KeywordFieldMapperBenchmark.java
{ "start": 1498, "end": 4066 }
class ____ { private MapperService mapperService; private SourceToParse sourceToParse; @Setup public void setUp() { this.mapperService = MapperServiceFactory.create(""" { "_doc": { "dynamic": false, "properties": { "host": { "type": "keyword", "store": true }, "name": { "type": "keyword" }, "type": { "type": "keyword", "normalizer": "lowercase" }, "uuid": { "type": "keyword", "doc_values": false }, "version": { "type": "keyword" }, "extra_field": { "type": "keyword" }, "extra_field_text": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 1024 } } }, "nested_object": { "properties": { "keyword_nested": { "type": "keyword" }, "text_nested": { "type": "text" }, "number_nested": { "type": "long" } } } } } } \s"""); this.sourceToParse = new SourceToParse(UUIDs.randomBase64UUID(), new BytesArray(""" { "host": "some_value", "name": "some_other_thing", "type": "some_type_thing", "uuid": "some_keyword_uuid", "version": "some_version", "extra_field_text": "bla bla text", "nested_object" : { "keyword_nested": "some random nested keyword", "text_nested": "some random nested text", "number_nested": 123234234 } }"""), XContentType.JSON); } @Benchmark public List<LuceneDocument> benchmarkParseKeywordFields() { return mapperService.documentMapper().parse(sourceToParse).docs(); } }
KeywordFieldMapperBenchmark
java
spring-projects__spring-security
access/src/test/java/org/springframework/security/access/expression/method/PrePostAnnotationSecurityMetadataSourceTests.java
{ "start": 1817, "end": 8824 }
class ____ { private PrePostAnnotationSecurityMetadataSource mds = new PrePostAnnotationSecurityMetadataSource( new ExpressionBasedAnnotationAttributeFactory(new DefaultMethodSecurityExpressionHandler())); private MockMethodInvocation voidImpl1; private MockMethodInvocation voidImpl2; private MockMethodInvocation voidImpl3; private MockMethodInvocation listImpl1; private MockMethodInvocation notherListImpl1; private MockMethodInvocation notherListImpl2; private MockMethodInvocation annotatedAtClassLevel; private MockMethodInvocation annotatedAtInterfaceLevel; private MockMethodInvocation annotatedAtMethodLevel; @BeforeEach public void setUpData() throws Exception { this.voidImpl1 = new MockMethodInvocation(new ReturnVoidImpl1(), ReturnVoid.class, "doSomething", List.class); this.voidImpl2 = new MockMethodInvocation(new ReturnVoidImpl2(), ReturnVoid.class, "doSomething", List.class); this.voidImpl3 = new MockMethodInvocation(new ReturnVoidImpl3(), ReturnVoid.class, "doSomething", List.class); this.listImpl1 = new MockMethodInvocation(new ReturnAListImpl1(), ReturnAList.class, "doSomething", List.class); this.notherListImpl1 = new MockMethodInvocation(new ReturnAnotherListImpl1(), ReturnAnotherList.class, "doSomething", List.class); this.notherListImpl2 = new MockMethodInvocation(new ReturnAnotherListImpl2(), ReturnAnotherList.class, "doSomething", List.class); this.annotatedAtClassLevel = new MockMethodInvocation(new CustomAnnotationAtClassLevel(), ReturnVoid.class, "doSomething", List.class); this.annotatedAtInterfaceLevel = new MockMethodInvocation(new CustomAnnotationAtInterfaceLevel(), ReturnVoid2.class, "doSomething", List.class); this.annotatedAtMethodLevel = new MockMethodInvocation(new CustomAnnotationAtMethodLevel(), ReturnVoid.class, "doSomething", List.class); } @Test public void classLevelPreAnnotationIsPickedUpWhenNoMethodLevelExists() { ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl1).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue(); PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; assertThat(pre.getAuthorizeExpression()).isNotNull(); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("someExpression"); assertThat(pre.getFilterExpression()).isNull(); } @Test public void mixedClassAndMethodPreAnnotationsAreBothIncluded() { ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl2).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue(); PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("someExpression"); assertThat(pre.getFilterExpression()).isNotNull(); assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("somePreFilterExpression"); } @Test public void methodWithPreFilterOnlyIsAllowed() { ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl3).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue(); PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("permitAll"); assertThat(pre.getFilterExpression()).isNotNull(); assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("somePreFilterExpression"); } @Test public void methodWithPostFilterOnlyIsAllowed() { ConfigAttribute[] attrs = this.mds.getAttributes(this.listImpl1).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(2); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue(); assertThat(attrs[1] instanceof PostInvocationExpressionAttribute).isTrue(); PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; PostInvocationExpressionAttribute post = (PostInvocationExpressionAttribute) attrs[1]; assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("permitAll"); assertThat(post.getFilterExpression()).isNotNull(); assertThat(post.getFilterExpression().getExpressionString()).isEqualTo("somePostFilterExpression"); } @Test public void interfaceAttributesAreIncluded() { ConfigAttribute[] attrs = this.mds.getAttributes(this.notherListImpl1).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue(); PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; assertThat(pre.getFilterExpression()).isNotNull(); assertThat(pre.getAuthorizeExpression()).isNotNull(); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("interfaceMethodAuthzExpression"); assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("interfacePreFilterExpression"); } @Test public void classAttributesTakesPrecedeceOverInterfaceAttributes() { ConfigAttribute[] attrs = this.mds.getAttributes(this.notherListImpl2).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue(); PreInvocationExpressionAttribute pre = (PreInvocationExpressionAttribute) attrs[0]; assertThat(pre.getFilterExpression()).isNotNull(); assertThat(pre.getAuthorizeExpression()).isNotNull(); assertThat(pre.getAuthorizeExpression().getExpressionString()).isEqualTo("interfaceMethodAuthzExpression"); assertThat(pre.getFilterExpression().getExpressionString()).isEqualTo("classMethodPreFilterExpression"); } @Test public void customAnnotationAtClassLevelIsDetected() { ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtClassLevel).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); } @Test public void customAnnotationAtInterfaceLevelIsDetected() { ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtInterfaceLevel) .toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); } @Test public void customAnnotationAtMethodLevelIsDetected() { ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtMethodLevel).toArray(new ConfigAttribute[0]); assertThat(attrs).hasSize(1); } @Test public void proxyFactoryInterfaceAttributesFound() throws Exception { MockMethodInvocation mi = MethodInvocationFactory.createSec2150MethodInvocation(); Collection<ConfigAttribute> attributes = this.mds.getAttributes(mi); assertThat(attributes).hasSize(1); Expression expression = (Expression) ReflectionTestUtils.getField(attributes.iterator().next(), "authorizeExpression"); assertThat(expression.getExpressionString()).isEqualTo("hasRole('ROLE_PERSON')"); } public
PrePostAnnotationSecurityMetadataSourceTests
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenCustomizer.java
{ "start": 1034, "end": 1259 }
interface ____<T extends OAuth2TokenContext> { /** * Customize the OAuth 2.0 Token attributes. * @param context the context containing the OAuth 2.0 Token attributes */ void customize(T context); }
OAuth2TokenCustomizer
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationAllPermitsAcquisitionTests.java
{ "start": 5011, "end": 21317 }
class ____ extends IndexShardTestCase { private ClusterService clusterService; private TransportService transportService; private ShardStateAction shardStateAction; private ShardId shardId; private IndexShard primary; private IndexShard replica; private boolean globalBlock; private ClusterBlock block; @Override @Before public void setUp() throws Exception { super.setUp(); globalBlock = randomBoolean(); RestStatus restStatus = randomFrom(RestStatus.values()); block = new ClusterBlock(randomIntBetween(1, 10), randomAlphaOfLength(5), false, true, false, restStatus, ClusterBlockLevel.ALL); clusterService = createClusterService(threadPool); final ClusterState.Builder state = ClusterState.builder(clusterService.state()); Set<DiscoveryNodeRole> roles = new HashSet<>(DiscoveryNodeRole.roles()); DiscoveryNode node1 = DiscoveryNodeUtils.builder("_node1").name("_name1").roles(roles).build(); DiscoveryNode node2 = DiscoveryNodeUtils.builder("_node2").name("_name2").roles(roles).build(); state.nodes(DiscoveryNodes.builder().add(node1).add(node2).localNodeId(node1.getId()).masterNodeId(node1.getId())); shardId = new ShardId("index", UUID.randomUUID().toString(), 0); ShardRouting shardRouting = shardRoutingBuilder(shardId, node1.getId(), true, ShardRoutingState.INITIALIZING).withRecoverySource( RecoverySource.EmptyStoreRecoverySource.INSTANCE ).build(); Settings indexSettings = indexSettings(IndexVersion.current(), 1, 1).put(SETTING_INDEX_UUID, shardId.getIndex().getUUID()) .put(SETTING_CREATION_DATE, System.currentTimeMillis()) .build(); primary = newStartedShard(p -> newShard(shardRouting, indexSettings, new InternalEngineFactory()), true); for (int i = 0; i < 10; i++) { final String id = Integer.toString(i); indexDoc(primary, "_doc", id, "{\"value\":" + id + "}"); } IndexMetadata indexMetadata = IndexMetadata.builder(shardId.getIndexName()) .settings(indexSettings) .primaryTerm(shardId.id(), primary.getOperationPrimaryTerm()) .putMapping(""" { "properties": { "value": { "type": "short"}}}""") .build(); state.metadata(Metadata.builder().put(indexMetadata, false).generateClusterUuidIfNeeded()); replica = newShard(primary.shardId(), false, node2.getId(), indexMetadata, null); recoverReplica(replica, primary, true); IndexRoutingTable.Builder routing = IndexRoutingTable.builder(indexMetadata.getIndex()); routing.addIndexShard(new IndexShardRoutingTable.Builder(shardId).addShard(primary.routingEntry())); state.routingTable(RoutingTable.builder().add(routing.build()).build()); setState(clusterService, state.build()); final Settings transportSettings = Settings.builder().put("node.name", node1.getId()).build(); MockTransport transport = new MockTransport() { @Override protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) { assertThat(action, allOf(startsWith("cluster:admin/test/"), endsWith("[r]"))); assertThat(node, equalTo(node2)); // node2 doesn't really exist, but we are performing some trickery in mockIndicesService() to pretend that node1 holds both // the primary and the replica, so redirect the request back to node1. transportService.sendRequest( transportService.getLocalNode(), action, request, new TransportResponseHandler<TransportReplicationAction.ReplicaResponse>() { @Override public TransportReplicationAction.ReplicaResponse read(StreamInput in) throws IOException { return new TransportReplicationAction.ReplicaResponse(in); } @SuppressWarnings("unchecked") private TransportResponseHandler<TransportReplicationAction.ReplicaResponse> getResponseHandler() { return (TransportResponseHandler<TransportReplicationAction.ReplicaResponse>) getResponseHandlers() .onResponseReceived(requestId, TransportMessageListener.NOOP_LISTENER); } @Override public Executor executor() { return TransportResponseHandler.TRANSPORT_WORKER; } @Override public void handleResponse(TransportReplicationAction.ReplicaResponse response) { getResponseHandler().handleResponse(response); } @Override public void handleException(TransportException exp) { getResponseHandler().handleException(exp); } } ); } }; transportService = transport.createTransportService( transportSettings, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, bta -> node1, null, emptySet() ); transportService.start(); transportService.acceptIncomingRequests(); shardStateAction = new ShardStateAction(clusterService, transportService, null, null, threadPool); } @Override @After public void tearDown() throws Exception { closeShards(primary, replica); transportService.stop(); clusterService.close(); super.tearDown(); } public void testTransportReplicationActionWithAllPermits() throws Exception { final int numOperations = scaledRandomIntBetween(4, 32); final int delayedOperations = randomIntBetween(1, numOperations); logger.trace( "starting [{}] operations, among which the first [{}] started ops should be blocked by [{}]", numOperations, delayedOperations, block ); final CyclicBarrier delayedOperationsBarrier = new CyclicBarrier(delayedOperations + 1); final List<Thread> threads = new ArrayList<>(delayedOperationsBarrier.getParties()); @SuppressWarnings({ "rawtypes", "unchecked" }) final PlainActionFuture<Response>[] futures = new PlainActionFuture[numOperations]; final TestAction[] actions = new TestAction[numOperations]; for (int i = 0; i < numOperations; i++) { final int threadId = i; final boolean delayed = (threadId < delayedOperations); final PlainActionFuture<Response> listener = new PlainActionFuture<>(); futures[threadId] = listener; final TestAction singlePermitAction = new SinglePermitWithBlocksAction( Settings.EMPTY, "cluster:admin/test/single_permit[" + threadId + "]", transportService, clusterService, shardStateAction, threadPool, shardId, primary, replica, globalBlock ); actions[threadId] = singlePermitAction; Thread thread = new Thread(() -> { final TransportReplicationAction.ConcreteShardRequest<Request> primaryRequest = new TransportReplicationAction.ConcreteShardRequest<>(request(), allocationId(), primaryTerm()); @SuppressWarnings("rawtypes") TransportReplicationAction.AsyncPrimaryAction asyncPrimaryAction = singlePermitAction.new AsyncPrimaryAction( primaryRequest, listener, null ) { @Override protected void doRun() throws Exception { if (delayed) { logger.trace("op [{}] has started and will resume execution once allPermitsAction is terminated", threadId); delayedOperationsBarrier.await(); } super.doRun(); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) void runWithPrimaryShardReference(final TransportReplicationAction.PrimaryShardReference reference) { assertThat(reference.indexShard.getActiveOperationsCount(), greaterThan(0)); assertSame(primary, reference.indexShard); assertBlockIsPresentForDelayedOp(); super.runWithPrimaryShardReference(reference); } @Override public void onFailure(Exception e) { assertBlockIsPresentForDelayedOp(); super.onFailure(e); } private void assertBlockIsPresentForDelayedOp() { if (delayed) { final ClusterState clusterState = clusterService.state(); if (globalBlock) { assertTrue("Global block must exist", clusterState.blocks().hasGlobalBlock(block)); } else { String indexName = primary.shardId().getIndexName(); assertTrue("Index block must exist", clusterState.blocks().hasIndexBlock(indexName, block)); } } } }; asyncPrimaryAction.run(); }); threads.add(thread); thread.start(); } logger.trace("now starting the operation that acquires all permits and sets the block in the cluster state"); // An action which acquires all operation permits during execution and set a block final TestAction allPermitsAction = new AllPermitsThenBlockAction( Settings.EMPTY, "cluster:admin/test/all_permits", transportService, clusterService, shardStateAction, threadPool, shardId, primary, replica ); final PlainActionFuture<Response> allPermitFuture = new PlainActionFuture<>(); Thread thread = new Thread(() -> { @SuppressWarnings("rawtypes") final TransportReplicationAction.ConcreteShardRequest<Request> primaryRequest = new TransportReplicationAction.ConcreteShardRequest<>(request(), allocationId(), primaryTerm()); @SuppressWarnings("rawtypes") TransportReplicationAction.AsyncPrimaryAction asyncPrimaryAction = allPermitsAction.new AsyncPrimaryAction( primaryRequest, allPermitFuture, null ) { @Override @SuppressWarnings({ "rawtypes", "unchecked" }) void runWithPrimaryShardReference(final TransportReplicationAction.PrimaryShardReference reference) { assertEquals( "All permits must be acquired", IndexShard.OPERATIONS_BLOCKED, reference.indexShard.getActiveOperationsCount() ); assertSame(primary, reference.indexShard); final ClusterState clusterState = clusterService.state(); final ClusterBlocks.Builder blocks = ClusterBlocks.builder(); if (globalBlock) { assertFalse("Global block must not exist yet", clusterState.blocks().hasGlobalBlock(block)); blocks.addGlobalBlock(block); } else { String indexName = reference.indexShard.shardId().getIndexName(); assertFalse("Index block must not exist yet", clusterState.blocks().hasIndexBlock(indexName, block)); blocks.addIndexBlock(indexName, block); } logger.trace("adding test block to cluster state {}", block); setState(clusterService, ClusterState.builder(clusterState).blocks(blocks)); try { logger.trace("releasing delayed operations"); delayedOperationsBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { onFailure(e); } super.runWithPrimaryShardReference(reference); } }; asyncPrimaryAction.run(); }); threads.add(thread); thread.start(); logger.trace("waiting for all operations to terminate"); for (Thread t : threads) { t.join(); } final Response allPermitsResponse = allPermitFuture.get(); assertSuccessfulOperation(allPermitsAction, allPermitsResponse); for (int i = 0; i < numOperations; i++) { final PlainActionFuture<Response> future = futures[i]; final TestAction action = actions[i]; if (i < delayedOperations) { ExecutionException exception = expectThrows(ExecutionException.class, "delayed operation should have failed", future::get); assertFailedOperation(action, exception); } else { // non delayed operation might fail depending on the order they were executed try { assertSuccessfulOperation(action, futures[i].get()); } catch (final ExecutionException e) { assertFailedOperation(action, e); } } } assertWarnings( "[indices.merge.scheduler.use_thread_pool] setting was deprecated in Elasticsearch and will be removed in a future release. " + "See the breaking changes documentation for the next major version." ); } private void assertSuccessfulOperation(final TestAction action, final Response response) { final String name = action.getActionName(); assertThat(name + " operation should have been executed on primary", action.executedOnPrimary.get(), is(true)); assertThat(name + " operation should have been executed on replica", action.executedOnReplica.get(), is(true)); assertThat(name + " operation must have a non null result", response, notNullValue()); assertThat(name + " operation should have been successful on 2 shards", response.getShardInfo().getSuccessful(), equalTo(2)); } private void assertFailedOperation(final TestAction action, final ExecutionException exception) { final String name = action.getActionName(); assertThat(name + " operation should not have been executed on primary", action.executedOnPrimary.get(), nullValue()); assertThat(name + " operation should not have been executed on replica", action.executedOnReplica.get(), nullValue()); assertThat(exception.getCause(), instanceOf(ClusterBlockException.class)); ClusterBlockException clusterBlockException = (ClusterBlockException) exception.getCause(); assertThat(clusterBlockException.blocks(), hasItem(equalTo(block))); } private long primaryTerm() { return primary.getOperationPrimaryTerm(); } private String allocationId() { return primary.routingEntry().allocationId().getId(); } private Request request() { return new Request(primary.shardId()); } /** * A type of {@link TransportReplicationAction} that allows to use the primary and replica shards passed to the constructor for the * execution of the replication action. Also records if the operation is executed on the primary and the replica. */ private abstract
TransportReplicationAllPermitsAcquisitionTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/idgenerator/TableGeneratorsTest.java
{ "start": 1400, "end": 3396 }
class ____ { private static final int INITIAL_VALUE = 5; private static final int EXPECTED_DB_INSERTED_VALUE = INITIAL_VALUE; @Test public void testTableGeneratorIsGenerated(DomainModelScope modelScope, @TempDir File tmpDir) throws Exception { final var scriptFile = new File( tmpDir, "update_script.sql" ); final var metadata = modelScope.getDomainModel(); metadata.orderColumns( true ); metadata.validate(); new SchemaExport() .setOutputFile( scriptFile.getAbsolutePath() ) .create( EnumSet.of( TargetType.SCRIPT ), metadata ); final List<String> commands = Files.readAllLines( scriptFile.toPath() ); final String expectedTestEntityTableCreationCommand = "CREATE TABLE TEST_ENTITY \\(ID .*, PRIMARY KEY \\(ID\\)\\);"; Assertions.assertTrue( isCommandGenerated( commands, expectedTestEntityTableCreationCommand ), "The command '" + expectedTestEntityTableCreationCommand + "' has not been correctly generated" ); final String expectedIdTableGeneratorCreationCommand = "CREATE TABLE ID_TABLE_GENERATOR \\(VALUE .*, PK .*, PRIMARY KEY \\(PK\\)\\);"; Assertions.assertTrue( isCommandGenerated( commands, expectedIdTableGeneratorCreationCommand ), "The command '" + expectedIdTableGeneratorCreationCommand + "' has not been correctly generated" ); final String expectedInsertIntoTableGeneratorCommand = "INSERT INTO ID_TABLE_GENERATOR\\(PK, VALUE\\) VALUES \\('TEST_ENTITY_ID'," + EXPECTED_DB_INSERTED_VALUE + "\\);"; Assertions.assertTrue( isCommandGenerated( commands, expectedInsertIntoTableGeneratorCommand ), "The command '" + expectedInsertIntoTableGeneratorCommand + "' has not been correctly generated" ); } @Entity(name = "TestEntity") @Table(name = "TEST_ENTITY") @TableGenerator(name = "tableGenerator", table = "ID_TABLE_GENERATOR", pkColumnName = "PK", pkColumnValue = "TEST_ENTITY_ID", valueColumnName = "VALUE", allocationSize = 3, initialValue = INITIAL_VALUE ) public static
TableGeneratorsTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/engine/LiveVersionMap.java
{ "start": 1453, "end": 6182 }
class ____ { /** Tracks bytes used by current map, i.e. what is freed on refresh. For deletes, which are also added to tombstones, * we only account for the CHM entry here, and account for BytesRef/VersionValue against the tombstones, since refresh would not * clear this from RAM. */ final AtomicLong ramBytesUsed = new AtomicLong(); private static final VersionLookup EMPTY = new VersionLookup(Collections.emptyMap()); private final Map<BytesRef, VersionValue> map; // each version map has a notion of safe / unsafe which allows us to apply certain optimization in the auto-generated ID usecase // where we know that documents can't have any duplicates so we can skip the version map entirely. This reduces // the memory pressure significantly for this use-case where we often get a massive amount of small document (metrics). // if the version map is in safeAccess mode we track all version in the version map. yet if a document comes in that needs // safe access but we are not in this mode we force a refresh and make the map as safe access required. All subsequent ops will // respect that and fill the version map. The nice part here is that we are only really requiring this for a single ID and since // we hold the ID lock in the engine while we do all this it's safe to do it globally unlocked. // NOTE: these values can both be non-volatile since it's ok to read a stale value per doc ID. We serialize changes in the engine // that will prevent concurrent updates to the same document ID and therefore we can rely on the happens-before guanratee of the // map reference itself. private boolean unsafe; // minimum timestamp of delete operations that were made while this map was active. this is used to make sure they are kept in // the tombstone private final AtomicLong minDeleteTimestamp = new AtomicLong(Long.MAX_VALUE); // Modifies the map of this instance by merging with the given VersionLookup public void merge(VersionLookup versionLookup) { long existingEntriesSize = 0; for (var entry : versionLookup.map.entrySet()) { var existingValue = map.get(entry.getKey()); existingEntriesSize += existingValue == null ? 0 : mapEntryBytesUsed(entry.getKey(), existingValue); } map.putAll(versionLookup.map); adjustRamUsage(versionLookup.ramBytesUsed() - existingEntriesSize); minDeleteTimestamp.accumulateAndGet(versionLookup.minDeleteTimestamp(), Math::min); } // Visible for testing VersionLookup(Map<BytesRef, VersionValue> map) { this.map = map; } public VersionValue get(BytesRef key) { return map.get(key); } VersionValue put(BytesRef key, VersionValue value) { long ramAccounting = mapEntryBytesUsed(key, value); VersionValue previousValue = map.put(key, value); ramAccounting += previousValue == null ? 0 : -mapEntryBytesUsed(key, previousValue); adjustRamUsage(ramAccounting); return previousValue; } public boolean isEmpty() { return map.isEmpty(); } int size() { return map.size(); } public boolean isUnsafe() { return unsafe; } void markAsUnsafe() { unsafe = true; } VersionValue remove(BytesRef uid) { VersionValue previousValue = map.remove(uid); if (previousValue != null) { adjustRamUsage(-mapEntryBytesUsed(uid, previousValue)); } return previousValue; } public void updateMinDeletedTimestamp(DeleteVersionValue delete) { minDeleteTimestamp.accumulateAndGet(delete.time, Math::min); } public long minDeleteTimestamp() { return minDeleteTimestamp.get(); } void adjustRamUsage(long value) { if (value != 0) { long v = ramBytesUsed.addAndGet(value); assert v >= 0 : "bytes=" + v; } } public long ramBytesUsed() { return ramBytesUsed.get(); } public static long mapEntryBytesUsed(BytesRef key, VersionValue value) { return (BASE_BYTES_PER_BYTESREF + key.bytes.length) + (BASE_BYTES_PER_CHM_ENTRY + value.ramBytesUsed()); } // Used only for testing Map<BytesRef, VersionValue> getMap() { return map; } } private static final
VersionLookup
java
google__guava
guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/Uninterruptibles.java
{ "start": 894, "end": 1281 }
class ____ { private Uninterruptibles() {} @CanIgnoreReturnValue public static <V extends @Nullable Object> V getUninterruptibly(Future<V> future) throws ExecutionException { try { return future.get(); } catch (InterruptedException e) { // Should never be thrown in GWT but play it safe throw new IllegalStateException(e); } } }
Uninterruptibles
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Web3jEndpointBuilderFactory.java
{ "start": 47519, "end": 49602 }
interface ____ { /** * Web3j Ethereum Blockchain (camel-web3j) * Interact with Ethereum nodes using web3j client API. * * Category: blockchain * Since: 2.22 * Maven coordinates: org.apache.camel:camel-web3j * * @return the dsl builder for the headers' name. */ default Web3jHeaderNameBuilder web3j() { return Web3jHeaderNameBuilder.INSTANCE; } /** * Web3j Ethereum Blockchain (camel-web3j) * Interact with Ethereum nodes using web3j client API. * * Category: blockchain * Since: 2.22 * Maven coordinates: org.apache.camel:camel-web3j * * Syntax: <code>web3j:nodeAddress</code> * * Path parameter: nodeAddress (required) * Sets the node address used to communicate * * @param path nodeAddress * @return the dsl builder */ default Web3jEndpointBuilder web3j(String path) { return Web3jEndpointBuilderFactory.endpointBuilder("web3j", path); } /** * Web3j Ethereum Blockchain (camel-web3j) * Interact with Ethereum nodes using web3j client API. * * Category: blockchain * Since: 2.22 * Maven coordinates: org.apache.camel:camel-web3j * * Syntax: <code>web3j:nodeAddress</code> * * Path parameter: nodeAddress (required) * Sets the node address used to communicate * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path nodeAddress * @return the dsl builder */ default Web3jEndpointBuilder web3j(String componentName, String path) { return Web3jEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Web3j Ethereum Blockchain component. */ public static
Web3jBuilders
java
redisson__redisson
redisson-hibernate/redisson-hibernate-52/src/main/java/org/redisson/hibernate/strategy/NonStrictReadWriteEntityRegionAccessStrategy.java
{ "start": 1228, "end": 3961 }
class ____ extends BaseRegionAccessStrategy implements EntityRegionAccessStrategy { public NonStrictReadWriteEntityRegionAccessStrategy(Settings settings, GeneralDataRegion region) { super(settings, region); } @Override public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException { return region.get(session, key); } @Override public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { if (minimalPutOverride && region.contains(key)) { return false; } region.put(session, key, value); return true; } @Override public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws CacheException { return null; } @Override public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException { evict(key); } @Override public EntityRegion getRegion() { return (EntityRegion) region; } @Override public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException { return false; } @Override public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException { return false; } @Override public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { remove(session, key); return false; } @Override public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { unlockItem(session, key, lock); return false; } @Override public void remove(SharedSessionContractImplementor session, Object key) throws CacheException { evict(key); } @Override public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { return ((RedissonEntityRegion)region).getCacheKeysFactory().createEntityKey( id, persister, factory, tenantIdentifier ); } @Override public Object getCacheKeyId(Object cacheKey) { return ((RedissonEntityRegion)region).getCacheKeysFactory().getEntityId( cacheKey ); } }
NonStrictReadWriteEntityRegionAccessStrategy
java
micronaut-projects__micronaut-core
context/src/main/java/io/micronaut/scheduling/NextFireTime.java
{ "start": 974, "end": 2160 }
class ____ implements Supplier<Duration> { private Duration duration; private ZonedDateTime nextFireTime; private final CronExpression cron; private final ZoneId zoneId; /** * Default constructor. * * @param cron A cron expression */ NextFireTime(CronExpression cron) { this(cron, ZoneId.systemDefault()); } /** * @param cron A cron expression * @param zoneId The zoneId to base the cron expression on */ NextFireTime(CronExpression cron, ZoneId zoneId) { this.cron = cron; this.zoneId = zoneId; nextFireTime = ZonedDateTime.now(zoneId); } @Override public Duration get() { ZonedDateTime now = ZonedDateTime.now(zoneId); // check if the task have fired too early computeNextFireTime(now.isAfter(nextFireTime) ? now : nextFireTime); return duration; } private void computeNextFireTime(ZonedDateTime currentFireTime) { nextFireTime = cron.nextTimeAfter(currentFireTime); duration = Duration.ofMillis(nextFireTime.toInstant().toEpochMilli() - ZonedDateTime.now(zoneId).toInstant().toEpochMilli()); } }
NextFireTime
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/errors/StreamsUncaughtExceptionHandler.java
{ "start": 1335, "end": 2144 }
enum ____ { /** Replace the failed thread with a new one. */ REPLACE_THREAD(0, "REPLACE_THREAD"), /** Shut down the client. */ SHUTDOWN_CLIENT(1, "SHUTDOWN_KAFKA_STREAMS_CLIENT"), /** Try to shut down the whole application. */ SHUTDOWN_APPLICATION(2, "SHUTDOWN_KAFKA_STREAMS_APPLICATION"); /** * An english description for the used option. This is for debugging only and may change. */ public final String name; /** * The permanent and immutable id for the used option. This can't change ever. */ public final int id; StreamThreadExceptionResponse(final int id, final String name) { this.id = id; this.name = name; } } }
StreamThreadExceptionResponse
java
quarkusio__quarkus
extensions/reactive-mssql-client/runtime/src/main/java/io/quarkus/reactive/mssql/client/MSSQLPoolCreator.java
{ "start": 262, "end": 547 }
interface ____ an integration point that allows users to use the {@link Vertx}, {@link PoolOptions} and * {@link MSSQLConnectOptions} objects configured automatically by Quarkus, in addition to a custom strategy * for creating the final {@link Pool}. * <p> * Implementations of this
is
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/handler/BinaryWebSocketHandler.java
{ "start": 944, "end": 1240 }
class ____ {@link WebSocketHandler} implementations * that process binary messages only. * * <p>Text messages are rejected with {@link CloseStatus#NOT_ACCEPTABLE}. * All other methods have empty implementations. * * @author Rossen Stoyanchev * @author Phillip Webb * @since 4.0 */ public
for
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/type/TypeBindings.java
{ "start": 15518, "end": 15854 }
class ____ contains simple logic for avoiding repeated lookups via * {@link Class#getTypeParameters()} as that can be a performance issue for * some use cases (wasteful, usually one-off or not reusing mapper). * Partly isolated to avoid initialization for cases where no generic types are * used. */ static
that
java
spring-projects__spring-security
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserServiceTests.java
{ "start": 1210, "end": 3693 }
class ____ { @Test public void constructorWhenUserServicesIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingOAuth2UserService<>(null)); } @Test public void constructorWhenUserServicesIsEmptyThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DelegatingOAuth2UserService<>(Collections.emptyList())); } @Test @SuppressWarnings("unchecked") public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() { OAuth2UserService<OAuth2UserRequest, OAuth2User> userService = mock(OAuth2UserService.class); DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>( Arrays.asList(userService, userService)); assertThatIllegalArgumentException().isThrownBy(() -> delegatingUserService.loadUser(null)); } @Test @SuppressWarnings("unchecked") public void loadUserWhenUserServiceCanLoadThenReturnUser() { OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class); OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class); OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class); OAuth2User mockUser = mock(OAuth2User.class); given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser); DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>( Arrays.asList(userService1, userService2, userService3)); OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class)); assertThat(loadedUser).isEqualTo(mockUser); } @Test @SuppressWarnings("unchecked") public void loadUserWhenUserServiceCannotLoadThenReturnNull() { OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class); OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class); OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class); DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>( Arrays.asList(userService1, userService2, userService3)); OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class)); assertThat(loadedUser).isNull(); } }
DelegatingOAuth2UserServiceTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/TestMixinDeserForCreators.java
{ "start": 1324, "end": 1421 }
interface ____'t do, as they can't have * constructors or static methods. */ static
won
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/merge/BidirectionalOneToManyMergeTest.java
{ "start": 2574, "end": 3604 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String review; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "post_id") private Post post; public PostComment() { } public PostComment(String review, Post post) { this.review = review; this.post = post; } public Long getId() { return id; } public PostComment setId(Long id) { this.id = id; return this; } public String getReview() { return review; } public PostComment setReview(String review) { this.review = review; return this; } public Post getPost() { return post; } public PostComment setPost(Post post) { this.post = post; return this; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof PostComment) ) { return false; } return id != null && id.equals( ((PostComment) o).getId() ); } @Override public int hashCode() { return 31; } } }
PostComment
java
apache__flink
flink-examples/flink-examples-table/src/main/java/org/apache/flink/table/examples/java/basics/TemporalJoinSQLExample.java
{ "start": 6254, "end": 7326 }
class ____ { public String id; public Instant trxTime; public String currencyCode; // the rate comparing with euro public double amount; // for POJO detection in DataStream API public Transaction() {} // for structured type detection in Table API public Transaction(String id, Instant trxTime, String currencyCode, double amount) { this.id = id; this.trxTime = trxTime; this.currencyCode = currencyCode; this.amount = amount; } @Override public String toString() { return "Transaction{" + "id=" + id + ", trxTime=" + trxTime + ", currencyCode='" + currencyCode + '\'' + ", amount=" + amount + '}'; } } /** Enriched transaction by joining with the currency rate table. */ public static
Transaction
java
google__auto
common/src/test/java/com/google/auto/common/AnnotationMirrorsTest.java
{ "start": 2086, "end": 2146 }
interface ____ {} @SimpleAnnotation static
SimpleAnnotation
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertHasSizeGreaterThanOrEqualTo_Test.java
{ "start": 1063, "end": 2409 }
class ____ extends DoubleArraysBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertHasSizeGreaterThanOrEqualTo(someInfo(), null, 6)) .withMessage(actualIsNull()); } @Test void should_fail_if_size_of_actual_is_not_greater_than_or_equal_to_boundary() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertHasSizeGreaterThanOrEqualTo(someInfo(), actual, 6)) .withMessage(shouldHaveSizeGreaterThanOrEqualTo(actual, actual.length, 6).create()); } @Test void should_pass_if_size_of_actual_is_greater_than_boundary() { arrays.assertHasSizeGreaterThanOrEqualTo(someInfo(), actual, 1); } @Test void should_pass_if_size_of_actual_is_equal_to_boundary() { arrays.assertHasSizeGreaterThanOrEqualTo(someInfo(), actual, actual.length); } }
DoubleArrays_assertHasSizeGreaterThanOrEqualTo_Test
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/controllers/OperatorControllerTest.java
{ "start": 2155, "end": 5413 }
class ____ { @InjectMocks private OperatorController operatorController; @Mock private SwitchDomain switchDomain; @Mock private SwitchManager switchManager; @Mock private ServerStatusManager serverStatusManager; @Mock private ClientManager clientManager; @Mock private DistroMapper distroMapper; @BeforeEach void setUp() { MockEnvironment environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); } @Test void testPushState() { MetricsMonitor.resetPush(); ObjectNode objectNode = operatorController.pushState(true, true); assertTrue(objectNode.toString().contains("succeed\":0")); } @Test void testSwitchDomain() { SwitchDomain switchDomain = operatorController.switches(new MockHttpServletRequest()); assertEquals(this.switchDomain, switchDomain); } @Test void testUpdateSwitch() { try { String res = operatorController.updateSwitch(true, "test", "test"); assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test void testMetrics() { Mockito.when(serverStatusManager.getServerStatus()).thenReturn(ServerStatus.UP); Collection<String> clients = new HashSet<>(); clients.add("1628132208793_127.0.0.1_8080"); clients.add("127.0.0.1:8081#true"); clients.add("127.0.0.1:8082#false"); Mockito.when(clientManager.allClientId()).thenReturn(clients); Client client = new IpPortBasedClient("127.0.0.1:8081#true", true); client.addServiceInstance(Service.newService("", "", ""), new InstancePublishInfo()); Mockito.when(clientManager.getClient("127.0.0.1:8081#true")).thenReturn(client); Mockito.when(clientManager.isResponsibleClient(client)).thenReturn(Boolean.TRUE); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter("onlyStatus", "false"); ObjectNode objectNode = operatorController.metrics(servletRequest); assertEquals(1, objectNode.get("responsibleInstanceCount").asInt()); assertEquals(ServerStatus.UP.toString(), objectNode.get("status").asText()); assertEquals(3, objectNode.get("clientCount").asInt()); assertEquals(1, objectNode.get("connectionBasedClientCount").asInt()); assertEquals(1, objectNode.get("ephemeralIpPortClientCount").asInt()); assertEquals(1, objectNode.get("persistentIpPortClientCount").asInt()); assertEquals(1, objectNode.get("responsibleClientCount").asInt()); } @Test void testGetResponsibleServer4Client() { Mockito.when(distroMapper.mapSrv(Mockito.anyString())).thenReturn("test"); ObjectNode objectNode = operatorController.getResponsibleServer4Client("test", "test"); assertEquals("test", objectNode.get("responsibleServer").asText()); } @Test void testSetLogLevel() { String res = operatorController.setLogLevel("test", "info"); assertEquals("ok", res); } }
OperatorControllerTest
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/ConsumeJmsMapMessageTest.java
{ "start": 1882, "end": 5102 }
class ____ extends AbstractJMSTest { @Order(2) @RegisterExtension public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension(); private static final Logger LOG = LoggerFactory.getLogger(ConsumeJmsMapMessageTest.class); protected JmsTemplate jmsTemplate; protected CamelContext context; protected ProducerTemplate template; protected ConsumerTemplate consumer; private MockEndpoint endpoint; @Test public void testConsumeMapMessage() throws Exception { endpoint.expectedMessageCount(1); jmsTemplate.setPubSubDomain(false); jmsTemplate.send("test.map", session -> { MapMessage mapMessage = session.createMapMessage(); mapMessage.setString("foo", "abc"); mapMessage.setString("bar", "xyz"); return mapMessage; }); endpoint.assertIsSatisfied(); assertCorrectMapReceived(); } protected void assertCorrectMapReceived() { Exchange exchange = endpoint.getReceivedExchanges().get(0); // This should be a JMS Exchange assertNotNull(ExchangeHelper.getBinding(exchange, JmsBinding.class)); JmsMessage in = exchange.getIn(JmsMessage.class); assertNotNull(in); Map<?, ?> map = exchange.getIn().getBody(Map.class); LOG.info("Received map: {}", map); assertNotNull(map, "Should have received a map message!"); assertIsInstanceOf(MapMessage.class, in.getJmsMessage()); assertEquals("abc", map.get("foo"), "map.foo"); assertEquals("xyz", map.get("bar"), "map.bar"); assertEquals(2, map.size(), "map.size"); } @Test public void testSendMapMessage() throws Exception { endpoint.expectedMessageCount(1); Map<String, String> map = new HashMap<>(); map.put("foo", "abc"); map.put("bar", "xyz"); template.sendBody("direct:test", map); endpoint.assertIsSatisfied(); assertCorrectMapReceived(); } @BeforeEach public void setUp() throws Exception { endpoint = getMockEndpoint("mock:result"); } @Override protected String getComponentName() { return "activemq"; } @Override protected JmsComponent setupComponent( CamelContext camelContext, ConnectionFactory connectionFactory, String componentName) { jmsTemplate = new JmsTemplate(connectionFactory); return super.setupComponent(camelContext, connectionFactory, componentName); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("activemq:test.map").to("mock:result"); from("direct:test").to("activemq:test.map"); } }; } @Override public CamelContextExtension getCamelContextExtension() { return camelContextExtension; } @BeforeEach void setUpRequirements() { context = camelContextExtension.getContext(); template = camelContextExtension.getProducerTemplate(); consumer = camelContextExtension.getConsumerTemplate(); } }
ConsumeJmsMapMessageTest
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/MonoFromPublisherTest.java
{ "start": 810, "end": 1061 }
class ____ { @Test public void scanOperator(){ MonoFromPublisher<String> test = new MonoFromPublisher<>(Flux.just("foo", "bar")); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } }
MonoFromPublisherTest
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/async/MyAsyncEndpoint.java
{ "start": 1117, "end": 2584 }
class ____ extends DefaultEndpoint { private String reply; private long delay = 25; private int failFirstAttempts; private boolean synchronous; public MyAsyncEndpoint(String endpointUri, Component component) { super(endpointUri, component); } @Override public Producer createProducer() { Producer answer = new MyAsyncProducer(this); if (isSynchronous()) { // force it to be synchronously return new SynchronousDelegateProducer(answer); } else { return answer; } } @Override public Consumer createConsumer(Processor processor) { throw new UnsupportedOperationException("Consumer not supported"); } @Override public boolean isSingleton() { return false; } public String getReply() { return reply; } public void setReply(String reply) { this.reply = reply; } public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public int getFailFirstAttempts() { return failFirstAttempts; } public void setFailFirstAttempts(int failFirstAttempts) { this.failFirstAttempts = failFirstAttempts; } public boolean isSynchronous() { return synchronous; } public void setSynchronous(boolean synchronous) { this.synchronous = synchronous; } }
MyAsyncEndpoint