language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/support/header/CloseTimerTask.java
{ "start": 1267, "end": 2692 }
class ____ extends AbstractTimerTask { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CloseTimerTask.class); private final int closeTimeout; public CloseTimerTask( ChannelProvider channelProvider, HashedWheelTimer hashedWheelTimer, Long tick, int closeTimeout) { super(channelProvider, hashedWheelTimer, tick); this.closeTimeout = closeTimeout; start(); } @Override protected void doTask(Channel channel) { try { Long lastRead = lastRead(channel); Long lastWrite = lastWrite(channel); Long now = now(); // check ping & pong at server if ((lastRead != null && now - lastRead > closeTimeout) || (lastWrite != null && now - lastWrite > closeTimeout)) { logger.warn( PROTOCOL_FAILED_RESPONSE, "", "", "Close channel " + channel + ", because idleCheck timeout: " + closeTimeout + "ms"); channel.close(); } } catch (Throwable t) { logger.warn( TRANSPORT_FAILED_CLOSE, "", "", "Exception when close remote channel " + channel.getRemoteAddress(), t); } } }
CloseTimerTask
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/collector/AppLevelTimelineCollectorWithAgg.java
{ "start": 4363, "end": 5588 }
class ____ implements Runnable { private void aggregate() { LOG.debug("App-level real-time aggregating"); if (!isReadyToAggregate()) { LOG.warn("App-level collector is not ready, skip aggregation. "); return; } try { TimelineCollectorContext currContext = getTimelineEntityContext(); Map<String, AggregationStatusTable> aggregationGroups = getAggregationGroups(); if (aggregationGroups == null || aggregationGroups.isEmpty()) { LOG.debug("App-level collector is empty, skip aggregation. "); return; } TimelineEntity resultEntity = TimelineCollector.aggregateWithoutGroupId( aggregationGroups, currContext.getAppId(), TimelineEntityType.YARN_APPLICATION.toString()); TimelineEntities entities = new TimelineEntities(); entities.addEntity(resultEntity); putEntitiesAsync(entities, getCurrentUser()); } catch (Exception e) { LOG.error("Error aggregating timeline metrics", e); } LOG.debug("App-level real-time aggregation complete"); } @Override public void run() { aggregate(); } } }
AppLevelAggregator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/node/shutdown/TransportPrevalidateShardPathAction.java
{ "start": 1961, "end": 5596 }
class ____ extends TransportNodesAction< PrevalidateShardPathRequest, PrevalidateShardPathResponse, NodePrevalidateShardPathRequest, NodePrevalidateShardPathResponse, Void> { public static final String ACTION_NAME = "internal:admin/indices/prevalidate_shard_path"; public static final ActionType<PrevalidateShardPathResponse> TYPE = new ActionType<>(ACTION_NAME); private static final Logger logger = LogManager.getLogger(TransportPrevalidateShardPathAction.class); private final TransportService transportService; private final NodeEnvironment nodeEnv; private final Settings settings; @Inject public TransportPrevalidateShardPathAction( ThreadPool threadPool, ClusterService clusterService, TransportService transportService, ActionFilters actionFilters, NodeEnvironment nodeEnv, Settings settings ) { super( ACTION_NAME, clusterService, transportService, actionFilters, NodePrevalidateShardPathRequest::new, threadPool.executor(ThreadPool.Names.MANAGEMENT) ); this.transportService = transportService; this.nodeEnv = nodeEnv; this.settings = settings; } @Override protected PrevalidateShardPathResponse newResponse( PrevalidateShardPathRequest request, List<NodePrevalidateShardPathResponse> nodeResponses, List<FailedNodeException> failures ) { return new PrevalidateShardPathResponse(clusterService.getClusterName(), nodeResponses, failures); } @Override protected NodePrevalidateShardPathRequest newNodeRequest(PrevalidateShardPathRequest request) { return new NodePrevalidateShardPathRequest(request.getShardIds()); } @Override protected NodePrevalidateShardPathResponse newNodeResponse(StreamInput in, DiscoveryNode node) throws IOException { return new NodePrevalidateShardPathResponse(in); } @Override protected NodePrevalidateShardPathResponse nodeOperation(NodePrevalidateShardPathRequest request, Task task) { Set<ShardId> localShards = new HashSet<>(); ShardPath shardPath = null; // For each shard we only check whether the shard path exists, regardless of whether the content is a valid index or not. for (ShardId shardId : request.getShardIds()) { try { var indexMetadata = clusterService.state().metadata().findIndex(shardId.getIndex()).orElse(null); String customDataPath = null; if (indexMetadata != null) { customDataPath = new IndexSettings(indexMetadata, settings).customDataPath(); } else { // The index is not known to this node. This shouldn't happen, but it can be safely ignored for this operation. logger.warn("node doesn't have metadata for the index [{}]", shardId.getIndex()); } shardPath = ShardPath.loadShardPath(logger, nodeEnv, shardId, customDataPath); if (shardPath != null) { localShards.add(shardId); } } catch (IOException e) { final String path = shardPath != null ? shardPath.resolveIndex().toString() : ""; logger.error(() -> String.format(Locale.ROOT, "error loading shard path for shard [%s]", shardId), e); } } return new NodePrevalidateShardPathResponse(transportService.getLocalNode(), localShards); } }
TransportPrevalidateShardPathAction
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java
{ "start": 19266, "end": 41201 }
class ____ { private ByteBuffer outputBuffer; private int messagesRead = 0; // Note that `bytesRead` should contain only bytes from batches that have been processed, i.e. bytes from // `messagesRead` and any discarded batches. private int bytesRead = 0; private int messagesRetained = 0; private int bytesRetained = 0; private long maxOffset = -1L; private long maxTimestamp = RecordBatch.NO_TIMESTAMP; private long shallowOffsetOfMaxTimestamp = -1L; private FilterResult(ByteBuffer outputBuffer) { this.outputBuffer = outputBuffer; } private void updateRetainedBatchMetadata(MutableRecordBatch retainedBatch, int numMessagesInBatch, boolean headerOnly) { int bytesRetained = headerOnly ? DefaultRecordBatch.RECORD_BATCH_OVERHEAD : retainedBatch.sizeInBytes(); updateRetainedBatchMetadata(retainedBatch.maxTimestamp(), retainedBatch.lastOffset(), retainedBatch.lastOffset(), numMessagesInBatch, bytesRetained); } private void updateRetainedBatchMetadata(long maxTimestamp, long shallowOffsetOfMaxTimestamp, long maxOffset, int messagesRetained, int bytesRetained) { validateBatchMetadata(maxTimestamp, shallowOffsetOfMaxTimestamp, maxOffset); if (maxTimestamp > this.maxTimestamp) { this.maxTimestamp = maxTimestamp; this.shallowOffsetOfMaxTimestamp = shallowOffsetOfMaxTimestamp; } this.maxOffset = Math.max(maxOffset, this.maxOffset); this.messagesRetained += messagesRetained; this.bytesRetained += bytesRetained; } private void validateBatchMetadata(long maxTimestamp, long shallowOffsetOfMaxTimestamp, long maxOffset) { if (maxTimestamp != RecordBatch.NO_TIMESTAMP && shallowOffsetOfMaxTimestamp < 0) throw new IllegalArgumentException("shallowOffset undefined for maximum timestamp " + maxTimestamp); if (maxOffset < 0) throw new IllegalArgumentException("maxOffset undefined"); } public ByteBuffer outputBuffer() { return outputBuffer; } public int messagesRead() { return messagesRead; } public int bytesRead() { return bytesRead; } public int messagesRetained() { return messagesRetained; } public int bytesRetained() { return bytesRetained; } public long maxOffset() { return maxOffset; } public long maxTimestamp() { return maxTimestamp; } public long shallowOffsetOfMaxTimestamp() { return shallowOffsetOfMaxTimestamp; } } public static MemoryRecords readableRecords(ByteBuffer buffer) { return new MemoryRecords(buffer); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, Compression compression, TimestampType timestampType, long baseOffset) { return builder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, compression, timestampType, baseOffset); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, Compression compression, TimestampType timestampType, long baseOffset, int maxSize) { long logAppendTime = RecordBatch.NO_TIMESTAMP; if (timestampType == TimestampType.LOG_APPEND_TIME) logAppendTime = System.currentTimeMillis(); return new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, compression, timestampType, baseOffset, logAppendTime, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, false, false, RecordBatch.NO_PARTITION_LEADER_EPOCH, maxSize); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, byte magic, Compression compression, TimestampType timestampType, long baseOffset, long logAppendTime) { return builder(buffer, magic, compression, timestampType, baseOffset, logAppendTime, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, false, RecordBatch.NO_PARTITION_LEADER_EPOCH); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, byte magic, Compression compression, TimestampType timestampType, long baseOffset) { long logAppendTime = RecordBatch.NO_TIMESTAMP; if (timestampType == TimestampType.LOG_APPEND_TIME) logAppendTime = System.currentTimeMillis(); return builder(buffer, magic, compression, timestampType, baseOffset, logAppendTime, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, false, RecordBatch.NO_PARTITION_LEADER_EPOCH); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, byte magic, Compression compression, TimestampType timestampType, long baseOffset, long logAppendTime, int partitionLeaderEpoch) { return builder(buffer, magic, compression, timestampType, baseOffset, logAppendTime, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, false, partitionLeaderEpoch); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, Compression compression, long baseOffset, long producerId, short producerEpoch, int baseSequence, boolean isTransactional) { return builder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, compression, TimestampType.CREATE_TIME, baseOffset, RecordBatch.NO_TIMESTAMP, producerId, producerEpoch, baseSequence, isTransactional, RecordBatch.NO_PARTITION_LEADER_EPOCH); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, byte magic, Compression compression, TimestampType timestampType, long baseOffset, long logAppendTime, long producerId, short producerEpoch, int baseSequence) { return builder(buffer, magic, compression, timestampType, baseOffset, logAppendTime, producerId, producerEpoch, baseSequence, false, RecordBatch.NO_PARTITION_LEADER_EPOCH); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, byte magic, Compression compression, TimestampType timestampType, long baseOffset, long logAppendTime, long producerId, short producerEpoch, int baseSequence, boolean isTransactional, int partitionLeaderEpoch) { return builder(buffer, magic, compression, timestampType, baseOffset, logAppendTime, producerId, producerEpoch, baseSequence, isTransactional, false, partitionLeaderEpoch); } public static MemoryRecordsBuilder builder(ByteBuffer buffer, byte magic, Compression compression, TimestampType timestampType, long baseOffset, long logAppendTime, long producerId, short producerEpoch, int baseSequence, boolean isTransactional, boolean isControlBatch, int partitionLeaderEpoch) { return new MemoryRecordsBuilder(buffer, magic, compression, timestampType, baseOffset, logAppendTime, producerId, producerEpoch, baseSequence, isTransactional, isControlBatch, partitionLeaderEpoch, buffer.remaining()); } public static MemoryRecords withRecords(Compression compression, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, compression, records); } public static MemoryRecords withRecords(Compression compression, int partitionLeaderEpoch, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, 0L, compression, TimestampType.CREATE_TIME, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, partitionLeaderEpoch, false, records); } public static MemoryRecords withRecords(byte magic, Compression compression, SimpleRecord... records) { return withRecords(magic, 0L, compression, TimestampType.CREATE_TIME, records); } public static MemoryRecords withRecords(long initialOffset, Compression compression, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, initialOffset, compression, TimestampType.CREATE_TIME, records); } public static MemoryRecords withRecords(byte magic, long initialOffset, Compression compression, SimpleRecord... records) { return withRecords(magic, initialOffset, compression, TimestampType.CREATE_TIME, records); } public static MemoryRecords withRecords(long initialOffset, Compression compression, int partitionLeaderEpoch, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, initialOffset, compression, TimestampType.CREATE_TIME, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, partitionLeaderEpoch, false, records); } public static MemoryRecords withIdempotentRecords(Compression compression, long producerId, short producerEpoch, int baseSequence, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, 0L, compression, TimestampType.CREATE_TIME, producerId, producerEpoch, baseSequence, RecordBatch.NO_PARTITION_LEADER_EPOCH, false, records); } public static MemoryRecords withIdempotentRecords(byte magic, long initialOffset, Compression compression, long producerId, short producerEpoch, int baseSequence, int partitionLeaderEpoch, SimpleRecord... records) { return withRecords(magic, initialOffset, compression, TimestampType.CREATE_TIME, producerId, producerEpoch, baseSequence, partitionLeaderEpoch, false, records); } public static MemoryRecords withIdempotentRecords(long initialOffset, Compression compression, long producerId, short producerEpoch, int baseSequence, int partitionLeaderEpoch, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, initialOffset, compression, TimestampType.CREATE_TIME, producerId, producerEpoch, baseSequence, partitionLeaderEpoch, false, records); } public static MemoryRecords withTransactionalRecords(Compression compression, long producerId, short producerEpoch, int baseSequence, SimpleRecord... records) { return withRecords(RecordBatch.CURRENT_MAGIC_VALUE, 0L, compression, TimestampType.CREATE_TIME, producerId, producerEpoch, baseSequence, RecordBatch.NO_PARTITION_LEADER_EPOCH, true, records); } public static MemoryRecords withTransactionalRecords(byte magic, long initialOffset, Compression compression, long producerId, short producerEpoch, int baseSequence, int partitionLeaderEpoch, SimpleRecord... records) { return withRecords(magic, initialOffset, compression, TimestampType.CREATE_TIME, producerId, producerEpoch, baseSequence, partitionLeaderEpoch, true, records); } public static MemoryRecords withTransactionalRecords(long initialOffset, Compression compression, long producerId, short producerEpoch, int baseSequence, int partitionLeaderEpoch, SimpleRecord... records) { return withTransactionalRecords(RecordBatch.CURRENT_MAGIC_VALUE, initialOffset, compression, producerId, producerEpoch, baseSequence, partitionLeaderEpoch, records); } public static MemoryRecords withRecords(byte magic, long initialOffset, Compression compression, TimestampType timestampType, SimpleRecord... records) { return withRecords(magic, initialOffset, compression, timestampType, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, RecordBatch.NO_PARTITION_LEADER_EPOCH, false, records); } public static MemoryRecords withRecords(byte magic, long initialOffset, Compression compression, TimestampType timestampType, long producerId, short producerEpoch, int baseSequence, int partitionLeaderEpoch, boolean isTransactional, SimpleRecord... records) { if (records.length == 0) return MemoryRecords.EMPTY; int sizeEstimate = AbstractRecords.estimateSizeInBytes(magic, compression.type(), Arrays.asList(records)); ByteBufferOutputStream bufferStream = new ByteBufferOutputStream(sizeEstimate); long logAppendTime = RecordBatch.NO_TIMESTAMP; if (timestampType == TimestampType.LOG_APPEND_TIME) logAppendTime = System.currentTimeMillis(); try (final MemoryRecordsBuilder builder = new MemoryRecordsBuilder(bufferStream, magic, compression, timestampType, initialOffset, logAppendTime, producerId, producerEpoch, baseSequence, isTransactional, false, partitionLeaderEpoch, sizeEstimate)) { for (SimpleRecord record : records) builder.append(record); return builder.build(); } } public static MemoryRecords withEndTransactionMarker(long producerId, short producerEpoch, EndTransactionMarker marker) { return withEndTransactionMarker(0L, System.currentTimeMillis(), RecordBatch.NO_PARTITION_LEADER_EPOCH, producerId, producerEpoch, marker); } public static MemoryRecords withEndTransactionMarker(long timestamp, long producerId, short producerEpoch, EndTransactionMarker marker) { return withEndTransactionMarker(0L, timestamp, RecordBatch.NO_PARTITION_LEADER_EPOCH, producerId, producerEpoch, marker); } public static MemoryRecords withEndTransactionMarker(long initialOffset, long timestamp, int partitionLeaderEpoch, long producerId, short producerEpoch, EndTransactionMarker marker) { int endTxnMarkerBatchSize = DefaultRecordBatch.RECORD_BATCH_OVERHEAD + marker.endTxnMarkerValueSize(); ByteBuffer buffer = ByteBuffer.allocate(endTxnMarkerBatchSize); writeEndTransactionalMarker(buffer, initialOffset, timestamp, partitionLeaderEpoch, producerId, producerEpoch, marker); buffer.flip(); return MemoryRecords.readableRecords(buffer); } public static void writeEndTransactionalMarker(ByteBuffer buffer, long initialOffset, long timestamp, int partitionLeaderEpoch, long producerId, short producerEpoch, EndTransactionMarker marker) { boolean isTransactional = true; try (MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, Compression.NONE, TimestampType.CREATE_TIME, initialOffset, timestamp, producerId, producerEpoch, RecordBatch.NO_SEQUENCE, isTransactional, true, partitionLeaderEpoch, buffer.capacity()) ) { builder.appendEndTxnMarker(timestamp, marker); } } public static MemoryRecords withLeaderChangeMessage( long initialOffset, long timestamp, int leaderEpoch, ByteBuffer buffer, LeaderChangeMessage leaderChangeMessage ) { try (MemoryRecordsBuilder builder = createKraftControlRecordBuilder( initialOffset, timestamp, leaderEpoch, buffer ) ) { builder.appendLeaderChangeMessage(timestamp, leaderChangeMessage); return builder.build(); } } public static MemoryRecords withSnapshotHeaderRecord( long initialOffset, long timestamp, int leaderEpoch, ByteBuffer buffer, SnapshotHeaderRecord snapshotHeaderRecord ) { try (MemoryRecordsBuilder builder = createKraftControlRecordBuilder( initialOffset, timestamp, leaderEpoch, buffer ) ) { builder.appendSnapshotHeaderMessage(timestamp, snapshotHeaderRecord); return builder.build(); } } public static MemoryRecords withSnapshotFooterRecord( long initialOffset, long timestamp, int leaderEpoch, ByteBuffer buffer, SnapshotFooterRecord snapshotFooterRecord ) { try (MemoryRecordsBuilder builder = createKraftControlRecordBuilder( initialOffset, timestamp, leaderEpoch, buffer ) ) { builder.appendSnapshotFooterMessage(timestamp, snapshotFooterRecord); return builder.build(); } } public static MemoryRecords withKRaftVersionRecord( long initialOffset, long timestamp, int leaderEpoch, ByteBuffer buffer, KRaftVersionRecord kraftVersionRecord ) { try (MemoryRecordsBuilder builder = createKraftControlRecordBuilder( initialOffset, timestamp, leaderEpoch, buffer ) ) { builder.appendKRaftVersionMessage(timestamp, kraftVersionRecord); return builder.build(); } } public static MemoryRecords withVotersRecord( long initialOffset, long timestamp, int leaderEpoch, ByteBuffer buffer, VotersRecord votersRecord ) { try (MemoryRecordsBuilder builder = createKraftControlRecordBuilder( initialOffset, timestamp, leaderEpoch, buffer ) ) { builder.appendVotersMessage(timestamp, votersRecord); return builder.build(); } } private static MemoryRecordsBuilder createKraftControlRecordBuilder( long initialOffset, long timestamp, int leaderEpoch, ByteBuffer buffer ) { return new MemoryRecordsBuilder( buffer, RecordBatch.CURRENT_MAGIC_VALUE, Compression.NONE, TimestampType.CREATE_TIME, initialOffset, timestamp, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH, RecordBatch.NO_SEQUENCE, false, true, leaderEpoch, buffer.capacity() ); } }
FilterResult
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBean.java
{ "start": 6127, "end": 6565 }
class ____ extends AbstractLazyCreationTargetSource { @Override protected Object createObject() throws Exception { Assert.state(serviceUrl != null, "No JMXServiceURL set"); return JMXConnectorFactory.connect(serviceUrl, environment); } @Override public Class<?> getTargetClass() { return JMXConnector.class; } } /** * Lazily creates an {@code MBeanServerConnection}. */ private
JMXConnectorLazyInitTargetSource
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/expression/UnresolvedAttribute.java
{ "start": 1659, "end": 4992 }
class ____ extends Attribute implements Unresolvable { private final boolean customMessage; protected final String unresolvedMsg; // TODO: Check usage of constructors without qualifiers, that's likely where qualifiers need to be plugged into resolution logic. public UnresolvedAttribute(Source source, String name) { this(source, name, null); } public UnresolvedAttribute(Source source, String name, @Nullable String unresolvedMessage) { this(source, null, name, unresolvedMessage); } public UnresolvedAttribute(Source source, @Nullable String qualifier, String name, @Nullable String unresolvedMessage) { this(source, qualifier, name, null, unresolvedMessage); } public UnresolvedAttribute(Source source, String name, @Nullable NameId id, @Nullable String unresolvedMessage) { this(source, null, name, id, unresolvedMessage); } @SuppressWarnings("this-escape") public UnresolvedAttribute( Source source, @Nullable String qualifier, String name, @Nullable NameId id, @Nullable String unresolvedMessage ) { super(source, qualifier, name, id); this.customMessage = unresolvedMessage != null; this.unresolvedMsg = unresolvedMessage != null ? unresolvedMessage : defaultUnresolvedMessage(null); } @Override public void writeTo(StreamOutput out) throws IOException { throw new UnsupportedOperationException("doesn't escape the node"); } @Override public String getWriteableName() { throw new UnsupportedOperationException("doesn't escape the node"); } @Override protected NodeInfo<? extends UnresolvedAttribute> info() { return NodeInfo.create(this, UnresolvedAttribute::new, qualifier(), name(), id(), unresolvedMsg); } public boolean customMessage() { return customMessage; } @Override public boolean resolved() { return false; } @Override protected Attribute clone( Source source, String qualifier, String name, DataType dataType, Nullability nullability, NameId id, boolean synthetic ) { // TODO: This looks like a bug; making clones should allow for changes. return this; } // Cannot just use the super method because that requires a data type. @Override public UnresolvedAttribute withId(NameId id) { return new UnresolvedAttribute(source(), qualifier(), name(), id, unresolvedMessage()); } public UnresolvedAttribute withUnresolvedMessage(String unresolvedMessage) { return new UnresolvedAttribute(source(), qualifier(), name(), id(), unresolvedMessage); } @Override protected TypeResolution resolveType() { return new TypeResolution("unresolved attribute [" + name() + "]"); } @Override public DataType dataType() { throw new UnresolvedException("dataType", this); } @Override public String toString() { return UNRESOLVED_PREFIX + qualifiedName(); } @Override protected String label() { return UNRESOLVED_PREFIX; } @Override public boolean isDimension() { // We don't want to use this during the analysis phase, and this
UnresolvedAttribute
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/GroupList.java
{ "start": 956, "end": 1240 }
class ____ extends RemotingSerializable { private HashSet<String> groupList = new HashSet<>(); public HashSet<String> getGroupList() { return groupList; } public void setGroupList(HashSet<String> groupList) { this.groupList = groupList; } }
GroupList
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/internal/Lists.java
{ "start": 5583, "end": 14323 }
interface ____ must be mutually comparable (that is, e1.compareTo(e2) * must not throw a ClassCastException for any elements e1 and e2 in the list), examples : * <ul> * <li>a list composed of {"a1", "a2", "a3"} is ok because the element type (String) is Comparable</li> * <li>a list composed of Rectangle {r1, r2, r3} is <b>NOT ok</b> because Rectangle is not Comparable</li> * <li>a list composed of {True, "abc", False} is <b>NOT ok</b> because elements are not mutually comparable</li> * </ul> * Empty lists are considered sorted.<br> Unique element lists are considered sorted unless the element type is not Comparable. * * @param info contains information about the assertion. * @param actual the given {@code List}. * * @throws AssertionError if the actual list is not sorted in ascending order according to the natural ordering of its * elements. * @throws AssertionError if the actual list is <code>null</code>. * @throws AssertionError if the actual list element type does not implement {@link Comparable}. * @throws AssertionError if the actual list elements are not mutually {@link Comparable}. */ public void assertIsSorted(AssertionInfo info, List<?> actual) { assertNotNull(info, actual); if (comparisonStrategy instanceof ComparatorBasedComparisonStrategy strategy) { // instead of comparing elements with their natural comparator, use the one set by client. Comparator<?> comparator = strategy.getComparator(); assertIsSortedAccordingToComparator(info, actual, comparator); return; } try { // sorted assertion is only relevant if elements are Comparable, we assume they are List<Comparable<Object>> comparableList = listOfComparableElements(actual); // array with 0 or 1 element are considered sorted. if (comparableList.size() <= 1) return; for (int i = 0; i < comparableList.size() - 1; i++) { // array is sorted in ascending order iif element i is less or equal than element i+1 if (comparableList.get(i).compareTo(comparableList.get(i + 1)) > 0) throw failures.failure(info, shouldBeSorted(i, actual)); } } catch (ClassCastException e) { // elements are either not Comparable or not mutually Comparable (e.g. List<Object> containing String and Integer) throw failures.failure(info, shouldHaveMutuallyComparableElements(actual)); } } /** * Verifies that the actual list is sorted according to the given comparator.<br> Empty lists are considered sorted whatever * the comparator is.<br> One element lists are considered sorted if the element is compatible with comparator. * * @param info contains information about the assertion. * @param actual the given {@code List}. * @param comparator the {@link Comparator} used to compare list elements * * @throws AssertionError if the actual list is not sorted according to the given comparator. * @throws AssertionError if the actual list is <code>null</code>. * @throws NullPointerException if the given comparator is <code>null</code>. * @throws AssertionError if the actual list elements are not mutually comparable according to given Comparator. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void assertIsSortedAccordingToComparator(AssertionInfo info, List<?> actual, Comparator<?> comparator) { assertNotNull(info, actual); requireNonNull(comparator, "The given comparator should not be null"); try { // Empty collections are considered sorted even if comparator can't be applied to their element type // We can't verify that point because of erasure type at runtime. if (actual.isEmpty()) return; Comparator rawComparator = comparator; if (actual.size() == 1) { // Compare unique element with itself to verify that it is compatible with comparator (a ClassCastException is // thrown if not). We have to use a raw comparator to compare the unique element of actual ... :( rawComparator.compare(actual.get(0), actual.get(0)); return; } for (int i = 0; i < actual.size() - 1; i++) { // List is sorted in comparator defined order if current element is less or equal than next element if (rawComparator.compare(actual.get(i), actual.get(i + 1)) > 0) throw failures.failure(info, shouldBeSortedAccordingToGivenComparator(i, actual, comparator)); } } catch (ClassCastException e) { throw failures.failure(info, shouldHaveComparableElementsAccordingToGivenComparator(actual, comparator)); } } /** * Verifies that the given {@code List} satisfies the given <code>{@link Condition}</code> at the given index. * @param <T> the type of the actual value and the type of values that given {@code Condition} takes. * @param info contains information about the assertion. * @param actual the given {@code List}. * @param condition the given {@code Condition}. * @param index the index where the object should be stored in the given {@code List}. * @throws AssertionError if the given {@code List} is {@code null} or empty. * @throws NullPointerException if the given {@code Index} is {@code null}. * @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of the given * {@code List}. * @throws NullPointerException if the given {@code Condition} is {@code null}. * @throws AssertionError if the value in the given {@code List} at the given index does not satisfy the given {@code Condition} * . */ public <T> void assertHas(AssertionInfo info, List<? extends T> actual, Condition<? super T> condition, Index index) { if (conditionIsMetAtIndex(info, actual, condition, index)) return; throw failures.failure(info, shouldHaveAtIndex(actual, condition, index, actual.get(index.value))); } /** * Verifies that the given {@code List} satisfies the given <code>{@link Condition}</code> at the given index. * @param <T> the type of the actual value and the type of values that given {@code Condition} takes. * @param info contains information about the assertion. * @param actual the given {@code List}. * @param condition the given {@code Condition}. * @param index the index where the object should be stored in the given {@code List}. * @throws AssertionError if the given {@code List} is {@code null} or empty. * @throws NullPointerException if the given {@code Index} is {@code null}. * @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of the given * {@code List}. * @throws NullPointerException if the given {@code Condition} is {@code null}. * @throws AssertionError if the value in the given {@code List} at the given index does not satisfy the given {@code Condition} * . */ public <T> void assertIs(AssertionInfo info, List<? extends T> actual, Condition<? super T> condition, Index index) { if (conditionIsMetAtIndex(info, actual, condition, index)) return; throw failures.failure(info, shouldBeAtIndex(actual, condition, index, actual.get(index.value))); } public <T> void satisfies(AssertionInfo info, List<? extends T> actual, Consumer<? super T> requirements, Index index) { assertNotNull(info, actual); requireNonNull(requirements, "The Consumer expressing the assertions requirements must not be null"); checkIndexValueIsValid(index, actual.size() - 1); requirements.accept(actual.get(index.value)); } private <T> boolean conditionIsMetAtIndex(AssertionInfo info, List<T> actual, Condition<? super T> condition, Index index) { assertNotNull(info, actual); assertNotNull(condition); Iterables.instance().assertNotEmpty(info, actual); checkIndexValueIsValid(index, actual.size() - 1); return condition.matches(actual.get(index.value)); } @SuppressWarnings("unchecked") private static List<Comparable<Object>> listOfComparableElements(List<?> collection) { return collection.stream().map(object -> (Comparable<Object>) object).collect(toList()); } private void assertNotNull(AssertionInfo info, List<?> actual) { Objects.instance().assertNotNull(info, actual); } private void assertNotNull(Condition<?> condition) { Conditions.instance().assertIsNotNull(condition); } private boolean areEqual(Object actual, Object other) { return comparisonStrategy.areEqual(actual, other); } // TODO reduce the visibility of the fields annotated with @VisibleForTesting public ComparisonStrategy getComparisonStrategy() { return comparisonStrategy; } }
and
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/SingleTableNativeQueryTest.java
{ "start": 8008, "end": 8996 }
class ____ extends Person { private Color color; @Column(name = "fav_hobby") private String favoriteThing; @OneToOne private Woman wife; @OneToMany(mappedBy = "father") private List<Child> children = new ArrayList<>(); public Man() { } public Man(String name, String favoriteThing) { super( name ); this.favoriteThing = favoriteThing; } public String getFavoriteThing() { return favoriteThing; } public void setFavoriteThing(String favoriteThing) { this.favoriteThing = favoriteThing; } public Woman getWife() { return wife; } public void setWife(Woman wife) { this.wife = wife; } public List<Child> getChildren() { return children; } public void setChildren(List<Child> children) { this.children = children; } public Color getColor() { return color; } public void setColor(final Color color) { this.color = color; } } @Entity(name = "Woman") @DiscriminatorValue("WOMAN") public static
Man
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/Gh29105Tests.java
{ "start": 915, "end": 1748 }
class ____ { @Test void beanProviderWithParentContextReuseOrder() { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(DefaultConfiguration.class, CustomConfiguration.class); AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext(); child.setParent(parent); child.register(DefaultConfiguration.class); child.refresh(); Stream<Class<?>> orderedTypes = child.getBeanProvider(MyService.class).orderedStream().map(Object::getClass); assertThat(orderedTypes).containsExactly(CustomService.class, DefaultService.class); assertThat(child.getDefaultListableBeanFactory().getOrder("defaultService")).isEqualTo(0); assertThat(child.getDefaultListableBeanFactory().getOrder("customService")).isEqualTo(-1); child.close(); parent.close(); }
Gh29105Tests
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxDefer.java
{ "start": 1090, "end": 1921 }
class ____<T> extends Flux<T> implements SourceProducer<T> { final Supplier<? extends Publisher<? extends T>> supplier; FluxDefer(Supplier<? extends Publisher<? extends T>> supplier) { this.supplier = Objects.requireNonNull(supplier, "supplier"); } @Override @SuppressWarnings("unchecked") public void subscribe(CoreSubscriber<? super T> actual) { Publisher<? extends T> p; try { p = Objects.requireNonNull(supplier.get(), "The Publisher returned by the supplier is null"); } catch (Throwable e) { Operators.error(actual, Operators.onOperatorError(e, actual.currentContext())); return; } from(p).subscribe(actual); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return SourceProducer.super.scanUnsafe(key); } }
FluxDefer
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/MapTypeInfo.java
{ "start": 1529, "end": 2318 }
class ____<K, V> extends TypeInformation<Map<K, V>> { /* The type information for the keys in the map*/ private final TypeInformation<K> keyTypeInfo; /* The type information for the values in the map */ private final TypeInformation<V> valueTypeInfo; public MapTypeInfo(TypeInformation<K> keyTypeInfo, TypeInformation<V> valueTypeInfo) { this.keyTypeInfo = Preconditions.checkNotNull(keyTypeInfo, "The key type information cannot be null."); this.valueTypeInfo = Preconditions.checkNotNull( valueTypeInfo, "The value type information cannot be null."); } public MapTypeInfo(Class<K> keyClass, Class<V> valueClass) { this.keyTypeInfo = of(checkNotNull(keyClass, "The key
MapTypeInfo
java
spring-projects__spring-boot
module/spring-boot-data-jdbc-test/src/test/java/org/springframework/boot/data/jdbc/test/autoconfigure/DataJdbcTypeExcludeFilterTests.java
{ "start": 2241, "end": 2312 }
class ____ extends AbstractJdbcConfiguration { } }
TestJdbcConfiguration
java
apache__spark
sql/api/src/main/java/org/apache/spark/sql/api/java/UDF22.java
{ "start": 981, "end": 1333 }
interface ____<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, R> extends Serializable { R call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15, T16 t16, T17 t17, T18 t18, T19 t19, T20 t20, T21 t21, T22 t22) throws Exception; }
UDF22
java
apache__camel
core/camel-core-languages/src/main/java/org/apache/camel/language/csimple/CSimpleCompiler.java
{ "start": 955, "end": 1980 }
interface ____ { /** * Service factory key. */ String FACTORY = "csimple-compiler"; /** * Adds an import line * * @param imports import such as com.foo.MyClass */ void addImport(String imports); /** * Adds an alias * * @param key the key * @param value the value */ void addAliases(String key, String value); /** * Create an expression from the given csimple script * * @param camelContext the camel context * @param script the csimple script * @return the compiled expression */ CSimpleExpression compileExpression(CamelContext camelContext, String script); /** * Create an expression from the given csimple script * * @param camelContext the camel context * @param script the csimple script * @return the compiled preidcate */ CSimpleExpression compilePredicate(CamelContext camelContext, String script); }
CSimpleCompiler
java
resilience4j__resilience4j
resilience4j-micrometer/src/test/java/io/github/resilience4j/micrometer/tagged/TaggedTimeLimiterMetricsPublisherTest.java
{ "start": 1521, "end": 8295 }
class ____ { private MeterRegistry meterRegistry; private TimeLimiter timeLimiter; private TimeLimiterRegistry timeLimiterRegistry; private TaggedTimeLimiterMetricsPublisher taggedTimeLimiterMetricsPublisher; @Before public void setUp() { meterRegistry = new SimpleMeterRegistry(); taggedTimeLimiterMetricsPublisher = new TaggedTimeLimiterMetricsPublisher(meterRegistry); timeLimiterRegistry = TimeLimiterRegistry .of(TimeLimiterConfig.ofDefaults(), taggedTimeLimiterMetricsPublisher); timeLimiter = timeLimiterRegistry.timeLimiter("backendA"); } @Test public void shouldAddMetricsForANewlyCreatedTimeLimiter() { TimeLimiter newTimeLimiter = timeLimiterRegistry.timeLimiter("backendB"); newTimeLimiter.onSuccess(); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap) .containsKeys("backendA", "backendB"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendA")).hasSize(3); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendB")).hasSize(3); assertThat(meterRegistry.getMeters()).hasSize(6); Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); Optional<Counter> successful = findMeterByKindAndNameTags(counters, "successful", newTimeLimiter.getName()); assertThat(successful).map(Counter::count).contains(1d); } @Test public void shouldAddCustomTags() { TimeLimiter timeLimiterF = timeLimiterRegistry.timeLimiter("backendF", Map.of("key1", "value1")); timeLimiterF.onSuccess(); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).containsKeys("backendA", "backendF"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendF")).hasSize(3); assertThat(meterRegistry.getMeters()).hasSize(6); RequiredSearch match = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).tags("key1", "value1"); assertThat(match).isNotNull(); } @Test public void shouldRemovedMetricsForRemovedRetry() { assertThat(meterRegistry.getMeters()).hasSize(3); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).containsKeys("backendA"); timeLimiterRegistry.remove("backendA"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).isEmpty(); assertThat(meterRegistry.getMeters()).isEmpty(); } @Test public void shouldReplaceMetrics() { Counter before = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counter(); assertThat(before).isNotNull(); assertThat(before.count()).isZero(); assertThat(before.getId().getTag(TagNames.NAME)).isEqualTo(timeLimiter.getName()); timeLimiterRegistry.replace(timeLimiter.getName(), TimeLimiter.ofDefaults()); Counter after = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counter(); assertThat(after).isNotNull(); assertThat(after.count()).isZero(); assertThat(after.getId().getTag(TagNames.NAME)) .isEqualTo(TimeLimiter.ofDefaults().getName()); } @Test public void successfulCounterIsRegistered() { Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); timeLimiter.onSuccess(); Optional<Counter> successful = findMeterByKindAndNameTags(counters, "successful", timeLimiter.getName()); assertThat(successful).map(Counter::count).contains(1d); } @Test public void failedCounterIsRegistered() { Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); timeLimiter.onError(new RuntimeException()); Optional<Counter> failed = findMeterByKindAndNameTags(counters, "failed", timeLimiter.getName()); assertThat(failed).map(Counter::count).contains(1d); } @Test public void timoutCounterIsRegistered() { Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); timeLimiter.onError(new TimeoutException()); Optional<Counter> timeout = findMeterByKindAndNameTags(counters, "timeout", timeLimiter.getName()); assertThat(timeout).map(Counter::count).contains(1d); } @Test public void customMetricNamesGetApplied() { MeterRegistry meterRegistry = new SimpleMeterRegistry(); TaggedTimeLimiterMetricsPublisher taggedTimeLimiterMetricsPublisher = new TaggedTimeLimiterMetricsPublisher( TimeLimiterMetricNames.custom() .callsMetricName("custom_calls") .build(), meterRegistry); TimeLimiterRegistry timeLimiterRegistry = TimeLimiterRegistry .of(TimeLimiterConfig.ofDefaults(), taggedTimeLimiterMetricsPublisher); timeLimiterRegistry.timeLimiter("backendA"); Set<String> metricNames = meterRegistry.getMeters() .stream() .map(Meter::getId) .map(Meter.Id::getName) .collect(Collectors.toSet()); assertThat(metricNames).hasSameElementsAs(Arrays.asList( "custom_calls" )); } @Test public void testReplaceNewMeter(){ TimeLimiter oldOne = TimeLimiter.of("backendC", TimeLimiterConfig.ofDefaults()); // add meters of old taggedTimeLimiterMetricsPublisher.addMetrics(meterRegistry, oldOne); // one success call oldOne.onSuccess(); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).containsKeys("backendC"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendC")).hasSize(3); Collection<Counter> counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); Optional<Counter> successful = findMeterByKindAndNameTags(counters, "successful", oldOne.getName()); assertThat(successful).map(Counter::count).contains(1d); TimeLimiter newOne = TimeLimiter.of("backendC", TimeLimiterConfig.ofDefaults()); // add meters of new taggedTimeLimiterMetricsPublisher.addMetrics(meterRegistry, newOne); // three success call newOne.onSuccess(); newOne.onSuccess(); newOne.onSuccess(); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap).containsKeys("backendC"); assertThat(taggedTimeLimiterMetricsPublisher.meterIdMap.get("backendC")).hasSize(3); counters = meterRegistry.get(DEFAULT_TIME_LIMITER_CALLS).counters(); successful = findMeterByKindAndNameTags(counters, "successful", newOne.getName()); assertThat(successful).map(Counter::count).contains(3d); } }
TaggedTimeLimiterMetricsPublisherTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/TimelineWriter.java
{ "start": 1717, "end": 4539 }
interface ____ extends Service { /** * Stores the entire information in {@link TimelineEntities} to the timeline * store. Any errors occurring for individual write request objects will be * reported in the response. * * @param context a {@link TimelineCollectorContext} * @param data a {@link TimelineEntities} object. * @param callerUgi {@link UserGroupInformation}. * @return a {@link TimelineWriteResponse} object. * @throws IOException if there is any exception encountered while storing or * writing entities to the back end storage. */ TimelineWriteResponse write(TimelineCollectorContext context, TimelineEntities data, UserGroupInformation callerUgi) throws IOException; /** * Stores {@link TimelineDomain} object to the timeline * store. Any errors occurring for individual write request objects will be * reported in the response. * * @param context a {@link TimelineCollectorContext} * @param domain a {@link TimelineDomain} object. * @return a {@link TimelineWriteResponse} object. * @throws IOException if there is any exception encountered while storing or * writing entities to the back end storage. */ TimelineWriteResponse write(TimelineCollectorContext context, TimelineDomain domain) throws IOException; /** * Aggregates the entity information to the timeline store based on which * track this entity is to be rolled up to The tracks along which aggregations * are to be done are given by {@link TimelineAggregationTrack} * * Any errors occurring for individual write request objects will be reported * in the response. * * @param data * a {@link TimelineEntity} object * a {@link TimelineAggregationTrack} enum * value. * @param track Specifies the track or dimension along which aggregation would * occur. Includes USER, FLOW, QUEUE, etc. * @return a {@link TimelineWriteResponse} object. * @throws IOException if there is any exception encountered while aggregating * entities to the backend storage. */ TimelineWriteResponse aggregate(TimelineEntity data, TimelineAggregationTrack track) throws IOException; /** * Flushes the data to the backend storage. Whatever may be buffered will be * written to the storage when the method returns. This may be a potentially * time-consuming operation, and should be used judiciously. * * @throws IOException if there is any exception encountered while flushing * entities to the backend storage. */ void flush() throws IOException; /** * Check if writer connection is working properly. * * @return True if writer connection works as expected, false otherwise. */ TimelineHealth getHealthStatus(); }
TimelineWriter
java
apache__dubbo
dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/event/MetadataSubDispatcher.java
{ "start": 1649, "end": 2367 }
class ____ extends SimpleMetricsEventMulticaster { public MetadataSubDispatcher(MetadataMetricsCollector collector) { CategorySet.ALL.forEach(categorySet -> { super.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { super.addListener(categorySet.getError().getEventFunc().apply(collector)); } }); } /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */
MetadataSubDispatcher
java
apache__maven
impl/maven-core/src/test/java/org/apache/maven/internal/impl/PropertiesAsMapTest.java
{ "start": 1383, "end": 2418 }
class ____ { @Test void testPropertiesAsMap() { Properties props = new Properties(); props.setProperty("foo1", "bar1"); props.setProperty("foo2", "bar2"); PropertiesAsMap pam = new PropertiesAsMap(props); assertEquals(2, pam.size()); Set<Entry<String, String>> set = pam.entrySet(); assertNotNull(set); assertEquals(2, set.size()); Iterator<Entry<String, String>> iterator = set.iterator(); assertNotNull(iterator); assertTrue(iterator.hasNext(), "Expected " + iterator + ".hasNext() to return true"); assertTrue(iterator.hasNext(), "Expected " + iterator + ".hasNext() to return true"); Entry<String, String> entry = iterator.next(); assertNotNull(entry); entry = iterator.next(); assertNotNull(entry); assertThrows(NoSuchElementException.class, () -> iterator.next()); assertFalse(iterator.hasNext(), "Expected " + iterator + ".hasNext() to return false"); } }
PropertiesAsMapTest
java
quarkusio__quarkus
integration-tests/hibernate-orm-jpamodelgen/src/test/java/io/quarkus/it/hibernate/jpamodelgen/PanacheJpaModelGenTest.java
{ "start": 234, "end": 2247 }
class ____ { private static final String ROOT = "/panache/static-metamodel"; @Test public void staticMetamodel() { // Create/retrieve given() .pathParam("name", "foo") .contentType(ContentType.JSON) .when().get(ROOT + "/by/name/{name}") .then() .statusCode(404); given() .body(new MyStaticMetamodelEntity("foo")) .contentType(ContentType.JSON) .when().post(ROOT) .then() .statusCode(204); given() .pathParam("name", "foo") .contentType(ContentType.JSON) .when().get(ROOT + "/by/name/{name}") .then() .statusCode(200); // Update given() .pathParam("name", "bar") .contentType(ContentType.JSON) .when().get(ROOT + "/by/name/{name}") .then() .statusCode(404); given() .pathParam("before", "foo") .pathParam("after", "bar") .contentType(ContentType.JSON) .when().post(ROOT + "/rename/{before}/to/{after}") .then() .statusCode(204); given() .pathParam("name", "bar") .contentType(ContentType.JSON) .when().get(ROOT + "/by/name/{name}") .then() .statusCode(200); // Delete given() .pathParam("name", "bar") .contentType(ContentType.JSON) .when().delete(ROOT + "/by/name/{name}") .then() .statusCode(204); given() .pathParam("name", "bar") .contentType(ContentType.JSON) .when().get(ROOT + "/by/name/{name}") .then() .statusCode(404); } }
PanacheJpaModelGenTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/spi/ImplicitDiscriminatorStrategy.java
{ "start": 424, "end": 932 }
interface ____ { /** * Determine the discriminator value to use for the given {@code entityMapping}. */ Object toDiscriminatorValue(EntityMappingType entityMapping, NavigableRole discriminatorRole, MappingMetamodelImplementor mappingModel); /** * Determine the entity-mapping which matches the given {@code discriminatorValue}. */ EntityMappingType toEntityMapping(Object discriminatorValue, NavigableRole discriminatorRole, MappingMetamodelImplementor mappingModel); }
ImplicitDiscriminatorStrategy
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client-jaxrs/runtime/src/main/java/io/quarkus/jaxrs/client/reactive/runtime/ParameterGenericTypesSupplier.java
{ "start": 159, "end": 554 }
class ____ implements Supplier<Type[]> { private final Method method; private volatile Type[] value; public ParameterGenericTypesSupplier(Method method) { this.method = method; } @Override public Type[] get() { if (value == null) { value = method.getGenericParameterTypes(); } return value; } }
ParameterGenericTypesSupplier
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/alternatives/priority/AlternativePriorityResolutionTest.java
{ "start": 2141, "end": 2334 }
class ____ { final String msg; MessageBean(String msg) { this.msg = msg; } public String ping() { return msg; } } }
MessageBean
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AddressSelectionTest.java
{ "start": 1473, "end": 2170 }
class ____ { void f() throws Exception { // BUG: Diagnostic contains: InetAddress.getByName("example.com"); // BUG: Diagnostic contains: new Socket("example.com", 80); // BUG: Diagnostic contains: new InetSocketAddress("example.com", 80); } } """) .doTest(); } @Test public void negative() throws Exception { compilationHelper .addSourceLines( "Test.java", """ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket;
Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/SerializeWriterTest_9.java
{ "start": 267, "end": 2119 }
class ____ extends TestCase { public void test_error() throws Exception { SerializeWriter writer = new SerializeWriter(new StringWriter()); Exception error = null; try { writer.writeTo(new StringWriter()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); writer.close(); } public void test_error_2() throws Exception { SerializeWriter writer = new SerializeWriter(new StringWriter()); Exception error = null; try { writer.writeTo(new ByteArrayOutputStream(), Charset.forName("UTF-8")); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); writer.close(); } public void test_error_3() throws Exception { SerializeWriter writer = new SerializeWriter(new StringWriter()); Exception error = null; try { writer.writeTo(new ByteArrayOutputStream(), "UTF-8"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); writer.close(); } public void test_error_4() throws Exception { SerializeWriter writer = new SerializeWriter(new StringWriter()); Exception error = null; try { writer.toCharArray(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); writer.close(); } public void test_error_5() throws Exception { SerializeWriter writer = new SerializeWriter(new StringWriter()); Exception error = null; try { writer.toBytes("UTF-8"); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); writer.close(); } }
SerializeWriterTest_9
java
quarkusio__quarkus
independent-projects/bootstrap/maven-resolver/src/test/java/io/quarkus/bootstrap/resolver/maven/test/ProxyNoMirrorSettingsReposTest.java
{ "start": 423, "end": 1264 }
class ____ extends BootstrapMavenContextTestBase { @Test public void basicPomRepos() throws Exception { final BootstrapMavenContext mvn = bootstrapMavenContextWithSettings("custom-settings/proxy-no-mirror"); final List<RemoteRepository> repos = mvn.getRemoteRepositories(); assertEquals(3, repos.size()); assertEquals("custom-repo", repos.get(0).getId()); assertNotNull(repos.get(0).getProxy()); assertNotNull(repos.get(0).getMirroredRepositories()); final RemoteRepository centralRepo = repos.get(repos.size() - 1); assertEquals("central", centralRepo.getId(), "central repo must be added as default repository"); assertNotNull(centralRepo.getProxy()); assertTrue(centralRepo.getMirroredRepositories().isEmpty()); } }
ProxyNoMirrorSettingsReposTest
java
elastic__elasticsearch
x-pack/plugin/eql/qa/rest/src/javaRestTest/java/org/elasticsearch/xpack/eql/EqlSpecIT.java
{ "start": 654, "end": 1486 }
class ____ extends EqlSpecTestCase { @ClassRule public static final ElasticsearchCluster cluster = EqlTestCluster.CLUSTER; @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } public EqlSpecIT( String query, String name, List<long[]> eventIds, String[] joinKeys, Integer size, Integer maxSamplesPerKey, Boolean allowPartialSearchResults, Boolean allowPartialSequenceResults, Boolean expectShardFailures ) { super( query, name, eventIds, joinKeys, size, maxSamplesPerKey, allowPartialSearchResults, allowPartialSequenceResults, expectShardFailures ); } }
EqlSpecIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/softdelete/timestamp/MappingVerificationTests.java
{ "start": 908, "end": 2137 }
class ____ { @Test @DomainModel(annotatedClasses = Employee.class) @SessionFactory(exportSchema = false) void verifyModel(SessionFactoryScope scope) { final MappingMetamodelImplementor mappingMetamodel = scope.getSessionFactory().getMappingMetamodel(); final EntityPersister entityMapping = mappingMetamodel.getEntityDescriptor( Employee.class ); MappingVerifier.verifyTimestampMapping( entityMapping.getSoftDeleteMapping(), "deleted_at", "employees" ); final PluralAttributeMapping accoladesMapping = (PluralAttributeMapping) entityMapping.findAttributeMapping( "accolades" ); MappingVerifier.verifyTimestampMapping( accoladesMapping.getSoftDeleteMapping(), "deleted_on", "employee_accolades" ); } @Test void testBadEntityMapping() { try { new MetadataSources() .addAnnotatedClass( BadJuju.class ) .buildMetadata(); fail( "Expecting a failure" ); } catch (UnsupportedMappingException expected) { } } @Test void testBadCollectionMapping() { try { new MetadataSources() .addAnnotatedClass( BadAss.class ) .buildMetadata(); fail( "Expecting a failure" ); } catch (UnsupportedMappingException expected) { } } }
MappingVerificationTests
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/common/CorrelateTestPrograms.java
{ "start": 1327, "end": 13818 }
class ____ { static final Row[] BEFORE_DATA = {Row.of(1L, 1, "hi#there"), Row.of(2L, 2, "hello#world")}; static final Row[] AFTER_DATA = { Row.of(4L, 4, "foo#bar"), Row.of(3L, 3, "bar#fiz"), }; static final String[] SOURCE_SCHEMA = {"a BIGINT", "b INT NOT NULL", "c VARCHAR"}; public static final TableTestProgram CORRELATE_CATALOG_FUNC = TableTestProgram.of( "correlate-catalog-func", "validate correlate with temporary catalog function") .setupTemporaryCatalogFunction("func1", TableFunc1.class) .setupTableSource( SourceTestStep.newBuilder("source_t") .addSchema(SOURCE_SCHEMA) .producedBeforeRestore(BEFORE_DATA) .producedAfterRestore(AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("a VARCHAR", "b VARCHAR") .consumedBeforeRestore( "+I[hi#there, $hi]", "+I[hi#there, $there]", "+I[hello#world, $hello]", "+I[hello#world, $world]") .consumedAfterRestore( "+I[foo#bar, $foo]", "+I[foo#bar, $bar]", "+I[bar#fiz, $bar]", "+I[bar#fiz, $fiz]") .build()) .runSql( "INSERT INTO sink_t SELECT c, s FROM source_t, LATERAL TABLE(func1(c, '$')) AS T(s)") .build(); public static final TableTestProgram CORRELATE_SYSTEM_FUNC = TableTestProgram.of( "correlate-system-func", "validate correlate with temporary system function") .setupTemporarySystemFunction("STRING_SPLIT", StringSplit.class) .setupTableSource( SourceTestStep.newBuilder("source_t") .addSchema(SOURCE_SCHEMA) .producedBeforeRestore(BEFORE_DATA) .producedAfterRestore(AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("a VARCHAR", "b VARCHAR") .consumedBeforeRestore( "+I[hi#there, hi]", "+I[hi#there, there]", "+I[hello#world, hello]", "+I[hello#world, world]") .consumedAfterRestore( "+I[foo#bar, foo]", "+I[foo#bar, bar]", "+I[bar#fiz, bar]", "+I[bar#fiz, fiz]") .build()) .runSql( "INSERT INTO sink_t SELECT c, s FROM source_t, LATERAL TABLE(STRING_SPLIT(c, '#')) AS T(s)") .build(); public static final TableTestProgram CORRELATE_JOIN_FILTER = TableTestProgram.of("correlate-join-filter", "validate correlate with join and filter") .setupTemporaryCatalogFunction("func1", TableFunc1.class) .setupTableSource( SourceTestStep.newBuilder("source_t") .addSchema(SOURCE_SCHEMA) .producedBeforeRestore(BEFORE_DATA) .producedAfterRestore(AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("a VARCHAR", "b VARCHAR") .consumedBeforeRestore( "+I[hello#world, hello]", "+I[hello#world, world]") .consumedAfterRestore("+I[bar#fiz, bar]", "+I[bar#fiz, fiz]") .build()) .runSql( "INSERT INTO sink_t SELECT * FROM (SELECT c, s FROM source_t, LATERAL TABLE(func1(c)) AS T(s)) AS T2 WHERE c LIKE '%hello%' OR c LIKE '%fiz%'") .build(); public static final TableTestProgram CORRELATE_LEFT_JOIN = TableTestProgram.of("correlate-left-join", "validate correlate with left join") .setupTemporaryCatalogFunction("func1", TableFunc1.class) .setupTableSource( SourceTestStep.newBuilder("source_t") .addSchema(SOURCE_SCHEMA) .producedBeforeRestore(BEFORE_DATA) .producedAfterRestore(AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("a VARCHAR", "b VARCHAR") .consumedBeforeRestore( "+I[hi#there, hi]", "+I[hi#there, there]", "+I[hello#world, hello]", "+I[hello#world, world]") .consumedAfterRestore( "+I[foo#bar, foo]", "+I[foo#bar, bar]", "+I[bar#fiz, bar]", "+I[bar#fiz, fiz]") .build()) .runSql( "INSERT INTO sink_t SELECT c, s FROM source_t LEFT JOIN LATERAL TABLE(func1(c)) AS T(s) ON TRUE") .build(); public static final TableTestProgram CORRELATE_CROSS_JOIN_UNNEST = TableTestProgram.of( "correlate-cross-join-unnest", "validate correlate with cross join and unnest") .setupTableSource( SourceTestStep.newBuilder("source_t") .addSchema("name STRING", "arr ARRAY<ROW<nested STRING>>") .producedBeforeRestore( Row.of( "Bob", new Row[] { Row.of("1"), Row.of("2"), Row.of("3") })) .producedAfterRestore( Row.of( "Alice", new Row[] { Row.of("4"), Row.of("5"), Row.of("6") })) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("name STRING", "nested STRING") .consumedBeforeRestore("+I[Bob, 1]", "+I[Bob, 2]", "+I[Bob, 3]") .consumedAfterRestore( "+I[Alice, 4]", "+I[Alice, 5]", "+I[Alice, 6]") .build()) .runSql( "INSERT INTO sink_t SELECT name, nested FROM source_t CROSS JOIN UNNEST(arr) AS T(nested)") .build(); public static final TableTestProgram CORRELATE_CROSS_JOIN_UNNEST_2 = TableTestProgram.of( "correlate-cross-join-unnest", "validate correlate with cross join and unnest") .setupTableSource( SourceTestStep.newBuilder("source_t") .addSchema("name STRING", "arr ARRAY<ROW<nested STRING>>") .producedBeforeRestore( Row.of( "Bob", new Row[] { Row.of("1"), Row.of("2"), Row.of("3") })) .producedAfterRestore( Row.of( "Alice", new Row[] { Row.of("4"), Row.of("5"), Row.of("6") })) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("name STRING", "nested STRING") .consumedBeforeRestore("+I[Bob, 1]", "+I[Bob, 2]", "+I[Bob, 3]") .consumedAfterRestore( "+I[Alice, 4]", "+I[Alice, 5]", "+I[Alice, 6]") .build()) .runSql( "INSERT INTO sink_t SELECT (SELECT name, nested FROM source_t, UNNEST(arr) AS T(nested)) FROM source_t") .build(); public static final TableTestProgram CORRELATE_WITH_LITERAL_AGG = TableTestProgram.of( "correlate-with-literal-agg", "validate correlate with literal aggregate function") .setupTableSource( SourceTestStep.newBuilder("source_t1") .addSchema("a INTEGER", "b BIGINT", "c STRING") .producedBeforeRestore(Row.of(1, 2L, "3"), Row.of(2, 3L, "4")) .build()) .setupTableSource( SourceTestStep.newBuilder("source_t2") .addSchema("d INTEGER", "e BIGINT", "f STRING") .producedBeforeRestore(Row.of(1, 2L, "3"), Row.of(2, 3L, "4")) .build()) .setupTableSource( SourceTestStep.newBuilder("source_t3") .addSchema("i INTEGER", "j BIGINT", "k STRING") .producedBeforeRestore(Row.of(1, 2L, "3"), Row.of(2, 3L, "4")) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema("b BIGINT") .consumedBeforeRestore( "+I[2]", "+I[3]", "-D[2]", "-D[3]", "+I[2]", "+I[3]") .build()) .runSql( "INSERT INTO sink_t SELECT b FROM source_t1 " + " WHERE (CASE WHEN a IN (SELECT 1 FROM source_t3) THEN 1 ELSE 2 END) " + " IN (SELECT d FROM source_t2 WHERE source_t1.c = source_t2.f)") .build(); }
CorrelateTestPrograms
java
google__auto
common/src/main/java/com/google/auto/common/Overrides.java
{ "start": 7006, "end": 8037 }
class ____. The only condition we // haven't checked is that C does not inherit mA. Ideally we could just write this: // return !elementUtils.getAllMembers(in).contains(overridden); // But that doesn't work in Eclipse. For example, getAllMembers(AbstractList) // contains List.isEmpty() where you might reasonably expect it to contain // AbstractCollection.isEmpty(). So we need to visit superclasses until we reach // one that declares the same method, and check that we haven't reached mA. We compare // the enclosing elements rather than the methods themselves for the reason described // at the start of the method. ExecutableElement inherited = methodFromSuperclasses(in, overridden); return inherited != null && !overridden.getEnclosingElement().equals(inherited.getEnclosingElement()); } else if (overriddenType.getKind().isInterface()) { // ...overrides from C another method mI declared in
A
java
quarkusio__quarkus
extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/MissingConfigIdentityExpressionTest.java
{ "start": 639, "end": 764 }
class ____ { @Scheduled(every = "1s", identity = "{my.identity}") void wrong() { } } }
InvalidBean
java
redisson__redisson
redisson/src/main/java/org/redisson/transaction/operation/map/MapCacheFastPutOperation.java
{ "start": 813, "end": 1887 }
class ____ extends MapOperation { private long ttl; private TimeUnit ttlUnit; private long maxIdleTime; private TimeUnit maxIdleUnit; public MapCacheFastPutOperation() { } public MapCacheFastPutOperation(RMap<?, ?> map, Object key, Object value, long ttl, TimeUnit ttlUnit, long maxIdleTime, TimeUnit maxIdleUnit, String transactionId, long threadId) { super(map, key, value, transactionId, threadId); this.ttl = ttl; this.ttlUnit = ttlUnit; this.maxIdleTime = maxIdleTime; this.maxIdleUnit = maxIdleUnit; } @Override public void commit(RMap<Object, Object> map) { ((RMapCache<Object, Object>) map).fastPutAsync(key, value, ttl, ttlUnit, maxIdleTime, maxIdleUnit); } public long getTTL() { return ttl; } public TimeUnit getTTLUnit() { return ttlUnit; } public TimeUnit getMaxIdleUnit() { return maxIdleUnit; } public long getMaxIdleTime() { return maxIdleTime; } }
MapCacheFastPutOperation
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java
{ "start": 5087, "end": 5668 }
class ____ implements StreamObserver<HealthCheckResponse> { private int count = 0; private HealthCheckResponse response; @Override public void onNext(HealthCheckResponse data) { count++; response = data; } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() {} public int getCount() { return count; } public HealthCheckResponse getResponse() { return response; } } }
MockStreamObserver
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/authentication/logout/SimpleUrlLogoutSuccessHandler.java
{ "start": 1248, "end": 1613 }
class ____ extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, @Nullable Authentication authentication) throws IOException, ServletException { super.handle(request, response, authentication); } }
SimpleUrlLogoutSuccessHandler
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalizedResource.java
{ "start": 8397, "end": 9074 }
class ____ extends ResourceTransition { @Override public void transition(LocalizedResource rsrc, ResourceEvent event) { ResourceRequestEvent req = (ResourceRequestEvent) event; LocalizerContext ctxt = req.getContext(); ContainerId container = ctxt.getContainerId(); rsrc.ref.add(container); rsrc.dispatcher.getEventHandler().handle( new LocalizerResourceRequestEvent(rsrc, req.getVisibility(), ctxt, req.getLocalResourceRequest().getPattern())); } } /** * Resource localized, notify waiting containers. */ @SuppressWarnings("unchecked") // dispatcher not typed private static
FetchResourceTransition
java
google__guava
android/guava-tests/test/com/google/common/base/StringsTest.java
{ "start": 1169, "end": 10052 }
class ____ extends TestCase { public void testNullToEmpty() { assertEquals("", Strings.nullToEmpty(null)); assertEquals("", Strings.nullToEmpty("")); assertEquals("a", Strings.nullToEmpty("a")); } public void testEmptyToNull() { assertThat(Strings.emptyToNull(null)).isNull(); assertThat(Strings.emptyToNull("")).isNull(); assertEquals("a", Strings.emptyToNull("a")); } public void testIsNullOrEmpty() { assertTrue(Strings.isNullOrEmpty(null)); assertTrue(Strings.isNullOrEmpty("")); assertFalse(Strings.isNullOrEmpty("a")); } public void testPadStart_noPadding() { assertSame("", Strings.padStart("", 0, '-')); assertSame("x", Strings.padStart("x", 0, '-')); assertSame("x", Strings.padStart("x", 1, '-')); assertSame("xx", Strings.padStart("xx", 0, '-')); assertSame("xx", Strings.padStart("xx", 2, '-')); } public void testPadStart_somePadding() { assertEquals("-", Strings.padStart("", 1, '-')); assertEquals("--", Strings.padStart("", 2, '-')); assertEquals("-x", Strings.padStart("x", 2, '-')); assertEquals("--x", Strings.padStart("x", 3, '-')); assertEquals("-xx", Strings.padStart("xx", 3, '-')); } public void testPadStart_negativeMinLength() { assertSame("x", Strings.padStart("x", -1, '-')); } // TODO: could remove if we got NPT working in GWT somehow public void testPadStart_null() { assertThrows(NullPointerException.class, () -> Strings.padStart(null, 5, '0')); } public void testPadEnd_noPadding() { assertSame("", Strings.padEnd("", 0, '-')); assertSame("x", Strings.padEnd("x", 0, '-')); assertSame("x", Strings.padEnd("x", 1, '-')); assertSame("xx", Strings.padEnd("xx", 0, '-')); assertSame("xx", Strings.padEnd("xx", 2, '-')); } public void testPadEnd_somePadding() { assertEquals("-", Strings.padEnd("", 1, '-')); assertEquals("--", Strings.padEnd("", 2, '-')); assertEquals("x-", Strings.padEnd("x", 2, '-')); assertEquals("x--", Strings.padEnd("x", 3, '-')); assertEquals("xx-", Strings.padEnd("xx", 3, '-')); } public void testPadEnd_negativeMinLength() { assertSame("x", Strings.padEnd("x", -1, '-')); } public void testPadEnd_null() { assertThrows(NullPointerException.class, () -> Strings.padEnd(null, 5, '0')); } @SuppressWarnings("InlineMeInliner") // test of method that doesn't just delegate public void testRepeat() { String input = "20"; assertEquals("", Strings.repeat(input, 0)); assertEquals("20", Strings.repeat(input, 1)); assertEquals("2020", Strings.repeat(input, 2)); assertEquals("202020", Strings.repeat(input, 3)); assertEquals("", Strings.repeat("", 4)); for (int i = 0; i < 100; ++i) { assertEquals(2 * i, Strings.repeat(input, i).length()); } assertThrows(IllegalArgumentException.class, () -> Strings.repeat("x", -1)); assertThrows( ArrayIndexOutOfBoundsException.class, () -> Strings.repeat("12345678", (1 << 30) + 3)); } @SuppressWarnings("InlineMeInliner") // test of method that doesn't just delegate public void testRepeat_null() { assertThrows(NullPointerException.class, () -> Strings.repeat(null, 5)); } @SuppressWarnings("UnnecessaryStringBuilder") // We want to test a non-String CharSequence public void testCommonPrefix() { assertEquals("", Strings.commonPrefix("", "")); assertEquals("", Strings.commonPrefix("abc", "")); assertEquals("", Strings.commonPrefix("", "abc")); assertEquals("", Strings.commonPrefix("abcde", "xyz")); assertEquals("", Strings.commonPrefix("xyz", "abcde")); assertEquals("", Strings.commonPrefix("xyz", "abcxyz")); assertEquals("a", Strings.commonPrefix("abc", "aaaaa")); assertEquals("aa", Strings.commonPrefix("aa", "aaaaa")); assertEquals("abc", Strings.commonPrefix(new StringBuilder("abcdef"), "abcxyz")); // Identical valid surrogate pairs. assertEquals( "abc\uD8AB\uDCAB", Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uDCABxyz")); // Differing valid surrogate pairs. assertEquals("abc", Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uDCACxyz")); // One invalid pair. assertEquals("abc", Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uD8ABxyz")); // Two identical invalid pairs. assertEquals( "abc\uD8AB\uD8AC", Strings.commonPrefix("abc\uD8AB\uD8ACdef", "abc\uD8AB\uD8ACxyz")); // Two differing invalid pairs. assertEquals("abc\uD8AB", Strings.commonPrefix("abc\uD8AB\uD8ABdef", "abc\uD8AB\uD8ACxyz")); // One orphan high surrogate. assertEquals("", Strings.commonPrefix("\uD8AB\uDCAB", "\uD8AB")); // Two orphan high surrogates. assertEquals("\uD8AB", Strings.commonPrefix("\uD8AB", "\uD8AB")); } @SuppressWarnings("UnnecessaryStringBuilder") // We want to test a non-String CharSequence public void testCommonSuffix() { assertEquals("", Strings.commonSuffix("", "")); assertEquals("", Strings.commonSuffix("abc", "")); assertEquals("", Strings.commonSuffix("", "abc")); assertEquals("", Strings.commonSuffix("abcde", "xyz")); assertEquals("", Strings.commonSuffix("xyz", "abcde")); assertEquals("", Strings.commonSuffix("xyz", "xyzabc")); assertEquals("c", Strings.commonSuffix("abc", "ccccc")); assertEquals("aa", Strings.commonSuffix("aa", "aaaaa")); assertEquals("abc", Strings.commonSuffix(new StringBuilder("xyzabc"), "xxxabc")); // Identical valid surrogate pairs. assertEquals( "\uD8AB\uDCABdef", Strings.commonSuffix("abc\uD8AB\uDCABdef", "xyz\uD8AB\uDCABdef")); // Differing valid surrogate pairs. assertEquals("def", Strings.commonSuffix("abc\uD8AB\uDCABdef", "abc\uD8AC\uDCABdef")); // One invalid pair. assertEquals("def", Strings.commonSuffix("abc\uD8AB\uDCABdef", "xyz\uDCAB\uDCABdef")); // Two identical invalid pairs. assertEquals( "\uD8AB\uD8ABdef", Strings.commonSuffix("abc\uD8AB\uD8ABdef", "xyz\uD8AB\uD8ABdef")); // Two differing invalid pairs. assertEquals("\uDCABdef", Strings.commonSuffix("abc\uDCAB\uDCABdef", "abc\uDCAC\uDCABdef")); // One orphan low surrogate. assertEquals("", Strings.commonSuffix("x\uD8AB\uDCAB", "\uDCAB")); // Two orphan low surrogates. assertEquals("\uDCAB", Strings.commonSuffix("\uDCAB", "\uDCAB")); } public void testValidSurrogatePairAt() { assertTrue(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 0)); assertTrue(Strings.validSurrogatePairAt("abc\uD8AB\uDCAB", 3)); assertTrue(Strings.validSurrogatePairAt("abc\uD8AB\uDCABxyz", 3)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uD8AB", 0)); assertFalse(Strings.validSurrogatePairAt("\uDCAB\uDCAB", 0)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", -1)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 1)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", -2)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 2)); assertFalse(Strings.validSurrogatePairAt("x\uDCAB", 0)); assertFalse(Strings.validSurrogatePairAt("\uD8ABx", 0)); } @SuppressWarnings("LenientFormatStringValidation") // Intentional for testing. public void testLenientFormat() { assertEquals("%s", Strings.lenientFormat("%s")); assertEquals("5", Strings.lenientFormat("%s", 5)); assertEquals("foo [5]", Strings.lenientFormat("foo", 5)); assertEquals("foo [5, 6, 7]", Strings.lenientFormat("foo", 5, 6, 7)); assertEquals("%s 1 2", Strings.lenientFormat("%s %s %s", "%s", 1, 2)); assertEquals(" [5, 6]", Strings.lenientFormat("", 5, 6)); assertEquals("123", Strings.lenientFormat("%s%s%s", 1, 2, 3)); assertEquals("1%s%s", Strings.lenientFormat("%s%s%s", 1)); assertEquals("5 + 6 = 11", Strings.lenientFormat("%s + 6 = 11", 5)); assertEquals("5 + 6 = 11", Strings.lenientFormat("5 + %s = 11", 6)); assertEquals("5 + 6 = 11", Strings.lenientFormat("5 + 6 = %s", 11)); assertEquals("5 + 6 = 11", Strings.lenientFormat("%s + %s = %s", 5, 6, 11)); assertEquals( "5 + 6 = 11", Strings.lenientFormat("%s + %s = %s", (Object[]) new Integer[] {5, 6, 11})); assertEquals("null [null, null]", Strings.lenientFormat("%s", null, null, null)); assertEquals("null [5, 6]", Strings.lenientFormat(null, 5, 6)); assertEquals("null", Strings.lenientFormat("%s", (Object) null)); } @J2ktIncompatible // TODO(b/319404022): Allow passing null array as varargs public void testLenientFormat_nullArrayVarargs() { assertEquals("(Object[])null", Strings.lenientFormat("%s", (Object[]) null)); } @GwtIncompatible // GWT reflection includes less data public void testLenientFormat_badArgumentToString() { assertThat(Strings.lenientFormat("boiler %s plate", new ThrowsOnToString())) .matches( // J2kt nested
StringsTest
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/factory/nullreturn/NullableFactory.java
{ "start": 3181, "end": 3277 }
class ____ { public final String name; C(String name) { this.name = name; } }
C
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionWrapper.java
{ "start": 1666, "end": 7685 }
class ____ extends GroovyObjectSupport { private static final String PARENT = "parent"; private static final String AUTOWIRE = "autowire"; private static final String CONSTRUCTOR_ARGS = "constructorArgs"; private static final String FACTORY_BEAN = "factoryBean"; private static final String FACTORY_METHOD = "factoryMethod"; private static final String INIT_METHOD = "initMethod"; private static final String DESTROY_METHOD = "destroyMethod"; private static final String SINGLETON = "singleton"; private static final Set<String> dynamicProperties = Set.of(PARENT, AUTOWIRE, CONSTRUCTOR_ARGS, FACTORY_BEAN, FACTORY_METHOD, INIT_METHOD, DESTROY_METHOD, SINGLETON); private @Nullable String beanName; private final @Nullable Class<?> clazz; private final @Nullable Collection<?> constructorArgs; private @Nullable AbstractBeanDefinition definition; private @Nullable BeanWrapper definitionWrapper; private @Nullable String parentName; GroovyBeanDefinitionWrapper(String beanName) { this(beanName, null); } GroovyBeanDefinitionWrapper(@Nullable String beanName, @Nullable Class<?> clazz) { this(beanName, clazz, null); } GroovyBeanDefinitionWrapper(@Nullable String beanName, @Nullable Class<?> clazz, @Nullable Collection<?> constructorArgs) { this.beanName = beanName; this.clazz = clazz; this.constructorArgs = constructorArgs; } public @Nullable String getBeanName() { return this.beanName; } void setBeanDefinition(AbstractBeanDefinition definition) { this.definition = definition; } AbstractBeanDefinition getBeanDefinition() { if (this.definition == null) { this.definition = createBeanDefinition(); } return this.definition; } protected AbstractBeanDefinition createBeanDefinition() { AbstractBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(this.clazz); if (!CollectionUtils.isEmpty(this.constructorArgs)) { ConstructorArgumentValues cav = new ConstructorArgumentValues(); for (Object constructorArg : this.constructorArgs) { cav.addGenericArgumentValue(constructorArg); } bd.setConstructorArgumentValues(cav); } if (this.parentName != null) { bd.setParentName(this.parentName); } this.definitionWrapper = new BeanWrapperImpl(bd); return bd; } void setBeanDefinitionHolder(BeanDefinitionHolder holder) { this.definition = (AbstractBeanDefinition) holder.getBeanDefinition(); this.beanName = holder.getBeanName(); } BeanDefinitionHolder getBeanDefinitionHolder() { Assert.state(this.beanName != null, "Bean name must be set"); return new BeanDefinitionHolder(getBeanDefinition(), this.beanName); } void setParent(@Nullable Object obj) { Assert.notNull(obj, "Parent bean cannot be set to a null runtime bean reference"); if (obj instanceof String name) { this.parentName = name; } else if (obj instanceof RuntimeBeanReference runtimeBeanReference) { this.parentName = runtimeBeanReference.getBeanName(); } else if (obj instanceof GroovyBeanDefinitionWrapper wrapper) { this.parentName = wrapper.getBeanName(); } getBeanDefinition().setParentName(this.parentName); getBeanDefinition().setAbstract(false); } GroovyBeanDefinitionWrapper addProperty(String propertyName, @Nullable Object propertyValue) { if (propertyValue instanceof GroovyBeanDefinitionWrapper wrapper) { propertyValue = wrapper.getBeanDefinition(); } getBeanDefinition().getPropertyValues().add(propertyName, propertyValue); return this; } @Override public @Nullable Object getProperty(String property) { Assert.state(this.definitionWrapper != null, "BeanDefinition wrapper not initialized"); if (this.definitionWrapper.isReadableProperty(property)) { return this.definitionWrapper.getPropertyValue(property); } else if (dynamicProperties.contains(property)) { return null; } return super.getProperty(property); } @Override public void setProperty(String property, @Nullable Object newValue) { if (PARENT.equals(property)) { setParent(newValue); } else { AbstractBeanDefinition bd = getBeanDefinition(); Assert.state(this.definitionWrapper != null, "BeanDefinition wrapper not initialized"); if (AUTOWIRE.equals(property)) { if ("byName".equals(newValue)) { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME); } else if ("byType".equals(newValue)) { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } else if ("constructor".equals(newValue)) { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); } else if (Boolean.TRUE.equals(newValue)) { bd.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME); } } // constructorArgs else if (CONSTRUCTOR_ARGS.equals(property) && newValue instanceof List<?> args) { ConstructorArgumentValues cav = new ConstructorArgumentValues(); for (Object arg : args) { cav.addGenericArgumentValue(arg); } bd.setConstructorArgumentValues(cav); } // factoryBean else if (FACTORY_BEAN.equals(property)) { if (newValue != null) { bd.setFactoryBeanName(newValue.toString()); } } // factoryMethod else if (FACTORY_METHOD.equals(property)) { if (newValue != null) { bd.setFactoryMethodName(newValue.toString()); } } // initMethod else if (INIT_METHOD.equals(property)) { if (newValue != null) { bd.setInitMethodName(newValue.toString()); } } // destroyMethod else if (DESTROY_METHOD.equals(property)) { if (newValue != null) { bd.setDestroyMethodName(newValue.toString()); } } // singleton property else if (SINGLETON.equals(property)) { bd.setScope(Boolean.TRUE.equals(newValue) ? BeanDefinition.SCOPE_SINGLETON : BeanDefinition.SCOPE_PROTOTYPE); } else if (this.definitionWrapper.isWritableProperty(property)) { this.definitionWrapper.setPropertyValue(property, newValue); } else { super.setProperty(property, newValue); } } } }
GroovyBeanDefinitionWrapper
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/aggregate/JsonArrayAggFunction.java
{ "start": 2333, "end": 5208 }
class ____ extends BuiltInAggregateFunction<String, JsonArrayAggFunction.Accumulator> { private static final long serialVersionUID = 1L; /** * Marker that represents a {@code null} since {@link ListView} does not allow {@code null}s. * * <p>Note that due to {@code WrapJsonAggFunctionArgumentsRule} and the fact that this function * already only receives JSON strings, this value cannot be created by the user and is thus safe * to use. */ private static final StringData NULL_STR = StringData.fromString("null"); private final transient List<DataType> argumentTypes; private final boolean skipNulls; public JsonArrayAggFunction(LogicalType[] argumentTypes, boolean skipNulls) { this.argumentTypes = Arrays.stream(argumentTypes) .map(DataTypeUtils::toInternalDataType) .collect(Collectors.toList()); this.skipNulls = skipNulls; } @Override public List<DataType> getArgumentDataTypes() { return argumentTypes; } @Override public DataType getOutputDataType() { return DataTypes.STRING(); } @Override public DataType getAccumulatorDataType() { return DataTypes.STRUCTURED( Accumulator.class, DataTypes.FIELD( "list", ListView.newListViewDataType(DataTypes.STRING().toInternal()))); } @Override public Accumulator createAccumulator() { return new Accumulator(); } public void resetAccumulator(Accumulator acc) { acc.list.clear(); } public void accumulate(Accumulator acc, StringData itemData) throws Exception { if (itemData == null) { if (!skipNulls) { acc.list.add(NULL_STR); } } else { acc.list.add(itemData); } } public void retract(Accumulator acc, StringData itemData) throws Exception { if (itemData == null) { acc.list.remove(NULL_STR); } else { acc.list.remove(itemData); } } @Override public String getValue(Accumulator acc) { final ArrayNode rootNode = createArrayNode(); try { for (final StringData item : acc.list.get()) { final JsonNode itemNode = getNodeFactory().rawValueNode(new RawValue(item.toString())); rootNode.add(itemNode); } } catch (Exception e) { throw new TableException("The accumulator state could not be serialized.", e); } return serializeJson(rootNode); } // --------------------------------------------------------------------------------------------- /** Accumulator for {@link JsonArrayAggFunction}. */ public static
JsonArrayAggFunction
java
apache__camel
components/camel-metrics/src/test/java/org/apache/camel/component/metrics/GaugeEndpointTest.java
{ "start": 1412, "end": 2524 }
class ____ { private static final String METRICS_NAME = "metrics.name"; private static final Object VALUE = "subject"; @Mock private MetricRegistry registry; private MetricsEndpoint endpoint; @BeforeEach public void setUp() { endpoint = new MetricsEndpoint(null, null, registry, MetricsType.GAUGE, METRICS_NAME); } @Test public void testGaugeEndpoint() { assertThat(endpoint.getRegistry(), is(registry)); assertThat(endpoint.getMetricsName(), is(METRICS_NAME)); assertThat(endpoint.getSubject(), is(nullValue())); } @Test public void testCreateProducer() throws Exception { Producer producer = endpoint.createProducer(); assertThat(producer, is(notNullValue())); assertThat(producer, is(instanceOf(GaugeProducer.class))); } @Test public void testGetSubject() { assertThat(endpoint.getSubject(), is(nullValue())); } @Test public void testSetSubject() { endpoint.setSubject(VALUE); assertThat(endpoint.getSubject(), is(VALUE)); } }
GaugeEndpointTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AnnotationPositionTest.java
{ "start": 2771, "end": 3079 }
interface ____ {}") .addSourceLines( "EitherUse.java", """ import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.TYPE}) @
NonTypeUse
java
spring-projects__spring-security
crypto/src/main/java/org/springframework/security/crypto/password/MessageDigestPasswordEncoder.java
{ "start": 3001, "end": 6042 }
class ____ extends AbstractValidatingPasswordEncoder { private static final String PREFIX = "{"; private static final String SUFFIX = "}"; private StringKeyGenerator saltGenerator = new Base64StringKeyGenerator(); private boolean encodeHashAsBase64; private Digester digester; /** * The digest algorithm to use Supports the named * <a href="https://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html#AppA"> * Message Digest Algorithms</a> in the Java environment. * @param algorithm */ public MessageDigestPasswordEncoder(String algorithm) { this.digester = new Digester(algorithm, 1); } public void setEncodeHashAsBase64(boolean encodeHashAsBase64) { this.encodeHashAsBase64 = encodeHashAsBase64; } /** * Encodes the rawPass using a MessageDigest. If a salt is specified it will be merged * with the password before encoding. * @param rawPassword The plain text password * @return Hex string of password digest (or base64 encoded string if * encodeHashAsBase64 is enabled. */ @Override protected String encodeNonNullPassword(String rawPassword) { String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX; return digest(salt, rawPassword); } private String digest(String salt, CharSequence rawPassword) { String saltedPassword = rawPassword + salt; byte[] digest = this.digester.digest(Utf8.encode(saltedPassword)); String encoded = encodedNonNullPassword(digest); return salt + encoded; } private String encodedNonNullPassword(byte[] digest) { if (this.encodeHashAsBase64) { return Utf8.decode(Base64.getEncoder().encode(digest)); } return new String(Hex.encode(digest)); } /** * Takes a previously encoded password and compares it with a rawpassword after mixing * in the salt and encoding that value * @param rawPassword plain text password * @param encodedPassword previously encoded password * @return true or false */ @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { String salt = extractSalt(encodedPassword); String rawPasswordEncoded = digest(salt, rawPassword); return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded); } /** * Sets the number of iterations for which the calculated hash value should be * "stretched". If this is greater than one, the initial digest is calculated, the * digest function will be called repeatedly on the result for the additional number * of iterations. * @param iterations the number of iterations which will be executed on the hashed * password/salt value. Defaults to 1. */ public void setIterations(int iterations) { this.digester.setIterations(iterations); } private String extractSalt(String prefixEncodedPassword) { int start = prefixEncodedPassword.indexOf(PREFIX); if (start != 0) { return ""; } int end = prefixEncodedPassword.indexOf(SUFFIX, start); if (end < 0) { return ""; } return prefixEncodedPassword.substring(start, end + 1); } }
MessageDigestPasswordEncoder
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/util/OsgiServiceLocator.java
{ "start": 1238, "end": 1638 }
class ____ { private static final Logger LOGGER = StatusLogger.getLogger(); private static final boolean OSGI_AVAILABLE = checkOsgiAvailable(); private static boolean checkOsgiAvailable() { try { /* * OSGI classes of any version can still be present even if Log4j2 does not run in * an OSGI container, hence we check if this
OsgiServiceLocator
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SlotSharingExecutionSlotAllocatorTest.java
{ "start": 2935, "end": 25002 }
class ____ { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext.newBuilder() .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext.newBuilder() .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext.newBuilder().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests); } @Test void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext.newBuilder().addGroup(EV1, EV2).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); List<TestingPayload> payloads = assignments.values().stream() .map( assignment -> { TestingPayload payload = new TestingPayload(); assignment .getLogicalSlotFuture() .thenAccept( logicalSlot -> logicalSlot.tryAssignPayload(payload)); return payload; }) .collect(Collectors.toList()); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getFirstResponseOrFail().get(); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isFalse(); assertThat(physicalSlot.getPayload()).isNotNull(); physicalSlot.getPayload().release(new Throwable()); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isTrue(); assertThat(context.getSlotProvider().getCancellations()).containsKey(slotRequestId); context.allocateSlotsFor(EV1, EV2); // there should be one more physical slot allocation, as the first allocation should be // removed after releasing all logical slots assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSchedulePendingRequestBulkTimeoutCheck() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile pendingSlotResourceProfile = fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, allocationId); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(1); assertThat(bulk.getPendingRequests()).containsExactly(pendingSlotResourceProfile); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).hasSize(1); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).containsExactly(allocationId); } @Test void testRequestBulkCancel() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext.newBuilder() .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext.newBuilder() .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext.newBuilder().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext.newBuilder() .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static
SlotSharingExecutionSlotAllocatorTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/testutil/runner/GeneratedSource.java
{ "start": 1097, "end": 3070 }
class ____ implements BeforeTestExecutionCallback, AfterTestExecutionCallback { private static final String FIXTURES_ROOT = "fixtures/"; /** * ThreadLocal, as the source dir must be injected for this extension to gain access * to the compilation information. As test execution of different classes in parallel is supported. */ private ThreadLocal<String> sourceOutputDir = new ThreadLocal<>(); private Compiler compiler; private List<Class<?>> fixturesFor = new ArrayList<>(); @Override public void beforeTestExecution(ExtensionContext context) throws Exception { CompilationRequest compilationRequest = context.getStore( NAMESPACE ) .get( context.getUniqueId() + "-compilationRequest", CompilationRequest.class ); this.compiler = compilationRequest.getCompiler(); setSourceOutputDir( context.getStore( NAMESPACE ) .get( compilationRequest, CompilationCache.class ) .getLastSourceOutputDir() ); } @Override public void afterTestExecution(ExtensionContext context) throws Exception { handleFixtureComparison(); clearSourceOutputDir(); } private void setSourceOutputDir(String sourceOutputDir) { this.sourceOutputDir.set( sourceOutputDir ); } private void clearSourceOutputDir() { this.sourceOutputDir.remove(); } /** * Adds more mappers that need to be compared. * * The comparison is done for mappers and the are compared against a Java file that matches the name of the * Mapper that would have been created for the fixture. * * @param fixturesFor the classes that need to be compared with * @return the same rule for chaining */ public GeneratedSource addComparisonToFixtureFor(Class<?>... fixturesFor) { this.fixturesFor.addAll( Arrays.asList( fixturesFor ) ); return this; } /** * @param mapperClass the
GeneratedSource
java
google__dagger
javatests/dagger/hilt/android/testsubpackage/PackagePrivateConstructorTestClasses.java
{ "start": 1164, "end": 1294 }
class ____ extends Fragment { public BaseFragment() {} BaseFragment(int unused) {} } public abstract static
BaseFragment
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonFilter.java
{ "start": 273, "end": 346 }
interface ____ { Class<?> clazz(); String[] props(); }
FastJsonFilter
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/body/stream/StreamPair.java
{ "start": 3907, "end": 4748 }
class ____ extends ExtendedInputStream { final boolean left; private Side(boolean left) { this.left = left; } @Override public void allowDiscard() { if (setFlagAndCheckMask(left ? FLAG_DISCARD_L : FLAG_DISCARD_R, MASK_DISCARD)) { upstream.allowDiscard(); } } @Override public void cancelInput() { if (setFlagAndCheckMask(left ? FLAG_CANCEL_L : FLAG_CANCEL_R, MASK_CANCEL)) { upstream.cancelInput(); } } final boolean isOtherSideCancelled() { return (flags.get() & (left ? FLAG_CANCEL_R : FLAG_CANCEL_L)) != 0; } } /** * Both sides of {@link io.micronaut.http.body.ByteBody.SplitBackpressureMode#SLOWEST}. */ private final
Side
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/HttpMethod.java
{ "start": 1046, "end": 4991 }
class ____ implements Comparable<HttpMethod>, Serializable { private static final long serialVersionUID = -70133475680645360L; /** * The HTTP method {@code GET}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP 1.1, section 9.3</a> */ public static final HttpMethod GET = new HttpMethod("GET"); /** * The HTTP method {@code HEAD}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4">HTTP 1.1, section 9.4</a> */ public static final HttpMethod HEAD = new HttpMethod("HEAD"); /** * The HTTP method {@code POST}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP 1.1, section 9.5</a> */ public static final HttpMethod POST = new HttpMethod("POST"); /** * The HTTP method {@code PUT}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6">HTTP 1.1, section 9.6</a> */ public static final HttpMethod PUT = new HttpMethod("PUT"); /** * The HTTP method {@code PATCH}. * @see <a href="https://datatracker.ietf.org/doc/html/rfc5789#section-2">RFC 5789</a> */ public static final HttpMethod PATCH = new HttpMethod("PATCH"); /** * The HTTP method {@code DELETE}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7">HTTP 1.1, section 9.7</a> */ public static final HttpMethod DELETE = new HttpMethod("DELETE"); /** * The HTTP method {@code OPTIONS}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2">HTTP 1.1, section 9.2</a> */ public static final HttpMethod OPTIONS = new HttpMethod("OPTIONS"); /** * The HTTP method {@code TRACE}. * @see <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.8">HTTP 1.1, section 9.8</a> */ public static final HttpMethod TRACE = new HttpMethod("TRACE"); private static final HttpMethod[] values = new HttpMethod[] { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE }; private final String name; private HttpMethod(String name) { this.name = name; } /** * Returns an array containing the standard HTTP methods. Specifically, * this method returns an array containing {@link #GET}, {@link #HEAD}, * {@link #POST}, {@link #PUT}, {@link #PATCH}, {@link #DELETE}, * {@link #OPTIONS}, and {@link #TRACE}. * * <p>Note that the returned value does not include any HTTP methods defined * in WebDav. */ public static HttpMethod[] values() { HttpMethod[] copy = new HttpMethod[values.length]; System.arraycopy(values, 0, copy, 0, values.length); return copy; } /** * Return an {@code HttpMethod} object for the given value. * @param method the method value as a String * @return the corresponding {@code HttpMethod} */ public static HttpMethod valueOf(String method) { Assert.notNull(method, "Method must not be null"); return switch (method) { case "GET" -> GET; case "HEAD" -> HEAD; case "POST" -> POST; case "PUT" -> PUT; case "PATCH" -> PATCH; case "DELETE" -> DELETE; case "OPTIONS" -> OPTIONS; case "TRACE" -> TRACE; default -> new HttpMethod(method); }; } /** * Return the name of this method, for example, "GET", "POST". */ public String name() { return this.name; } /** * Determine whether this {@code HttpMethod} matches the given method value. * @param method the HTTP method as a String * @return {@code true} if it matches, {@code false} otherwise * @since 4.2.4 */ public boolean matches(String method) { return name().equals(method); } @Override public int compareTo(HttpMethod other) { return this.name.compareTo(other.name); } @Override public int hashCode() { return this.name.hashCode(); } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof HttpMethod that && this.name.equals(that.name))); } @Override public String toString() { return this.name; } }
HttpMethod
java
quarkusio__quarkus
extensions/cache/deployment/src/test/java/io/quarkus/cache/test/runtime/CompletionStageReturnTypeTest.java
{ "start": 5709, "end": 7237 }
class ____ { private volatile int cacheResultInvocations; private volatile int cacheInvalidateInvocations; private volatile int cacheInvalidateAllInvocations; @CacheResult(cacheName = CACHE_NAME_1) public CompletableFuture<String> cacheResult1(String key) { cacheResultInvocations++; return CompletableFuture.completedFuture(new String()); } @CacheResult(cacheName = CACHE_NAME_2) public CompletableFuture<Object> cacheResult2(String key) { return CompletableFuture.completedFuture(new Object()); } @CacheInvalidate(cacheName = CACHE_NAME_1) @CacheInvalidate(cacheName = CACHE_NAME_2) public CompletableFuture<Void> cacheInvalidate(String key) { cacheInvalidateInvocations++; return CompletableFuture.completedFuture(null); } @CacheInvalidateAll(cacheName = CACHE_NAME_1) @CacheInvalidateAll(cacheName = CACHE_NAME_2) public CompletableFuture<Void> cacheInvalidateAll() { cacheInvalidateAllInvocations++; return CompletableFuture.completedFuture(null); } public int getCacheResultInvocations() { return cacheResultInvocations; } public int getCacheInvalidateInvocations() { return cacheInvalidateInvocations; } public int getCacheInvalidateAllInvocations() { return cacheInvalidateAllInvocations; } } }
CachedService
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/h2/H2_Explain_0.java
{ "start": 915, "end": 2351 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "EXPLAIN SELECT * FROM TEST WHERE ID=1"; // System.out.println(sql); List<SQLStatement> stmtList = SQLUtils.toStatementList(sql, JdbcConstants.H2); SQLStatement stmt = stmtList.get(0); assertEquals(1, stmtList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.H2); stmt.accept(visitor); { String text = SQLUtils.toSQLString(stmt, JdbcConstants.H2); assertEquals("EXPLAIN\n" + "SELECT *\n" + "FROM TEST\n" + "WHERE ID = 1", text); } System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(2, visitor.getColumns().size()); assertEquals(1, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); assertEquals(0, visitor.getOrderByColumns().size()); assertTrue(visitor.containsTable("TEST")); } }
H2_Explain_0
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/RootLogLevelConfigurator.java
{ "start": 1076, "end": 1359 }
class ____ extends ContextAwareBase implements Configurator { @Override public ExecutionStatus configure(LoggerContext loggerContext) { loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.INFO); return ExecutionStatus.INVOKE_NEXT_IF_ANY; } }
RootLogLevelConfigurator
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/config/support/Parameter.java
{ "start": 1153, "end": 1937 }
interface ____ { /** * Specify the parameter key when append parameters to url */ String key() default ""; /** * If required=true, the value must not be empty when append to url */ boolean required() default false; /** * If excluded=true, ignore it when append parameters to url */ boolean excluded() default false; /** * if escaped=true, escape it when append parameters to url */ boolean escaped() default false; /** * If attribute=false, ignore it when processing refresh()/getMetadata()/equals()/toString() */ boolean attribute() default true; /** * If append=true, append new value to exist value instead of overriding it. */ boolean append() default false; }
Parameter
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/PolicyConfig.java
{ "start": 1903, "end": 2086 }
class ____ be registered for reflection if you run your application in a native mode. */ @WithDefault("io.quarkus.security.StringPermission") String permissionClass(); }
must
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/management/DefaultDependencyManagementInjector.java
{ "start": 2016, "end": 3815 }
class ____ extends MavenModelMerger { public void mergeManagedDependencies(Model model) { DependencyManagement dependencyManagement = model.getDependencyManagement(); if (dependencyManagement != null) { Map<Object, Dependency> dependencies = new HashMap<>(); Map<Object, Object> context = Collections.emptyMap(); for (Dependency dependency : model.getDependencies()) { Object key = getDependencyKey(dependency); dependencies.put(key, dependency); } for (Dependency managedDependency : dependencyManagement.getDependencies()) { Object key = getDependencyKey(managedDependency); Dependency dependency = dependencies.get(key); if (dependency != null) { mergeDependency(dependency, managedDependency, false, context); } } } } @Override protected void mergeDependency_Optional( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context) { // optional flag is not managed } @Override protected void mergeDependency_Exclusions( Dependency target, Dependency source, boolean sourceDominant, Map<Object, Object> context) { List<Exclusion> tgt = target.getExclusions(); if (tgt.isEmpty()) { List<Exclusion> src = source.getExclusions(); for (Exclusion element : src) { Exclusion clone = element.clone(); target.addExclusion(clone); } } } } }
ManagementModelMerger
java
apache__avro
lang/java/mapred/src/main/java/org/apache/avro/mapreduce/AvroKeyValueInputFormat.java
{ "start": 1746, "end": 2805 }
class ____<K, V> extends FileInputFormat<AvroKey<K>, AvroValue<V>> { private static final Logger LOG = LoggerFactory.getLogger(AvroKeyValueInputFormat.class); /** {@inheritDoc} */ @Override public RecordReader<AvroKey<K>, AvroValue<V>> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { Schema keyReaderSchema = AvroJob.getInputKeySchema(context.getConfiguration()); if (null == keyReaderSchema) { LOG.warn("Key reader schema was not set. Use AvroJob.setInputKeySchema() if desired."); LOG.info("Using a key reader schema equal to the writer schema."); } Schema valueReaderSchema = AvroJob.getInputValueSchema(context.getConfiguration()); if (null == valueReaderSchema) { LOG.warn("Value reader schema was not set. Use AvroJob.setInputValueSchema() if desired."); LOG.info("Using a value reader schema equal to the writer schema."); } return new AvroKeyValueRecordReader<>(keyReaderSchema, valueReaderSchema); } }
AvroKeyValueInputFormat
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/vector/reader/ParquetDataColumnReader.java
{ "start": 1154, "end": 3646 }
interface ____ { /** * Initialize the reader by page data. * * @param valueCount value count * @param in page data * @throws IOException */ void initFromPage(int valueCount, ByteBufferInputStream in) throws IOException; /** * @return the next Dictionary ID from the page */ int readValueDictionaryId(); /** * @return the next Boolean from the page */ boolean readBoolean(); /** * @return the next TinyInt from the page */ int readTinyInt(); /** * @return the next SmallInt from the page */ int readSmallInt(); /** * @return the next Integer from the page */ int readInteger(); /** * @return the next Long from the page */ long readLong(); /** * @return the next Float from the page */ float readFloat(); /** * @return the next Double from the page */ double readDouble(); /** * @return the next Bytes from the page */ byte[] readBytes(); /** * @return the next TimestampData from the page */ TimestampData readTimestamp(); /** * @return the underlying dictionary if current reader is dictionary encoded */ Dictionary getDictionary(); /** * @param id in dictionary * @return the Boolean from the dictionary by id */ boolean readBoolean(int id); /** * @param id in dictionary * @return the tiny int from the dictionary by id */ int readTinyInt(int id); /** * @param id in dictionary * @return the Small Int from the dictionary by id */ int readSmallInt(int id); /** * @param id in dictionary * @return the Integer from the dictionary by id */ int readInteger(int id); /** * @param id in dictionary * @return the Long from the dictionary by id */ long readLong(int id); /** * @param id in dictionary * @return the Float from the dictionary by id */ float readFloat(int id); /** * @param id in dictionary * @return the Double from the dictionary by id */ double readDouble(int id); /** * @param id in dictionary * @return the Bytes from the dictionary by id */ byte[] readBytes(int id); /** * @param id in dictionary * @return the TimestampData from the dictionary by id */ TimestampData readTimestamp(int id); }
ParquetDataColumnReader
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/main/java/org/apache/hadoop/yarn/server/router/rmadmin/RMAdminProtocolMethod.java
{ "start": 1987, "end": 7452 }
class ____ extends FederationMethodWrapper { private static final Logger LOG = LoggerFactory.getLogger(RMAdminProtocolMethod.class); private FederationStateStoreFacade federationFacade; private FederationRMAdminInterceptor rmAdminInterceptor; private Configuration configuration; public RMAdminProtocolMethod(Class<?>[] pTypes, Object... pParams) throws IOException { super(pTypes, pParams); } public <R> Collection<R> invokeConcurrent(FederationRMAdminInterceptor interceptor, Class<R> clazz, String subClusterId) throws YarnException { this.rmAdminInterceptor = interceptor; this.federationFacade = FederationStateStoreFacade.getInstance(interceptor.getConf()); this.configuration = interceptor.getConf(); if (StringUtils.isNotBlank(subClusterId)) { return invoke(clazz, subClusterId); } else { return invokeConcurrent(clazz); } } @Override protected <R> Collection<R> invokeConcurrent(Class<R> clazz) throws YarnException { String methodName = Thread.currentThread().getStackTrace()[3].getMethodName(); this.setMethodName(methodName); ThreadPoolExecutor executorService = rmAdminInterceptor.getExecutorService(); // Get Active SubClusters Map<SubClusterId, SubClusterInfo> subClusterInfo = federationFacade.getSubClusters(true); Collection<SubClusterId> subClusterIds = subClusterInfo.keySet(); List<Callable<Pair<SubClusterId, Object>>> callables = new ArrayList<>(); List<Future<Pair<SubClusterId, Object>>> futures = new ArrayList<>(); Map<SubClusterId, Exception> exceptions = new TreeMap<>(); // Generate parallel Callable tasks for (SubClusterId subClusterId : subClusterIds) { callables.add(() -> { ResourceManagerAdministrationProtocol protocol = rmAdminInterceptor.getAdminRMProxyForSubCluster(subClusterId); Class<?>[] types = this.getTypes(); Object[] params = this.getParams(); Method method = ResourceManagerAdministrationProtocol.class.getMethod(methodName, types); Object result = method.invoke(protocol, params); return Pair.of(subClusterId, result); }); } // Get results from multiple threads Map<SubClusterId, R> results = new TreeMap<>(); try { futures.addAll(executorService.invokeAll(callables)); futures.stream().forEach(future -> { SubClusterId subClusterId = null; try { Pair<SubClusterId, Object> pair = future.get(); subClusterId = pair.getKey(); Object result = pair.getValue(); if (result != null) { R rResult = clazz.cast(result); results.put(subClusterId, rResult); } } catch (InterruptedException | ExecutionException e) { Throwable cause = e.getCause(); LOG.error("Cannot execute {} on {}: {}", methodName, subClusterId, cause.getMessage()); exceptions.put(subClusterId, e); } }); } catch (InterruptedException e) { throw new YarnException("invokeConcurrent Failed.", e); } // All sub-clusters return results to be considered successful, // otherwise an exception will be thrown. if (exceptions != null && !exceptions.isEmpty()) { Set<SubClusterId> subClusterIdSets = exceptions.keySet(); throw new YarnException("invokeConcurrent Failed, An exception occurred in subClusterIds = " + StringUtils.join(subClusterIdSets, ",")); } // return result return results.values(); } /** * Call the method in the protocol according to the subClusterId. * * @param clazz return type * @param subClusterId subCluster Id * @param <R> Generic R * @return response collection. * @throws YarnException yarn exception. */ protected <R> Collection<R> invoke(Class<R> clazz, String subClusterId) throws YarnException { // Get the method name to call String methodName = Thread.currentThread().getStackTrace()[3].getMethodName(); this.setMethodName(methodName); // Get Active SubClusters Map<SubClusterId, SubClusterInfo> subClusterInfoMap = federationFacade.getSubClusters(true); // According to subCluster of string type, convert to SubClusterId type SubClusterId subClusterIdKey = SubClusterId.newInstance(subClusterId); // If the provided subCluster is not Active or does not exist, // an exception will be returned directly. if (!subClusterInfoMap.containsKey(subClusterIdKey)) { throw new YarnException("subClusterId = " + subClusterId + " is not an active subCluster."); } // Call the method in the protocol and convert it according to clazz. try { ResourceManagerAdministrationProtocol protocol = rmAdminInterceptor.getAdminRMProxyForSubCluster(subClusterIdKey); Class<?>[] types = this.getTypes(); Object[] params = this.getParams(); Method method = ResourceManagerAdministrationProtocol.class.getMethod(methodName, types); Object result = method.invoke(protocol, params); if (result != null) { return Collections.singletonList(clazz.cast(result)); } } catch (Exception e) { throw new YarnException("invoke Failed, An exception occurred in subClusterId = " + subClusterId, e); } throw new YarnException("invoke Failed, An exception occurred in subClusterId = " + subClusterId); } }
RMAdminProtocolMethod
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/webapp/TestBlocks.java
{ "start": 18632, "end": 18744 }
class ____ extends HtmlBlock { @Override protected void render(Block html) { } } }
HtmlBlockForTest
java
quarkusio__quarkus
extensions/grpc/api/src/main/java/io/quarkus/grpc/RegisterInterceptors.java
{ "start": 311, "end": 381 }
interface ____ { RegisterInterceptor[] value(); }
RegisterInterceptors
java
square__javapoet
src/test/java/com/squareup/javapoet/JavaFileTest.java
{ "start": 26291, "end": 26813 }
class ____ {\n" + " java.lang.Thread thread;\n" + "}\n"); } @Test public void alwaysQualifySupersedesJavaLangImports() { String source = JavaFile.builder("com.squareup.tacos", TypeSpec.classBuilder("Taco") .addField(Thread.class, "thread") .alwaysQualify("Thread") .build()) .skipJavaLangImports(true) .build() .toString(); assertThat(source).isEqualTo("" + "package com.squareup.tacos;\n" + "\n" + "
Taco
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/partial/PartialThriftComparer.java
{ "start": 1536, "end": 9826 }
enum ____ { UNKNOWN, EQUAL, NOT_EQUAL } // Metadata that defines the scope of comparison. private ThriftMetadata.ThriftStruct metadata; /** * Constructs an instance of {@link PartialThriftComparer}. * * @param metadata defines the scope of comparison. */ public PartialThriftComparer(ThriftMetadata.ThriftStruct metadata) { this.metadata = metadata; } /** * Compares thrift objects {@code t1} and {@code t2} and returns true if they are equal false * otherwise. The comparison is limited to the scope defined by {@code metadata}. * * <p>If the objects are not equal then it optionally records their differences if {@code sb} is * supplied. * * <p> * * @param t1 the first object. * @param t2 the second object. * @param sb if non-null, results of the comparison are returned in it. * @return true if objects are equivalent, false otherwise. */ public boolean areEqual(T t1, T t2, StringBuilder sb) { return this.areEqual(this.metadata, t1, t2, sb); } private boolean areEqual( ThriftMetadata.ThriftObject data, Object o1, Object o2, StringBuilder sb) { byte fieldType = data.data.valueMetaData.type; switch (fieldType) { case TType.STRUCT: return this.areEqual((ThriftMetadata.ThriftStruct) data, o1, o2, sb); case TType.LIST: return this.areEqual((ThriftMetadata.ThriftList) data, o1, o2, sb); case TType.MAP: return this.areEqual((ThriftMetadata.ThriftMap) data, o1, o2, sb); case TType.SET: return this.areEqual((ThriftMetadata.ThriftSet) data, o1, o2, sb); case TType.ENUM: return this.areEqual((ThriftMetadata.ThriftEnum) data, o1, o2, sb); case TType.BOOL: case TType.BYTE: case TType.I16: case TType.I32: case TType.I64: case TType.DOUBLE: case TType.STRING: return this.areEqual((ThriftMetadata.ThriftPrimitive) data, o1, o2, sb); default: throw unsupportedFieldTypeException(fieldType); } } private boolean areEqual( ThriftMetadata.ThriftStruct data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; } TBase t1 = (TBase) o1; TBase t2 = (TBase) o2; if (data.fields.size() == 0) { if (t1.equals(t2)) { return true; } else { appendNotEqual(data, sb, t1, t2, "struct1", "struct2"); return false; } } else { boolean overallResult = true; for (Object o : data.fields.values()) { ThriftMetadata.ThriftObject field = (ThriftMetadata.ThriftObject) o; Object f1 = t1.getFieldValue(field.fieldId); Object f2 = t2.getFieldValue(field.fieldId); overallResult = overallResult && this.areEqual(field, f1, f2, sb); } return overallResult; } } private boolean areEqual( ThriftMetadata.ThriftPrimitive data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; } if (data.isBinary()) { if (areBinaryFieldsEqual(o1, o2)) { return true; } } else if (o1.equals(o2)) { return true; } appendNotEqual(data, sb, o1, o2, "o1", "o2"); return false; } private boolean areEqual(ThriftMetadata.ThriftEnum data, Object o1, Object o2, StringBuilder sb) { ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; } if (o1.equals(o2)) { return true; } appendNotEqual(data, sb, o1, o2, "o1", "o2"); return false; } private boolean areEqual(ThriftMetadata.ThriftList data, Object o1, Object o2, StringBuilder sb) { List<Object> l1 = (List<Object>) o1; List<Object> l2 = (List<Object>) o2; ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; } if (!checkSizeEquality(data, l1, l2, sb, "list")) { return false; } for (int i = 0; i < l1.size(); i++) { Object e1 = l1.get(i); Object e2 = l2.get(i); if (!this.areEqual(data.elementData, e1, e2, sb)) { return false; } } return true; } private boolean areEqual(ThriftMetadata.ThriftSet data, Object o1, Object o2, StringBuilder sb) { Set<Object> s1 = (Set<Object>) o1; Set<Object> s2 = (Set<Object>) o2; ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; } if (!checkSizeEquality(data, s1, s2, sb, "set")) { return false; } for (Object e1 : s1) { if (!s2.contains(e1)) { appendResult(data, sb, "Element %s in s1 not found in s2", e1); return false; } } return true; } private boolean areEqual(ThriftMetadata.ThriftMap data, Object o1, Object o2, StringBuilder sb) { Map<Object, Object> m1 = (Map<Object, Object>) o1; Map<Object, Object> m2 = (Map<Object, Object>) o2; ComparisonResult result = checkNullEquality(data, o1, o2, sb); if (result != ComparisonResult.UNKNOWN) { return result == ComparisonResult.EQUAL; } if (!checkSizeEquality(data, m1.keySet(), m2.keySet(), sb, "map.keySet")) { return false; } for (Map.Entry e1 : m1.entrySet()) { Object k1 = e1.getKey(); if (!m2.containsKey(k1)) { appendResult(data, sb, "Key %s in m1 not found in m2", k1); return false; } Object v1 = e1.getValue(); Object v2 = m2.get(k1); if (!this.areEqual(data.valueData, v1, v2, sb)) { return false; } } return true; } private boolean areBinaryFieldsEqual(Object o1, Object o2) { if (o1 instanceof byte[]) { if (Arrays.equals((byte[]) o1, (byte[]) o2)) { return true; } } else if (o1 instanceof ByteBuffer) { if (((ByteBuffer) o1).compareTo((ByteBuffer) o2) == 0) { return true; } } else { throw new UnsupportedOperationException( String.format("Unsupported binary field type: %s", o1.getClass().getName())); } return false; } private void appendResult( ThriftMetadata.ThriftObject data, StringBuilder sb, String format, Object... args) { if (sb != null) { String msg = String.format(format, args); sb.append(data.fieldId.getFieldName()); sb.append(" : "); sb.append(msg); } } private void appendNotEqual( ThriftMetadata.ThriftObject data, StringBuilder sb, Object o1, Object o2, String o1name, String o2name) { String o1s = o1.toString(); String o2s = o2.toString(); if ((o1s.length() + o2s.length()) < 100) { appendResult(data, sb, "%s (%s) != %s (%s)", o1name, o1s, o2name, o2s); } else { appendResult( data, sb, "%s != %s\n%s =\n%s\n%s =\n%s\n", o1name, o2name, o1name, o1s, o2name, o2s); } } private ComparisonResult checkNullEquality( ThriftMetadata.ThriftObject data, Object o1, Object o2, StringBuilder sb) { if ((o1 == null) && (o2 == null)) { return ComparisonResult.EQUAL; } if (o1 == null) { appendResult(data, sb, "o1 (null) != o2"); } if (o2 == null) { appendResult(data, sb, "o1 != o2 (null)"); } return ComparisonResult.UNKNOWN; } private boolean checkSizeEquality( ThriftMetadata.ThriftObject data, Collection c1, Collection c2, StringBuilder sb, String typeName) { if (c1.size() != c2.size()) { appendResult( data, sb, "%s1.size(%d) != %s2.size(%d)", typeName, c1.size(), typeName, c2.size()); return false; } return true; } static UnsupportedOperationException unsupportedFieldTypeException(byte fieldType) { return new UnsupportedOperationException("field type not supported: '" + fieldType + "'"); } }
ComparisonResult
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/util/AbstractArray.java
{ "start": 569, "end": 1210 }
class ____ implements BigArray { private final BigArrays bigArrays; public final boolean clearOnResize; private final AtomicBoolean closed = new AtomicBoolean(false); AbstractArray(BigArrays bigArrays, boolean clearOnResize) { this.bigArrays = bigArrays; this.clearOnResize = clearOnResize; } @Override public final void close() { if (closed.compareAndSet(false, true)) { try { bigArrays.adjustBreaker(-ramBytesUsed(), true); } finally { doClose(); } } } protected abstract void doClose(); }
AbstractArray
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/value/spi/CustomErroneousEnumMappingStrategyTest.java
{ "start": 1281, "end": 1735 }
enum ____ " + "org\\.mapstruct\\.ap\\.test\\.value\\.spi\\.CustomCheeseType." + " Constant was returned from EnumMappingStrategy: .*CustomErroneousEnumMappingStrategy@.*" ), @Diagnostic( type = CustomCheeseMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 33, messageRegExp = "Constant INCORRECT doesn't exist in
type
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/registry/classloading/NotLeakingTestAction.java
{ "start": 261, "end": 691 }
class ____ implements Runnable { @Override public void run() { checkExpectedClassLoader( getClass() ); } protected void checkExpectedClassLoader(Class aClass) { final ClassLoader owningClassloader = aClass.getClassLoader(); if ( !owningClassloader.getName().equals( "TestIsolatedIsolatedClassLoader" ) ) { throw new IllegalStateException( "Not being loaded by the expected classloader" ); } } }
NotLeakingTestAction
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/util/clhm/ConcurrentLinkedHashMap.java
{ "start": 47254, "end": 47864 }
class ____ implements Iterator<K> { final Iterator<K> iterator = data.keySet().iterator(); K current; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public K next() { current = iterator.next(); return current; } @Override public void remove() { checkState(current != null); ConcurrentLinkedHashMap.this.remove(current); current = null; } } /** An adapter to safely externalize the values. */ final
KeyIterator
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/mock/web/reactive/function/server/MockServerRequest.java
{ "start": 9323, "end": 14951 }
class ____ implements Builder { private HttpMethod method = HttpMethod.GET; private URI uri = URI.create("http://localhost"); private String contextPath = ""; private MockHeaders headers = new MockHeaders(new HttpHeaders()); private MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>(); private @Nullable Object body; private Map<String, Object> attributes = new ConcurrentHashMap<>(); private MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(); private Map<String, String> pathVariables = new LinkedHashMap<>(); private @Nullable WebSession session; private @Nullable Principal principal; private @Nullable InetSocketAddress remoteAddress; private @Nullable InetSocketAddress localAddress; private List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders(); private @Nullable ApiVersionStrategy versionStrategy; private @Nullable ServerWebExchange exchange; @Override public Builder method(HttpMethod method) { Assert.notNull(method, "'method' must not be null"); this.method = method; return this; } @Override public Builder uri(URI uri) { Assert.notNull(uri, "'uri' must not be null"); this.uri = uri; return this; } @Override public Builder contextPath(String contextPath) { Assert.notNull(contextPath, "'contextPath' must not be null"); this.contextPath = contextPath; return this; } @Override public Builder cookie(HttpCookie... cookies) { Arrays.stream(cookies).forEach(cookie -> this.cookies.add(cookie.getName(), cookie)); return this; } @Override public Builder cookies(MultiValueMap<String, HttpCookie> cookies) { Assert.notNull(cookies, "'cookies' must not be null"); this.cookies = cookies; return this; } @Override public Builder header(String key, String value) { Assert.notNull(key, "'key' must not be null"); Assert.notNull(value, "'value' must not be null"); this.headers.header(key, value); return this; } @Override public Builder headers(HttpHeaders headers) { Assert.notNull(headers, "'headers' must not be null"); this.headers = new MockHeaders(headers); return this; } @Override public Builder attribute(String name, Object value) { Assert.notNull(name, "'name' must not be null"); Assert.notNull(value, "'value' must not be null"); this.attributes.put(name, value); return this; } @Override public Builder attributes(Map<String, Object> attributes) { Assert.notNull(attributes, "'attributes' must not be null"); this.attributes = attributes; return this; } @Override public Builder queryParam(String key, String value) { Assert.notNull(key, "'key' must not be null"); Assert.notNull(value, "'value' must not be null"); this.queryParams.add(key, value); return this; } @Override public Builder queryParams(MultiValueMap<String, String> queryParams) { Assert.notNull(queryParams, "'queryParams' must not be null"); this.queryParams = queryParams; return this; } @Override public Builder pathVariable(String key, String value) { Assert.notNull(key, "'key' must not be null"); Assert.notNull(value, "'value' must not be null"); this.pathVariables.put(key, value); return this; } @Override public Builder pathVariables(Map<String, String> pathVariables) { Assert.notNull(pathVariables, "'pathVariables' must not be null"); this.pathVariables = pathVariables; return this; } @Override public Builder session(WebSession session) { Assert.notNull(session, "'session' must not be null"); this.session = session; return this; } @Override public Builder principal(Principal principal) { Assert.notNull(principal, "'principal' must not be null"); this.principal = principal; return this; } @Override public Builder remoteAddress(InetSocketAddress remoteAddress) { Assert.notNull(remoteAddress, "'remoteAddress' must not be null"); this.remoteAddress = remoteAddress; return this; } @Override public Builder localAddress(InetSocketAddress localAddress) { Assert.notNull(localAddress, "'localAddress' must not be null"); this.localAddress = localAddress; return this; } @Override public Builder messageReaders(List<HttpMessageReader<?>> messageReaders) { Assert.notNull(messageReaders, "'messageReaders' must not be null"); this.messageReaders = messageReaders; return this; } @Override public Builder apiVersionStrategy(@Nullable ApiVersionStrategy versionStrategy) { this.versionStrategy = versionStrategy; return this; } @Override public Builder exchange(ServerWebExchange exchange) { Assert.notNull(exchange, "'exchange' must not be null"); this.exchange = exchange; return this; } @Override public MockServerRequest body(Object body) { this.body = body; return new MockServerRequest(this.method, this.uri, this.contextPath, this.headers, this.cookies, this.body, this.attributes, this.queryParams, this.pathVariables, this.session, this.principal, this.remoteAddress, this.localAddress, this.messageReaders, this.versionStrategy, this.exchange); } @Override public MockServerRequest build() { return new MockServerRequest(this.method, this.uri, this.contextPath, this.headers, this.cookies, null, this.attributes, this.queryParams, this.pathVariables, this.session, this.principal, this.remoteAddress, this.localAddress, this.messageReaders, this.versionStrategy, this.exchange); } } private static
BuilderImpl
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/support/PropertyBindingSupportTest.java
{ "start": 13849, "end": 25317 }
class ____ created so its empty assertEquals(0, foo.getBar().getWork().getId()); assertNull(foo.getBar().getWork().getName()); } @Test public void testAutowired() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "bar.age", "33"); PropertyBindingSupport.build().bind(context, foo, "bar.{{committer}}", "true"); PropertyBindingSupport.build().bind(context, foo, "bar.gold-customer", "true"); PropertyBindingSupport.build().bind(context, foo, "bar.work", "#autowired"); assertEquals("James", foo.getName()); assertEquals(33, foo.getBar().getAge()); assertTrue(foo.getBar().isRider()); assertTrue(foo.getBar().isGoldCustomer()); assertEquals(456, foo.getBar().getWork().getId()); assertEquals("Acme", foo.getBar().getWork().getName()); } @Test public void testMandatory() { Foo foo = new Foo(); PropertyBindingSupport.build().withMandatory(true).bind(context, foo, "name", "James"); boolean bound = PropertyBindingSupport.build().bind(context, foo, "bar.myAge", "33"); assertFalse(bound); try { PropertyBindingSupport.build().withMandatory(true).bind(context, foo, "bar.myAge", "33"); fail("Should have thrown exception"); } catch (PropertyBindingException e) { assertEquals("myAge", e.getPropertyName()); assertSame(foo.getBar(), e.getTarget()); } } @Test public void testDoesNotExistClass() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); try { PropertyBindingSupport.build().bind(context, foo, "bar.work", "#class:org.apache.camel.support.DoesNotExist"); fail("Should throw exception"); } catch (PropertyBindingException e) { assertIsInstanceOf(ClassNotFoundException.class, e.getCause()); } } @Test public void testNullInjectorClass() { Foo foo = new Foo(); context.setInjector(new Injector() { @Override public <T> T newInstance(Class<T> type) { return null; } @Override public <T> T newInstance(Class<T> type, String factoryMethod) { return null; } @Override public <T> T newInstance(Class<T> type, Class<?> factoryClass, String factoryMethod) { return null; } @Override public <T> T newInstance(Class<T> type, boolean postProcessBean) { return null; } @Override public boolean supportsAutoWiring() { return false; } }); PropertyBindingSupport.build().bind(context, foo, "name", "James"); try { PropertyBindingSupport.build().bind(context, foo, "bar.work", "#class:org.apache.camel.support.Company"); fail("Should throw exception"); } catch (PropertyBindingException e) { assertIsInstanceOf(IllegalStateException.class, e.getCause()); } } @Test public void testNestedClassConstructorParameterOneParameter() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.Animal('Tony Tiger')"); PropertyBindingSupport.build().bind(context, foo, "animal.dangerous", "true"); assertEquals("James", foo.getName()); assertEquals("Tony Tiger", foo.getAnimal().getName()); assertTrue(foo.getAnimal().isDangerous()); } @Test public void testNestedClassConstructorParameterPlaceholder() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.Animal('{{companyName}}', false)"); assertEquals("James", foo.getName()); assertEquals("Acme", foo.getAnimal().getName()); assertFalse(foo.getAnimal().isDangerous()); } @Test public void testNestedClassConstructorParameterTwoParameter() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.Animal('Donald Duck', false)"); assertEquals("James", foo.getName()); assertEquals("Donald Duck", foo.getAnimal().getName()); assertFalse(foo.getAnimal().isDangerous()); } @Test public void testNestedClassConstructorParameterMandatoryBean() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); try { PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.Animal('#bean:myName', false)"); fail("Should have thrown exception"); } catch (PropertyBindingException e) { NoSuchBeanException nsb = assertIsInstanceOf(NoSuchBeanException.class, e.getCause()); assertEquals("myName", nsb.getName()); } // add bean and try again context.getRegistry().bind("myName", "Acme"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.Animal('#bean:myName', false)"); assertEquals("James", foo.getName()); assertEquals("Acme", foo.getAnimal().getName()); assertFalse(foo.getAnimal().isDangerous()); } @Test public void testNestedClassFactoryParameterOneParameter() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.AnimalFactory#createAnimal('Tiger')"); assertEquals("James", foo.getName()); assertEquals("Tiger", foo.getAnimal().getName()); assertTrue(foo.getAnimal().isDangerous()); } @Test public void testNestedClassFactoryParameterTwoParameter() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.AnimalFactory#createAnimal('Donald Duck', false)"); assertEquals("James", foo.getName()); assertEquals("Donald Duck", foo.getAnimal().getName()); assertFalse(foo.getAnimal().isDangerous()); } @Test public void testNestedClassFactoryParameterPlaceholder() { Foo foo = new Foo(); PropertyBindingSupport.build().bind(context, foo, "name", "James"); PropertyBindingSupport.build().bind(context, foo, "animal", "#class:org.apache.camel.support.AnimalFactory#createAnimal('{{companyName}}', false)"); assertEquals("James", foo.getName()); assertEquals("Acme", foo.getAnimal().getName()); assertFalse(foo.getAnimal().isDangerous()); } @Test public void testPropertiesOptionalKey() { Foo foo = new Foo(); Map<String, Object> prop = new HashMap<>(); prop.put("name", "James"); prop.put("?bar.AGE", "33"); prop.put("BAR.{{committer}}", "true"); prop.put("bar.gOLd-Customer", "true"); prop.put("?bar.silver-Customer", "true"); prop.put("?bAr.work.ID", "123"); prop.put("?bar.WORk.naME", "{{companyName}}"); prop.put("?bar.work.addresss", "Some street"); prop.put("?bar.work.addresss.zip", "1234"); PropertyBindingSupport.build().withIgnoreCase(true).bind(context, foo, prop); assertEquals("James", foo.getName()); assertEquals(33, foo.getBar().getAge()); assertTrue(foo.getBar().isRider()); assertTrue(foo.getBar().isGoldCustomer()); assertEquals(123, foo.getBar().getWork().getId()); assertEquals("Acme", foo.getBar().getWork().getName()); assertFalse(prop.isEmpty(), "Should NOT bind all properties"); assertEquals(3, prop.size()); assertTrue(prop.containsKey("?bar.silver-Customer")); assertTrue(prop.containsKey("?bar.work.addresss")); assertTrue(prop.containsKey("?bar.work.addresss.zip")); } @Test public void testPropertiesOptionalKeyMandatory() { Foo foo = new Foo(); Map<String, Object> prop = new HashMap<>(); prop.put("name", "James"); prop.put("bar.AGE", "33"); prop.put("BAR.{{committer}}", "true"); prop.put("bar.gOLd-Customer", "true"); prop.put("?bar.silver-Customer", "true"); prop.put("?bAr.work.ID", "123"); prop.put("?bar.WORk.naME", "{{companyName}}"); prop.put("?bar.work.addresss", "Some street"); prop.put("?bar.work.addresss.zip", "1234"); PropertyBindingSupport.build().withIgnoreCase(true).withMandatory(true).bind(context, foo, prop); assertEquals("James", foo.getName()); assertEquals(33, foo.getBar().getAge()); assertTrue(foo.getBar().isRider()); assertTrue(foo.getBar().isGoldCustomer()); assertEquals(123, foo.getBar().getWork().getId()); assertEquals("Acme", foo.getBar().getWork().getName()); assertFalse(prop.isEmpty(), "Should NOT bind all properties"); assertEquals(3, prop.size()); assertTrue(prop.containsKey("?bar.silver-Customer")); assertTrue(prop.containsKey("?bar.work.addresss")); assertTrue(prop.containsKey("?bar.work.addresss.zip")); // should not fail as we marked the option as optional prop.put("?bar.unknown", "123"); PropertyBindingSupport.build().withIgnoreCase(true).withMandatory(true).bind(context, foo, prop); prop.remove("?bar.unknown"); // should fail as its mandatory prop.put("bar.unknown", "123"); try { PropertyBindingSupport.build().withIgnoreCase(true).withMandatory(true).bind(context, foo, prop); fail("Should fail"); } catch (PropertyBindingException e) { assertEquals("unknown", e.getPropertyName()); } } @Test public void testConvert() { Foo foo = new Foo(); Map<String, Object> prop = new HashMap<>(); prop.put("name", "James"); prop.put("bar.age", "#valueAs(Integer):33"); prop.put("bar.rider", "#valueAs(boolean):true"); prop.put("bar.gold-customer", "#valueAs(boolean):true"); prop.put("bar.work.id", "#valueAs(int):123"); prop.put("bar.work.name", "{{companyName}}"); PropertyBindingSupport.bindProperties(context, foo, prop); assertEquals("James", foo.getName()); assertEquals(33, foo.getBar().getAge()); assertTrue(foo.getBar().isRider()); assertTrue(foo.getBar().isGoldCustomer()); assertEquals(123, foo.getBar().getWork().getId()); assertEquals("Acme", foo.getBar().getWork().getName()); assertTrue(prop.isEmpty(), "Should bind all properties"); } public static
was
java
micronaut-projects__micronaut-core
http-client-jdk/src/main/java/io/micronaut/http/client/jdk/DefaultJdkHttpClient.java
{ "start": 2428, "end": 6425 }
class ____ extends AbstractJdkHttpClient implements JdkHttpClient { public DefaultJdkHttpClient( @Nullable LoadBalancer loadBalancer, HttpVersionSelection httpVersion, @NonNull HttpClientConfiguration configuration, @Nullable String contextPath, @Nullable HttpClientFilterResolver<ClientFilterResolutionContext> filterResolver, @Nullable List<HttpFilterResolver.FilterEntry> clientFilterEntries, MediaTypeCodecRegistry mediaTypeCodecRegistry, MessageBodyHandlerRegistry messageBodyHandlerRegistry, RequestBinderRegistry requestBinderRegistry, String clientId, ConversionService conversionService, JdkClientSslBuilder sslBuilder, CookieDecoder cookieDecoder ) { super( configuration.getLoggerName().map(LoggerFactory::getLogger).orElseGet(() -> LoggerFactory.getLogger(DefaultJdkHttpClient.class)), loadBalancer, httpVersion, configuration, contextPath, filterResolver, clientFilterEntries, mediaTypeCodecRegistry, messageBodyHandlerRegistry, requestBinderRegistry, clientId, conversionService, sslBuilder, cookieDecoder ); } public DefaultJdkHttpClient(URI uri, ConversionService conversionService) { this( uri == null ? null : LoadBalancer.fixed(uri), null, new DefaultHttpClientConfiguration(), null, null, null, createDefaultMediaTypeRegistry(), JdkHttpClientFactory.createDefaultMessageBodyHandlerRegistry(), new DefaultRequestBinderRegistry(conversionService), null, conversionService, new JdkClientSslBuilder(new ResourceResolver()), new CompositeCookieDecoder(List.of(new DefaultCookieDecoder())) ); } public DefaultJdkHttpClient( URI uri, HttpClientConfiguration configuration, MediaTypeCodecRegistry mediaTypeCodecRegistry, MessageBodyHandlerRegistry messageBodyHandlerRegistry, ConversionService conversionService ) { this( uri == null ? null : LoadBalancer.fixed(uri), null, configuration, null, null, null, mediaTypeCodecRegistry, messageBodyHandlerRegistry, new DefaultRequestBinderRegistry(conversionService), null, conversionService, new JdkClientSslBuilder(new ResourceResolver()), new CompositeCookieDecoder(List.of(new DefaultCookieDecoder())) ); } private static MediaTypeCodecRegistry createDefaultMediaTypeRegistry() { JsonMapper mapper = JsonMapper.createDefault(); ApplicationConfiguration configuration = new ApplicationConfiguration(); return MediaTypeCodecRegistry.of( new JsonMediaTypeCodec(mapper, configuration, null), new JsonStreamMediaTypeCodec(mapper, configuration, null) ); } @Override public BlockingHttpClient toBlocking() { return new JdkBlockingHttpClient( loadBalancer, httpVersion, configuration, contextPath, filterResolver, clientFilterEntries, mediaTypeCodecRegistry, messageBodyHandlerRegistry, requestBinderRegistry, clientId, conversionService, sslBuilder, cookieDecoder ); } @Override public <I, O, E> Publisher<HttpResponse<O>> exchange(@NonNull HttpRequest<I> request, @NonNull Argument<O> bodyType, @NonNull Argument<E> errorType) { return exchangeImpl(request, bodyType); } @Override public boolean isRunning() { return false; } }
DefaultJdkHttpClient
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java
{ "start": 27875, "end": 27983 }
class ____ { @SuppressWarnings("unused") public boolean isTargetMethod() { return false; } }
A
java
quarkusio__quarkus
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/client/tls/MtlsWithJKSTrustStoreWithHttpServerWithAliasTest.java
{ "start": 1033, "end": 3336 }
class ____ { private static final String configuration = """ quarkus.grpc.clients.hello.plain-text=false quarkus.grpc.clients.hello.tls.trust-certificate-jks.path=target/certs/grpc-alias-client-truststore.jks quarkus.grpc.clients.hello.tls.trust-certificate-jks.password=password quarkus.grpc.clients.hello.tls.key-certificate-jks.path=target/certs/grpc-alias-client-keystore.jks quarkus.grpc.clients.hello.tls.key-certificate-jks.password=password quarkus.grpc.clients.hello.tls.key-certificate-jks.alias=alias quarkus.grpc.clients.hello.tls.key-certificate-jks.alias-password=alias-password quarkus.grpc.clients.hello.tls.enabled=true quarkus.grpc.clients.hello.use-quarkus-grpc-client=true quarkus.grpc.server.use-separate-server=false quarkus.grpc.server.plain-text=false # Force the client to use TLS for the tests quarkus.http.ssl.certificate.key-store-file=target/certs/grpc-alias-keystore.jks quarkus.http.ssl.certificate.key-store-password=password quarkus.http.ssl.certificate.key-store-alias=alias quarkus.http.ssl.certificate.key-store-alias-password=alias-password quarkus.http.ssl.certificate.trust-store-file=target/certs/grpc-alias-server-truststore.jks quarkus.http.ssl.certificate.trust-store-password=password quarkus.http.ssl.client-auth=REQUIRED quarkus.http.insecure-requests=disabled """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addPackage(HelloWorldTlsEndpoint.class.getPackage()) .addPackage(GreeterGrpc.class.getPackage()) .add(new StringAsset(configuration), "application.properties")); @GrpcClient("hello") GreeterGrpc.GreeterBlockingStub blockingHelloService; @Test void testClientTlsConfiguration() { HelloReply reply = blockingHelloService.sayHello(HelloRequest.newBuilder().setName("neo").build()); assertThat(reply.getMessage()).isEqualTo("Hello neo"); } }
MtlsWithJKSTrustStoreWithHttpServerWithAliasTest
java
square__retrofit
retrofit/src/main/java/retrofit2/SkipCallbackExecutorImpl.java
{ "start": 748, "end": 1798 }
class ____ implements SkipCallbackExecutor { private static final SkipCallbackExecutor INSTANCE = new SkipCallbackExecutorImpl(); static Annotation[] ensurePresent(Annotation[] annotations) { if (Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)) { return annotations; } Annotation[] newAnnotations = new Annotation[annotations.length + 1]; // Place the skip annotation first since we're guaranteed to check for it in the call adapter. newAnnotations[0] = SkipCallbackExecutorImpl.INSTANCE; System.arraycopy(annotations, 0, newAnnotations, 1, annotations.length); return newAnnotations; } @Override public Class<? extends Annotation> annotationType() { return SkipCallbackExecutor.class; } @Override public boolean equals(Object obj) { return obj instanceof SkipCallbackExecutor; } @Override public int hashCode() { return 0; } @Override public String toString() { return "@" + SkipCallbackExecutor.class.getName() + "()"; } }
SkipCallbackExecutorImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClashTest.java
{ "start": 888, "end": 1369 }
class ____ { @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(FunctionalInterfaceClash.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", """ import java.util.function.Function; import java.util.function.Consumer; public
FunctionalInterfaceClashTest
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java
{ "start": 8442, "end": 9253 }
class ____ implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (ReflectionUtils.isEqualsMethod(method)) { // Only consider equal when proxies are identical. return (proxy == args[0]); } else if (ReflectionUtils.isHashCodeMethod(method)) { // Use hashCode of reference proxy. return System.identityHashCode(proxy); } else if (!initialized && ReflectionUtils.isToStringMethod(method)) { return "Early singleton proxy for interfaces " + ObjectUtils.nullSafeToString(getEarlySingletonInterfaces()); } try { return method.invoke(getSingletonInstance(), args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }
EarlySingletonInvocationHandler
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.java
{ "start": 14888, "end": 15304 }
class ____ { static RequestCache requestCache = mock(RequestCache.class); @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .requestCache((cache) -> cache .requestCache(requestCache)) .requestCache(withDefaults()); return http.build(); // @formatter:on } } @Configuration @EnableWebSecurity static
InvokeTwiceDoesNotOverrideConfig
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/IntervalJoinTestPrograms.java
{ "start": 1179, "end": 10231 }
class ____ { static final Row[] ORDER_BEFORE_DATA = { Row.of(1, "2020-04-15 08:00:01"), Row.of(2, "2020-04-15 08:00:02"), Row.of(4, "2020-04-15 08:00:04"), Row.of(5, "2020-04-15 08:00:05"), Row.of(3, "2020-04-15 08:00:03") }; static final Row[] SHIPMENT_BEFORE_DATA = { Row.of(2, 1, "2020-04-15 08:00:02"), Row.of(5, 2, "2020-04-15 08:00:05"), Row.of(6, 5, "2020-04-15 08:00:06"), Row.of(15, 4, "2020-04-15 08:00:15"), Row.of(16, 6, "2020-04-15 08:00:15") }; static final Row[] ORDER_AFTER_DATA = { Row.of(7, "2020-04-15 08:00:09"), Row.of(10, "2020-04-15 08:00:11"), }; static final Row[] SHIPMENT_AFTER_DATA = { Row.of(7, 3, "2020-04-15 08:00:15"), Row.of(11, 7, "2020-04-15 08:00:16"), Row.of(13, 10, "2020-04-15 08:00:16") }; static final String[] ORDERS_EVENT_TIME_SCHEMA = { "id INT", "order_ts_str STRING", "order_ts AS TO_TIMESTAMP(order_ts_str)", "WATERMARK for `order_ts` AS `order_ts` - INTERVAL '1' SECOND" }; static final String[] ORDERS_PROC_TIME_SCHEMA = { "id INT", "order_ts_str STRING", "proc_time AS PROCTIME()" }; static final String[] SHIPMENTS_EVENT_TIME_SCHEMA = { "id INT", "order_id INT", "shipment_ts_str STRING", "shipment_ts AS TO_TIMESTAMP(shipment_ts_str)", "WATERMARK for `shipment_ts` AS `shipment_ts` - INTERVAL '1' SECOND" }; static final String[] SHIPMENTS_PROC_TIME_SCHEMA = { "id INT", "order_id INT", "shipment_ts_str STRING", "`proc_time` AS PROCTIME()" }; static final String[] SINK_SCHEMA = { "order_id INT", "order_ts_str STRING", "shipment_ts_str STRING" }; static final TableTestProgram INTERVAL_JOIN_EVENT_TIME = TableTestProgram.of( "interval-join-event-time", "validates interval join using event time") .setupTableSource( SourceTestStep.newBuilder("orders_t") .addSchema(ORDERS_EVENT_TIME_SCHEMA) .producedBeforeRestore(ORDER_BEFORE_DATA) .producedAfterRestore(ORDER_AFTER_DATA) .build()) .setupTableSource( SourceTestStep.newBuilder("shipments_t") .addSchema(SHIPMENTS_EVENT_TIME_SCHEMA) .producedBeforeRestore(SHIPMENT_BEFORE_DATA) .producedAfterRestore(SHIPMENT_AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema(SINK_SCHEMA) .consumedBeforeRestore( "+I[1, 2020-04-15 08:00:01, 2020-04-15 08:00:02]", "+I[2, 2020-04-15 08:00:02, 2020-04-15 08:00:05]", "+I[5, 2020-04-15 08:00:05, 2020-04-15 08:00:06]") .consumedAfterRestore( "+I[10, 2020-04-15 08:00:11, 2020-04-15 08:00:16]") .build()) .runSql( "INSERT INTO sink_t SELECT\n" + " o.id AS order_id,\n" + " o.order_ts_str,\n" + " s.shipment_ts_str\n" + " FROM orders_t o\n" + " JOIN shipments_t s ON o.id = s.order_id\n" + " WHERE o.order_ts BETWEEN s.shipment_ts - INTERVAL '5' SECOND AND s.shipment_ts + INTERVAL '5' SECOND;") .build(); static final TableTestProgram INTERVAL_JOIN_PROC_TIME = TableTestProgram.of( "interval-join-proc-time", "validates interval join using processing time") .setupTableSource( SourceTestStep.newBuilder("orders_t") .addSchema(ORDERS_PROC_TIME_SCHEMA) .producedBeforeRestore(ORDER_BEFORE_DATA) .producedAfterRestore(ORDER_AFTER_DATA) .build()) .setupTableSource( SourceTestStep.newBuilder("shipments_t") .addSchema(SHIPMENTS_PROC_TIME_SCHEMA) .producedBeforeRestore(SHIPMENT_BEFORE_DATA) .producedAfterRestore(SHIPMENT_AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema(SINK_SCHEMA) .consumedBeforeRestore( "+I[1, 2020-04-15 08:00:01, 2020-04-15 08:00:02]", "+I[2, 2020-04-15 08:00:02, 2020-04-15 08:00:05]", "+I[5, 2020-04-15 08:00:05, 2020-04-15 08:00:06]", "+I[4, 2020-04-15 08:00:04, 2020-04-15 08:00:15]") .consumedAfterRestore( "+I[7, 2020-04-15 08:00:09, 2020-04-15 08:00:16]", "+I[10, 2020-04-15 08:00:11, 2020-04-15 08:00:16]") .build()) .runSql( "INSERT INTO sink_t SELECT\n" + " o.id AS order_id,\n" + " o.order_ts_str,\n" + " s.shipment_ts_str\n" + " FROM orders_t o\n" + " JOIN shipments_t s ON o.id = s.order_id\n" + " WHERE o.proc_time BETWEEN s.proc_time - INTERVAL '5' SECOND AND s.proc_time + INTERVAL '5' SECOND;") .build(); static final TableTestProgram INTERVAL_JOIN_NEGATIVE_INTERVAL = TableTestProgram.of( "interval-join-negative-interval", "validates interval join using event time") .setupTableSource( SourceTestStep.newBuilder("orders_t") .addSchema(ORDERS_EVENT_TIME_SCHEMA) .producedBeforeRestore(ORDER_BEFORE_DATA) .producedAfterRestore(ORDER_AFTER_DATA) .build()) .setupTableSource( SourceTestStep.newBuilder("shipments_t") .addSchema(SHIPMENTS_EVENT_TIME_SCHEMA) .producedBeforeRestore(SHIPMENT_BEFORE_DATA) .producedAfterRestore(SHIPMENT_AFTER_DATA) .build()) .setupTableSink( SinkTestStep.newBuilder("sink_t") .addSchema(SINK_SCHEMA) .consumedBeforeRestore( "+I[1, 2020-04-15 08:00:01, null]", "+I[2, 2020-04-15 08:00:02, null]", "+I[4, 2020-04-15 08:00:04, null]", "+I[5, 2020-04-15 08:00:05, null]", "+I[3, 2020-04-15 08:00:03, null]") .consumedAfterRestore( "+I[7, 2020-04-15 08:00:09, null]", "+I[10, 2020-04-15 08:00:11, null]") .build()) .runSql( "INSERT INTO sink_t SELECT\n" + " o.id AS order_id,\n" + " o.order_ts_str,\n" + " s.shipment_ts_str\n" + " FROM orders_t o LEFT OUTER JOIN shipments_t s\n" + " ON o.id = s.order_id\n" + " AND o.order_ts BETWEEN s.shipment_ts + INTERVAL '10' SECOND AND s.shipment_ts + INTERVAL '5' SECOND;") .build(); }
IntervalJoinTestPrograms
java
jhy__jsoup
src/main/java/org/jsoup/Connection.java
{ "start": 42645, "end": 44411 }
interface ____ { /** * Update the key of a keyval * @param key new key * @return this KeyVal, for chaining */ KeyVal key(String key); /** * Get the key of a keyval * @return the key */ String key(); /** * Update the value of a keyval * @param value the new value * @return this KeyVal, for chaining */ KeyVal value(String value); /** * Get the value of a keyval * @return the value */ String value(); /** * Add or update an input stream to this keyVal * @param inputStream new input stream * @return this KeyVal, for chaining */ KeyVal inputStream(InputStream inputStream); /** * Get the input stream associated with this keyval, if any * @return input stream if set, or null */ @Nullable InputStream inputStream(); /** * Does this keyval have an input stream? * @return true if this keyval does indeed have an input stream */ boolean hasInputStream(); /** * Set the Content Type header used in the MIME body (aka mimetype) when uploading files. * Only useful if {@link #inputStream(InputStream)} is set. * <p>Will default to {@code application/octet-stream}.</p> * @param contentType the new content type * @return this KeyVal */ KeyVal contentType(String contentType); /** * Get the current Content Type, or {@code null} if not set. * @return the current Content Type. */ @Nullable String contentType(); } }
KeyVal
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/EnumSerializationTestUtils.java
{ "start": 877, "end": 1404 }
enum ____'s ordinal on the wire. * Reordering the values in an enum, or adding a new value, will change the ordinals and is therefore a wire protocol change, but it's easy * to miss this fact in the context of a larger commit. To protect against this trap, any enums that we send over the wire should have a * test that uses {@link #assertEnumSerialization} to assert a fixed mapping between ordinals and values. That way, a change to the ordinals * will require a test change, and thus some thought about BwC. */ public
value
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java
{ "start": 2034, "end": 4207 }
class ____ implements Filter, Filter.Listener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompatibleFilter.class); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { if (!invocation.getMethodName().startsWith("$") && !appResponse.hasException()) { Object value = appResponse.getValue(); if (value != null) { try { Method method = invoker.getInterface() .getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class<?> type = method.getReturnType(); Object newValue; String serialization = UrlUtils.serializationOrDefault(invoker.getUrl()); if ("json".equals(serialization) || "fastjson".equals(serialization)) { // If the serialization key is json or fastjson Type gtype = method.getGenericReturnType(); newValue = PojoUtils.realize(value, type, gtype); } else if (!type.isInstance(value)) { // if local service interface's method's return type is not instance of return value newValue = PojoUtils.isPojo(type) ? PojoUtils.realize(value, type) : CompatibleTypeUtils.compatibleTypeConvert(value, type); } else { newValue = value; } if (newValue != value) { appResponse.setValue(newValue); } } catch (Throwable t) { logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", t.getMessage(), t); } } } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} }
CompatibleFilter
java
apache__camel
components/camel-azure/camel-azure-storage-queue/src/test/java/org/apache/camel/component/azure/storage/queue/QueueConfigurationOptionsProxyTest.java
{ "start": 1154, "end": 2337 }
class ____ extends CamelTestSupport { @Test public void testIfCorrectOptionsReturnedCorrectly() { final QueueConfiguration configuration = new QueueConfiguration(); // first case: when exchange is set final Exchange exchange = new DefaultExchange(context); final QueueConfigurationOptionsProxy configurationOptionsProxy = new QueueConfigurationOptionsProxy(configuration); exchange.getIn().setHeader(QueueConstants.QUEUE_NAME, "testQueueExchange"); configuration.setQueueName("testQueueConfig"); assertEquals("testQueueExchange", configurationOptionsProxy.getQueueName(exchange)); // second class: exchange is empty exchange.getIn().setHeader(QueueConstants.QUEUE_NAME, null); assertEquals("testQueueConfig", configurationOptionsProxy.getQueueName(exchange)); // third class: if exchange is null assertEquals("testQueueConfig", configurationOptionsProxy.getQueueName(null)); // fourth class: if no option at all configuration.setQueueName(null); assertNull(configurationOptionsProxy.getQueueName(exchange)); } }
QueueConfigurationOptionsProxyTest
java
elastic__elasticsearch
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java
{ "start": 4767, "end": 38103 }
class ____ not be instantiated"); } /** * Creates a {@link PrivateKey} from the contents of a file and handles any exceptions * * @param path the path for the key file * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return a private key from the contents of the file */ public static PrivateKey readPrivateKey(Path path, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { try { final PrivateKey privateKey = PemUtils.parsePrivateKey(path, passwordSupplier); if (privateKey == null) { throw new SslConfigException("could not load ssl private key file [" + path + "]"); } return privateKey; } catch (SecurityException e) { throw SslFileUtil.accessControlFailure("PEM private key", List.of(path), e, null); } catch (IOException e) { throw SslFileUtil.ioException("PEM private key", List.of(path), e); } catch (GeneralSecurityException e) { throw SslFileUtil.securityException("PEM private key", List.of(path), e); } } /** * Creates a {@link PrivateKey} from the contents of a file. Supports PKCS#1, PKCS#8 * encoded formats of encrypted and plaintext RSA, DSA and EC(secp256r1) keys * * @param keyPath the path for the key file * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return a private key from the contents of the file */ static PrivateKey parsePrivateKey(Path keyPath, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { try (BufferedReader bReader = Files.newBufferedReader(keyPath, StandardCharsets.UTF_8)) { String line = bReader.readLine(); while (null != line && line.startsWith(HEADER) == false) { line = bReader.readLine(); } if (null == line) { throw new SslConfigException("Error parsing Private Key [" + keyPath.toAbsolutePath() + "], file is empty"); } if (PKCS8_ENCRYPTED_HEADER.equals(line.trim())) { char[] password = passwordSupplier.get(); if (password == null) { throw new SslConfigException("cannot read encrypted key [" + keyPath.toAbsolutePath() + "] without a password"); } return parsePKCS8Encrypted(bReader, password); } else if (PKCS8_HEADER.equals(line.trim())) { return parsePKCS8(bReader); } else if (PKCS1_HEADER.equals(line.trim())) { return parsePKCS1Rsa(bReader, passwordSupplier); } else if (OPENSSL_DSA_HEADER.equals(line.trim())) { return parseOpenSslDsa(bReader, passwordSupplier); } else if (OPENSSL_DSA_PARAMS_HEADER.equals(line.trim())) { return parseOpenSslDsa(removeDsaHeaders(bReader), passwordSupplier); } else if (OPENSSL_EC_HEADER.equals(line.trim())) { return parseOpenSslEC(bReader, passwordSupplier); } else if (OPENSSL_EC_PARAMS_HEADER.equals(line.trim())) { return parseOpenSslEC(removeECHeaders(bReader), passwordSupplier); } else { throw new SslConfigException( "cannot read PEM private key [" + keyPath.toAbsolutePath() + "] because the file does not contain a supported key format" ); } } } /** * Removes the EC Headers that OpenSSL adds to EC private keys as the information in them * is redundant * * @throws IOException if the EC Parameter footer is missing */ private static BufferedReader removeECHeaders(BufferedReader bReader) throws IOException { String line = bReader.readLine(); while (line != null) { if (OPENSSL_EC_PARAMS_FOOTER.equals(line.trim())) { break; } line = bReader.readLine(); } if (null == line || OPENSSL_EC_PARAMS_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, EC Parameters footer is missing"); } // Verify that the key starts with the correct header before passing it to parseOpenSslEC if (OPENSSL_EC_HEADER.equals(bReader.readLine()) == false) { throw new IOException("Malformed PEM file, EC Key header is missing"); } return bReader; } /** * Removes the DSA Params Headers that OpenSSL adds to DSA private keys as the information in them * is redundant * * @throws IOException if the EC Parameter footer is missing */ private static BufferedReader removeDsaHeaders(BufferedReader bReader) throws IOException { String line = bReader.readLine(); while (line != null) { if (OPENSSL_DSA_PARAMS_FOOTER.equals(line.trim())) { break; } line = bReader.readLine(); } if (null == line || OPENSSL_DSA_PARAMS_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, DSA Parameters footer is missing"); } // Verify that the key starts with the correct header before passing it to parseOpenSslDsa if (OPENSSL_DSA_HEADER.equals(bReader.readLine()) == false) { throw new IOException("Malformed PEM file, DSA Key header is missing"); } return bReader; } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an plaintext private key encoded in * PKCS#8 * * @param bReader the {@link BufferedReader} containing the key file contents * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link PKCS8EncodedKeySpec} */ private static PrivateKey parsePKCS8(BufferedReader bReader) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); while (line != null) { if (PKCS8_FOOTER.equals(line.trim())) { break; } sb.append(line.trim()); line = bReader.readLine(); } if (null == line || PKCS8_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } return parsePKCS8PemString(sb.toString()); } /** * Creates a {@link PrivateKey} from a String that contains the PEM encoded representation of a plaintext private key encoded in PKCS8 * @param pemString the PEM encoded representation of a plaintext private key encoded in PKCS8 * @return {@link PrivateKey} * @throws IOException if the algorithm identifier can not be parsed from DER * @throws GeneralSecurityException if the private key can't be generated from the {@link PKCS8EncodedKeySpec} */ public static PrivateKey parsePKCS8PemString(String pemString) throws IOException, GeneralSecurityException { byte[] keyBytes = Base64.getDecoder().decode(pemString); String keyAlgo = getKeyAlgorithmIdentifier(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an EC private key encoded in * OpenSSL traditional format. * * @param bReader the {@link BufferedReader} containing the key file contents * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link ECPrivateKeySpec} */ private static PrivateKey parseOpenSslEC(BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (OPENSSL_EC_FOOTER.equals(line.trim())) { break; } // Parse PEM headers according to https://www.ietf.org/rfc/rfc1421.txt if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line || OPENSSL_EC_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); KeyFactory keyFactory = KeyFactory.getInstance("EC"); ECPrivateKeySpec ecSpec = parseEcDer(keyBytes); return keyFactory.generatePrivate(ecSpec); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an RSA private key encoded in * OpenSSL traditional format. * * @param bReader the {@link BufferedReader} containing the key file contents * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link RSAPrivateCrtKeySpec} */ private static PrivateKey parsePKCS1Rsa(BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (PKCS1_FOOTER.equals(line.trim())) { // Unencrypted break; } // Parse PEM headers according to https://www.ietf.org/rfc/rfc1421.txt if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line || PKCS1_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); RSAPrivateCrtKeySpec spec = parseRsaDer(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(spec); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an DSA private key encoded in * OpenSSL traditional format. * * @param bReader the {@link BufferedReader} containing the key file contents * @param passwordSupplier A password supplier for the potentially encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link DSAPrivateKeySpec} */ private static PrivateKey parseOpenSslDsa(BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (OPENSSL_DSA_FOOTER.equals(line.trim())) { // Unencrypted break; } // Parse PEM headers according to https://www.ietf.org/rfc/rfc1421.txt if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line || OPENSSL_DSA_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); DSAPrivateKeySpec spec = parseDsaDer(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePrivate(spec); } /** * Creates a {@link PrivateKey} from the contents of {@code bReader} that contains an encrypted private key encoded in * PKCS#8 * * @param bReader the {@link BufferedReader} containing the key file contents * @param keyPassword The password for the encrypted (password protected) key * @return {@link PrivateKey} * @throws IOException if the file can't be read * @throws GeneralSecurityException if the private key can't be generated from the {@link PKCS8EncodedKeySpec} */ private static PrivateKey parsePKCS8Encrypted(BufferedReader bReader, char[] keyPassword) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); while (line != null) { if (PKCS8_ENCRYPTED_FOOTER.equals(line.trim())) { break; } sb.append(line.trim()); line = bReader.readLine(); } if (null == line || PKCS8_ENCRYPTED_FOOTER.equals(line.trim()) == false) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = Base64.getDecoder().decode(sb.toString()); final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = getEncryptedPrivateKeyInfo(keyBytes); String algorithm = encryptedPrivateKeyInfo.getAlgName(); if (algorithm.equals("PBES2") || algorithm.equals("1.2.840.113549.1.5.13")) { algorithm = getPBES2Algorithm(encryptedPrivateKeyInfo); } SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); SecretKey secretKey = secretKeyFactory.generateSecret(new PBEKeySpec(keyPassword)); Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters()); PKCS8EncodedKeySpec keySpec = encryptedPrivateKeyInfo.getKeySpec(cipher); String keyAlgo = getKeyAlgorithmIdentifier(keySpec.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo); return keyFactory.generatePrivate(keySpec); } private static EncryptedPrivateKeyInfo getEncryptedPrivateKeyInfo(byte[] keyBytes) throws IOException, GeneralSecurityException { try { return new EncryptedPrivateKeyInfo(keyBytes); } catch (IOException e) { // The Sun JCE provider can't handle non-AES PBES2 data (but it can handle PBES1 DES data - go figure) // It's not worth our effort to try and decrypt it ourselves, but we can detect it and give a good error message DerParser parser = new DerParser(keyBytes); final DerParser.Asn1Object rootSeq = parser.readAsn1Object(DerParser.Type.SEQUENCE); parser = rootSeq.getParser(); final DerParser.Asn1Object algSeq = parser.readAsn1Object(DerParser.Type.SEQUENCE); parser = algSeq.getParser(); final String algId = parser.readAsn1Object(DerParser.Type.OBJECT_OID).getOid(); if (PBES2_OID.equals(algId)) { final DerParser.Asn1Object algData = parser.readAsn1Object(DerParser.Type.SEQUENCE); parser = algData.getParser(); final DerParser.Asn1Object ignoreKdf = parser.readAsn1Object(DerParser.Type.SEQUENCE); final DerParser.Asn1Object cryptSeq = parser.readAsn1Object(DerParser.Type.SEQUENCE); parser = cryptSeq.getParser(); final String encryptionId = parser.readAsn1Object(DerParser.Type.OBJECT_OID).getOid(); if (encryptionId.startsWith(AES_OID) == false) { final String name = getAlgorithmNameFromOid(encryptionId); throw new GeneralSecurityException( "PKCS#8 Private Key is encrypted with unsupported PBES2 algorithm [" + encryptionId + "]" + (name == null ? "" : " (" + name + ")"), e ); } } throw e; } } /** * This is horrible, but it's the only option other than to parse the encoded ASN.1 value ourselves * @see AlgorithmParameters#toString() and com.sun.crypto.provider.PBES2Parameters#toString() */ private static String getPBES2Algorithm(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) { final AlgorithmParameters algParameters = encryptedPrivateKeyInfo.getAlgParameters(); if (algParameters != null) { return algParameters.toString(); } else { // AlgorithmParameters can be null when running on BCFIPS. // However, since BCFIPS doesn't support any PBE specs, nothing we do here would work, so we just do enough to avoid an NPE return encryptedPrivateKeyInfo.getAlgName(); } } /** * Decrypts the password protected contents using the algorithm and IV that is specified in the PEM Headers of the file * * @param pemHeaders The Proc-Type and DEK-Info PEM headers that have been extracted from the key file * @param keyContents The key as a base64 encoded String * @param passwordSupplier A password supplier for the encrypted (password protected) key * @return the decrypted key bytes * @throws GeneralSecurityException if the key can't be decrypted * @throws IOException if the PEM headers are missing or malformed */ private static byte[] possiblyDecryptPKCS1Key(Map<String, String> pemHeaders, String keyContents, Supplier<char[]> passwordSupplier) throws GeneralSecurityException, IOException { byte[] keyBytes = Base64.getDecoder().decode(keyContents); String procType = pemHeaders.get("Proc-Type"); if ("4,ENCRYPTED".equals(procType)) { // We only handle PEM encryption String encryptionParameters = pemHeaders.get("DEK-Info"); if (null == encryptionParameters) { // malformed pem throw new IOException("Malformed PEM File, DEK-Info header is missing"); } char[] password = passwordSupplier.get(); if (password == null) { throw new IOException("cannot read encrypted key without a password"); } Cipher cipher = getCipherFromParameters(encryptionParameters, password); byte[] decryptedKeyBytes = cipher.doFinal(keyBytes); return decryptedKeyBytes; } return keyBytes; } /** * Creates a {@link Cipher} from the contents of the DEK-Info header of a PEM file. RFC 1421 indicates that supported algorithms are * defined in RFC 1423. RFC 1423 only defines DES-CBS and triple DES (EDE) in CBC mode. AES in CBC mode is also widely used though ( 3 * different variants of 128, 192, 256 bit keys ) * * @param dekHeaderValue The value of the DEK-Info PEM header * @param password The password with which the key is encrypted * @return a cipher of the appropriate algorithm and parameters to be used for decryption * @throws GeneralSecurityException if the algorithm is not available in the used security provider, or if the key is inappropriate * for the cipher * @throws IOException if the DEK-Info PEM header is invalid */ private static Cipher getCipherFromParameters(String dekHeaderValue, char[] password) throws GeneralSecurityException, IOException { final String padding = "PKCS5Padding"; final SecretKey encryptionKey; final String[] valueTokens = dekHeaderValue.split(","); if (valueTokens.length != 2) { throw new IOException("Malformed PEM file, DEK-Info PEM header is invalid"); } final String algorithm = valueTokens[0]; final String ivString = valueTokens[1]; final byte[] iv; try { iv = hexStringToByteArray(ivString); } catch (IllegalArgumentException e) { throw new IOException("Malformed PEM file, DEK-Info IV is invalid", e); } if ("DES-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 8); encryptionKey = new SecretKeySpec(key, DEPRECATED_DES_ALGORITHM); } else if ("DES-EDE3-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 24); encryptionKey = new SecretKeySpec(key, DEPRECATED_DES_EDE_ALGORITHM); } else if ("AES-128-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 16); encryptionKey = new SecretKeySpec(key, "AES"); } else if ("AES-192-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 24); encryptionKey = new SecretKeySpec(key, "AES"); } else if ("AES-256-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 32); encryptionKey = new SecretKeySpec(key, "AES"); } else { throw new GeneralSecurityException("Private Key encrypted with unsupported algorithm [" + algorithm + "]"); } String transformation = encryptionKey.getAlgorithm() + "/" + "CBC" + "/" + padding; Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); return cipher; } /** * Performs key stretching in the same manner that OpenSSL does. This is basically a KDF * that uses n rounds of salted MD5 (as many times as needed to get the necessary number of key bytes) * <p> * https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_PrivateKey_traditional.html */ private static byte[] generateOpenSslKey(char[] password, byte[] salt, int keyLength) { byte[] passwordBytes = CharArrays.toUtf8Bytes(password); MessageDigest md5 = SslUtil.messageDigest("md5"); byte[] key = new byte[keyLength]; int copied = 0; int remaining; while (copied < keyLength) { remaining = keyLength - copied; md5.update(passwordBytes, 0, passwordBytes.length); md5.update(salt, 0, 8);// AES IV (salt) is longer but we only need 8 bytes byte[] tempDigest = md5.digest(); int bytesToCopy = (remaining > 16) ? 16 : remaining; // MD5 digests are 16 bytes System.arraycopy(tempDigest, 0, key, copied, bytesToCopy); copied += bytesToCopy; if (remaining == 0) { break; } md5.update(tempDigest, 0, 16); // use previous round digest as IV } Arrays.fill(passwordBytes, (byte) 0); return key; } /** * Converts a hexadecimal string to a byte array */ private static byte[] hexStringToByteArray(String hexString) { int len = hexString.length(); if (len % 2 == 0) { byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { final int k = Character.digit(hexString.charAt(i), 16); final int l = Character.digit(hexString.charAt(i + 1), 16); if (k == -1 || l == -1) { throw new IllegalStateException("String [" + hexString + "] is not hexadecimal"); } data[i / 2] = (byte) ((k << 4) + l); } return data; } else { throw new IllegalStateException( "Hexadecimal string [" + hexString + "] has odd length and cannot be converted to a byte array" ); } } /** * Parses a DER encoded EC key to an {@link ECPrivateKeySpec} using a minimal {@link DerParser} * * @param keyBytes the private key raw bytes * @return {@link ECPrivateKeySpec} * @throws IOException if the DER encoded key can't be parsed */ private static ECPrivateKeySpec parseEcDer(byte[] keyBytes) throws IOException, GeneralSecurityException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // version String keyHex = parser.readAsn1Object().getString(); BigInteger privateKeyInt = new BigInteger(keyHex, 16); DerParser.Asn1Object choice = parser.readAsn1Object(); parser = choice.getParser(); String namedCurve = getEcCurveNameFromOid(parser.readAsn1Object().getOid()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); AlgorithmParameterSpec algorithmParameterSpec = new ECGenParameterSpec(namedCurve); keyPairGenerator.initialize(algorithmParameterSpec); ECParameterSpec parameterSpec = ((ECKey) keyPairGenerator.generateKeyPair().getPrivate()).getParams(); return new ECPrivateKeySpec(privateKeyInt, parameterSpec); } /** * Parses a DER encoded RSA key to a {@link RSAPrivateCrtKeySpec} using a minimal {@link DerParser} * * @param keyBytes the private key raw bytes * @return {@link RSAPrivateCrtKeySpec} * @throws IOException if the DER encoded key can't be parsed */ private static RSAPrivateCrtKeySpec parseRsaDer(byte[] keyBytes) throws IOException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // (version) We don't need it but must read to get to modulus BigInteger modulus = parser.readAsn1Object().getInteger(); BigInteger publicExponent = parser.readAsn1Object().getInteger(); BigInteger privateExponent = parser.readAsn1Object().getInteger(); BigInteger prime1 = parser.readAsn1Object().getInteger(); BigInteger prime2 = parser.readAsn1Object().getInteger(); BigInteger exponent1 = parser.readAsn1Object().getInteger(); BigInteger exponent2 = parser.readAsn1Object().getInteger(); BigInteger coefficient = parser.readAsn1Object().getInteger(); return new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, prime1, prime2, exponent1, exponent2, coefficient); } /** * Parses a DER encoded DSA key to a {@link DSAPrivateKeySpec} using a minimal {@link DerParser} * * @param keyBytes the private key raw bytes * @return {@link DSAPrivateKeySpec} * @throws IOException if the DER encoded key can't be parsed */ private static DSAPrivateKeySpec parseDsaDer(byte[] keyBytes) throws IOException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // (version) We don't need it but must read to get to p BigInteger p = parser.readAsn1Object().getInteger(); BigInteger q = parser.readAsn1Object().getInteger(); BigInteger g = parser.readAsn1Object().getInteger(); parser.readAsn1Object().getInteger(); // we don't need x BigInteger x = parser.readAsn1Object().getInteger(); return new DSAPrivateKeySpec(x, p, q, g); } /** * Parses a DER encoded private key and reads its algorithm identifier Object OID. * * @param keyBytes the private key raw bytes * @return A string identifier for the key algorithm (RSA, DSA, or EC) * @throws GeneralSecurityException if the algorithm oid that is parsed from ASN.1 is unknown * @throws IOException if the DER encoded key can't be parsed */ private static String getKeyAlgorithmIdentifier(byte[] keyBytes) throws IOException, GeneralSecurityException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); // version DerParser.Asn1Object algSequence = parser.readAsn1Object(); parser = algSequence.getParser(); String oidString = parser.readAsn1Object().getOid(); return switch (oidString) { case "1.2.840.10040.4.1" -> "DSA"; case "1.2.840.113549.1.1.1" -> "RSA"; case "1.2.840.10045.2.1" -> "EC"; default -> throw new GeneralSecurityException( "Error parsing key algorithm identifier. Algorithm with OID [" + oidString + "] is not supported" ); }; } public static List<Certificate> readCertificates(Collection<Path> certPaths) throws CertificateException, IOException { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); List<Certificate> certificates = new ArrayList<>(certPaths.size()); for (Path path : certPaths) { try (InputStream input = Files.newInputStream(path)) { final Collection<? extends Certificate> parsed = certFactory.generateCertificates(input); if (parsed.isEmpty()) { throw new SslConfigException("failed to parse any certificates from [" + path.toAbsolutePath() + "]"); } certificates.addAll(parsed); } } return certificates; } private static String getAlgorithmNameFromOid(String oidString) throws GeneralSecurityException { return switch (oidString) { case "1.2.840.10040.4.1" -> "DSA"; case "1.2.840.113549.1.1.1" -> "RSA"; case "1.2.840.10045.2.1" -> "EC"; case "1.3.14.3.2.7" -> "DES-CBC"; case "2.16.840.1.101.3.4.1.1" -> "AES-128_ECB"; case "2.16.840.1.101.3.4.1.2" -> "AES-128_CBC"; case "2.16.840.1.101.3.4.1.3" -> "AES-128_OFB"; case "2.16.840.1.101.3.4.1.4" -> "AES-128_CFB"; case "2.16.840.1.101.3.4.1.6" -> "AES-128_GCM"; case "2.16.840.1.101.3.4.1.21" -> "AES-192_ECB"; case "2.16.840.1.101.3.4.1.22" -> "AES-192_CBC"; case "2.16.840.1.101.3.4.1.23" -> "AES-192_OFB"; case "2.16.840.1.101.3.4.1.24" -> "AES-192_CFB"; case "2.16.840.1.101.3.4.1.26" -> "AES-192_GCM"; case "2.16.840.1.101.3.4.1.41" -> "AES-256_ECB"; case "2.16.840.1.101.3.4.1.42" -> "AES-256_CBC"; case "2.16.840.1.101.3.4.1.43" -> "AES-256_OFB"; case "2.16.840.1.101.3.4.1.44" -> "AES-256_CFB"; case "2.16.840.1.101.3.4.1.46" -> "AES-256_GCM"; case "2.16.840.1.101.3.4.1.5" -> "AESWrap-128"; case "2.16.840.1.101.3.4.1.25" -> "AESWrap-192"; case "2.16.840.1.101.3.4.1.45" -> "AESWrap-256"; default -> null; }; } private static String getEcCurveNameFromOid(String oidString) throws GeneralSecurityException { return switch (oidString) { // see https://tools.ietf.org/html/rfc5480#section-2.1.1.1 case "1.2.840.10045.3.1" -> "secp192r1"; case "1.3.132.0.1" -> "sect163k1"; case "1.3.132.0.15" -> "sect163r2"; case "1.3.132.0.33" -> "secp224r1"; case "1.3.132.0.26" -> "sect233k1"; case "1.3.132.0.27" -> "sect233r1"; case "1.2.840.10045.3.1.7" -> "secp256r1"; case "1.3.132.0.16" -> "sect283k1"; case "1.3.132.0.17" -> "sect283r1"; case "1.3.132.0.34" -> "secp384r1"; case "1.3.132.0.36" -> "sect409k1"; case "1.3.132.0.37" -> "sect409r1"; case "1.3.132.0.35" -> "secp521r1"; case "1.3.132.0.38" -> "sect571k1"; case "1.3.132.0.39" -> "sect571r1"; default -> throw new GeneralSecurityException( "Error parsing EC named curve identifier. Named curve with OID: " + oidString + " is not supported" ); }; } }
should
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/src/AbstractFileSource.java
{ "start": 10706, "end": 14734 }
class ____< T, SplitT extends FileSourceSplit, SELF extends AbstractFileSourceBuilder<T, SplitT, SELF>> { // mandatory - have no defaults protected final Path[] inputPaths; protected final BulkFormat<T, SplitT> readerFormat; // optional - have defaults protected FileEnumerator.Provider fileEnumerator; protected FileSplitAssigner.Provider splitAssigner; @Nullable protected ContinuousEnumerationSettings continuousSourceSettings; protected AbstractFileSourceBuilder( final Path[] inputPaths, final BulkFormat<T, SplitT> readerFormat, final FileEnumerator.Provider defaultFileEnumerator, final FileSplitAssigner.Provider defaultSplitAssigner) { this.inputPaths = checkNotNull(inputPaths); this.readerFormat = checkNotNull(readerFormat); this.fileEnumerator = defaultFileEnumerator; this.splitAssigner = defaultSplitAssigner; } /** Creates the file source with the settings applied to this builder. */ public abstract AbstractFileSource<T, SplitT> build(); /** * Sets this source to streaming ("continuous monitoring") mode. * * <p>This makes the source a "continuous streaming" source that keeps running, monitoring * for new files, and reads these files when they appear and are discovered by the * monitoring. * * <p>The interval in which the source checks for new files is the {@code * discoveryInterval}. Shorter intervals mean that files are discovered more quickly, but * also imply more frequent listing or directory traversal of the file system / object * store. */ public SELF monitorContinuously(Duration discoveryInterval) { checkNotNull(discoveryInterval, "discoveryInterval"); checkArgument( !(discoveryInterval.isNegative() || discoveryInterval.isZero()), "discoveryInterval must be > 0"); this.continuousSourceSettings = new ContinuousEnumerationSettings(discoveryInterval); return self(); } /** * Sets this source to bounded (batch) mode. * * <p>In this mode, the source processes the files that are under the given paths when the * application is started. Once all files are processed, the source will finish. * * <p>This setting is also the default behavior. This method is mainly here to "switch back" * to bounded (batch) mode, or to make it explicit in the source construction. */ public SELF processStaticFileSet() { this.continuousSourceSettings = null; return self(); } /** * Configures the {@link FileEnumerator} for the source. The File Enumerator is responsible * for selecting from the input path the set of files that should be processed (and which to * filter out). Furthermore, the File Enumerator may split the files further into * sub-regions, to enable parallelization beyond the number of files. */ public SELF setFileEnumerator(FileEnumerator.Provider fileEnumerator) { this.fileEnumerator = checkNotNull(fileEnumerator); return self(); } /** * Configures the {@link FileSplitAssigner} for the source. The File Split Assigner * determines which parallel reader instance gets which {@link FileSourceSplit}, and in * which order these splits are assigned. */ public SELF setSplitAssigner(FileSplitAssigner.Provider splitAssigner) { this.splitAssigner = checkNotNull(splitAssigner); return self(); } @SuppressWarnings("unchecked") private SELF self() { return (SELF) this; } } }
AbstractFileSourceBuilder
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/JettyHttp12EndpointBuilderFactory.java
{ "start": 55924, "end": 57059 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final JettyHttp12HeaderNameBuilder INSTANCE = new JettyHttp12HeaderNameBuilder(); /** * The servlet context path used. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code ServletContextPath}. */ public String servletContextPath() { return "CamelServletContextPath"; } /** * Request URI's path, the header will be used to build the request URI * with the HTTP_URI. * * The option is a: {@code String} type. * * Group: consumer * * @return the name of the header {@code HttpPath}. */ public String httpPath() { return "CamelHttpPath"; } } static JettyHttp12EndpointBuilder endpointBuilder(String componentName, String path) {
JettyHttp12HeaderNameBuilder
java
micronaut-projects__micronaut-core
management/src/main/java/io/micronaut/management/health/indicator/diskspace/DiskSpaceIndicator.java
{ "start": 1532, "end": 2869 }
class ____ extends AbstractHealthIndicator<Map<String, Object>> { protected static final String NAME = "diskSpace"; private final DiskSpaceIndicatorConfiguration configuration; /** * @param configuration The disk space indicator configuration */ DiskSpaceIndicator(DiskSpaceIndicatorConfiguration configuration) { this.configuration = configuration; } @Override public String getName() { return NAME; } @SuppressWarnings("MagicNumber") @Override protected Map<String, Object> getHealthInformation() { File path = configuration.getPath(); long threshold = configuration.getThreshold(); long freeSpace = path.getUsableSpace(); Map<String, Object> detail = new LinkedHashMap<>(3); if (freeSpace >= threshold) { healthStatus = HealthStatus.UP; detail.put("total", path.getTotalSpace()); detail.put("free", freeSpace); detail.put("threshold", threshold); } else { healthStatus = HealthStatus.DOWN; detail.put("error", ( "Free disk space below threshold. " + "Available: %d bytes (threshold: %d bytes)").formatted( freeSpace, threshold)); } return detail; } }
DiskSpaceIndicator
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthentication.java
{ "start": 2808, "end": 4582 }
class ____<B extends Builder<B>> extends AbstractOAuth2TokenAuthenticationBuilder<OAuth2AccessToken, B> { private Map<String, Object> attributes; protected Builder(BearerTokenAuthentication token) { super(token); this.attributes = token.getTokenAttributes(); } /** * Use this principal. Must be of type {@link OAuth2AuthenticatedPrincipal} * @param principal the principal to use * @return the {@link Builder} for further configurations */ @Override public B principal(@Nullable Object principal) { Assert.isInstanceOf(OAuth2AuthenticatedPrincipal.class, principal, "principal must be of type OAuth2AuthenticatedPrincipal"); this.attributes = ((OAuth2AuthenticatedPrincipal) principal).getAttributes(); return super.principal(principal); } /** * A synonym for {@link #token(OAuth2AccessToken)} * @param token the token to use * @return the {@link Builder} for further configurations */ @Override public B credentials(@Nullable Object token) { Assert.isInstanceOf(OAuth2AccessToken.class, token, "token must be of type OAuth2AccessToken"); return token((OAuth2AccessToken) token); } /** * Use this token. Must have a {@link OAuth2AccessToken#getTokenType()} as * {@link OAuth2AccessToken.TokenType#BEARER}. * @param token the token to use * @return the {@link Builder} for further configurations */ @Override public B token(OAuth2AccessToken token) { Assert.isTrue(token.getTokenType() == OAuth2AccessToken.TokenType.BEARER, "token must be a bearer token"); super.credentials(token); return super.token(token); } /** * {@inheritDoc} */ @Override public BearerTokenAuthentication build() { return new BearerTokenAuthentication(this); } } }
Builder
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesCapacitySched.java
{ "start": 4226, "end": 9543 }
class ____ extends AbstractBinder { @Override protected void configure() { Configuration conf = createConfig(); conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); conf.set(YarnConfiguration.RM_CLUSTER_ID, "subCluster1"); rm = createRM(conf); final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getScheme()).thenReturn("http"); final HttpServletResponse response = mock(HttpServletResponse.class); bind(rm).to(ResourceManager.class).named("rm"); bind(conf).to(Configuration.class).named("conf"); bind(request).to(HttpServletRequest.class); bind(response).to(HttpServletResponse.class); } } @BeforeEach @Override public void setUp() throws Exception { super.setUp(); } public void initTestRMWebServicesCapacitySched(boolean pLegacyQueueMode) { this.legacyQueueMode = pLegacyQueueMode; backupSchedulerConfigFileInTarget(); } @AfterAll public static void afterClass() { restoreSchedulerConfigFileInTarget(); } @MethodSource("getParameters") @ParameterizedTest(name = "{index}: legacy-queue-mode={0}") public void testClusterScheduler(boolean pLegacyQueueMode) throws Exception { initTestRMWebServicesCapacitySched(pLegacyQueueMode); rm.registerNode("h1:1234", 32 * GB, 32); assertJsonResponse(target().path("ws/v1/cluster/scheduler") .request(MediaType.APPLICATION_JSON).get(Response.class), "webapp/scheduler-response.json"); assertJsonResponse(target().path("ws/v1/cluster/scheduler/") .request(MediaType.APPLICATION_JSON).get(Response.class), "webapp/scheduler-response.json"); assertJsonResponse(target().path("ws/v1/cluster/scheduler") .request().get(Response.class), "webapp/scheduler-response.json"); assertXmlResponse(target().path("ws/v1/cluster/scheduler/") .request(MediaType.APPLICATION_XML).get(Response.class), "webapp/scheduler-response.xml"); } @MethodSource("getParameters") @ParameterizedTest(name = "{index}: legacy-queue-mode={0}") public void testPerUserResources(boolean pLegacyQueueMode) throws Exception { initTestRMWebServicesCapacitySched(pLegacyQueueMode); rm.registerNode("h1:1234", 32 * GB, 32); MockRMAppSubmitter.submit(rm, MockRMAppSubmissionData.Builder .createWithMemory(32, rm) .withAppName("app1") .withUser("user1") .withAcls(null) .withQueue("a") .withUnmanagedAM(false) .build() ); MockRMAppSubmitter.submit(rm, MockRMAppSubmissionData.Builder .createWithMemory(64, rm) .withAppName("app2") .withUser("user2") .withAcls(null) .withQueue("b") .withUnmanagedAM(false) .build() ); assertXmlResponse(target().path("ws/v1/cluster/scheduler") .request(MediaType.APPLICATION_XML).get(Response.class), "webapp/scheduler-response-PerUserResources.xml"); assertJsonResponse(target().path("ws/v1/cluster/scheduler") .request(MediaType.APPLICATION_JSON).get(Response.class), "webapp/scheduler-response-PerUserResources.json"); } @MethodSource("getParameters") @ParameterizedTest(name = "{index}: legacy-queue-mode={0}") public void testClusterSchedulerOverviewCapacity(boolean pLegacyQueueMode) throws Exception { initTestRMWebServicesCapacitySched(pLegacyQueueMode); rm.registerNode("h1:1234", 32 * GB, 32); Response response = targetWithJsonObject().path("ws/v1/cluster/scheduler-overview") .request(MediaType.APPLICATION_JSON).get(Response.class); assertJsonType(response); JSONObject json = response.readEntity(JSONObject.class); JSONObject scheduler = json.getJSONObject("scheduler"); TestRMWebServices.verifyClusterSchedulerOverView(scheduler, "Capacity Scheduler"); } @MethodSource("getParameters") @ParameterizedTest(name = "{index}: legacy-queue-mode={0}") public void testResourceInfo(boolean pLegacyQueueMode) { initTestRMWebServicesCapacitySched(pLegacyQueueMode); Resource res = Resources.createResource(10, 1); // If we add a new resource (e.g. disks), then // CapacitySchedulerPage and these RM WebServices + docs need to be updated // e.g. ResourceInfo assertEquals("<memory:10, vCores:1>", res.toString()); } private Configuration createConfig() { Configuration conf = new Configuration(); conf.set("yarn.scheduler.capacity.legacy-queue-mode.enabled", String.valueOf(legacyQueueMode)); conf.set("yarn.scheduler.capacity.root.queues", "a, b, c"); conf.set("yarn.scheduler.capacity.root.a.capacity", "12.5"); conf.set("yarn.scheduler.capacity.root.a.accessible-node-labels", "root-a-default-label"); conf.set("yarn.scheduler.capacity.root.a.maximum-capacity", "50"); conf.set("yarn.scheduler.capacity.root.a.max-parallel-app", "42"); conf.set("yarn.scheduler.capacity.root.b.capacity", "50"); conf.set("yarn.scheduler.capacity.root.c.capacity", "37.5"); conf.set("yarn.scheduler.capacity.schedule-asynchronously.enable", "false"); return conf; } }
JerseyBinder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/clusterframework/types/SlotID.java
{ "start": 1299, "end": 3164 }
class ____ implements ResourceIDRetrievable, Serializable { private static final long serialVersionUID = -6399206032549807771L; /** The resource id which this slot located */ private final ResourceID resourceId; /** The numeric id for single slot */ private final int slotNumber; public SlotID(ResourceID resourceId, int slotNumber) { checkArgument(0 <= slotNumber, "Slot number must be positive."); this.resourceId = checkNotNull(resourceId, "ResourceID must not be null"); this.slotNumber = slotNumber; } private SlotID(ResourceID resourceID) { this.resourceId = checkNotNull(resourceID, "ResourceID must not be null"); this.slotNumber = -1; } // ------------------------------------------------------------------------ @Override public ResourceID getResourceID() { return resourceId; } public int getSlotNumber() { return slotNumber; } // ------------------------------------------------------------------------ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SlotID slotID = (SlotID) o; return slotNumber == slotID.slotNumber && resourceId.equals(slotID.resourceId); } @Override public int hashCode() { int result = resourceId.hashCode(); result = 31 * result + slotNumber; return result; } @Override public String toString() { return resourceId + "_" + (slotNumber >= 0 ? slotNumber : "dynamic"); } /** Get a SlotID without actual slot index for dynamic slot allocation. */ public static SlotID getDynamicSlotID(ResourceID resourceID) { return new SlotID(resourceID); } }
SlotID
java
redisson__redisson
redisson/src/test/java/org/redisson/rx/RedissonListRxTest.java
{ "start": 404, "end": 16753 }
class ____ extends BaseRxTest { @Test public void testAddByIndex() { RListRx<String> test2 = redisson.getList("test2"); sync(test2.add("foo")); sync(test2.add(0, "bar")); assertThat(sync(test2)).containsExactly("bar", "foo"); } @Test public void testAddAllReactive() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); RListRx<Integer> list2 = redisson.getList("list2"); Assertions.assertEquals(true, sync(list2.addAll(list.iterator()))); Assertions.assertEquals(5, sync(list2.size()).intValue()); } @Test public void testAddAllWithIndex() throws InterruptedException { final RListRx<Long> list = redisson.getList("list"); final CountDownLatch latch = new CountDownLatch(1); list.addAll(Arrays.asList(1L, 2L, 3L)).subscribe((Boolean element, Throwable error) -> { if (error != null) { Assertions.fail(error.getMessage()); return; } list.addAll(Arrays.asList(1L, 24L, 3L)).subscribe((Boolean value, Throwable err) -> { if (err != null) { Assertions.fail(err.getMessage()); return; } latch.countDown(); }); }); latch.await(); assertThat(sync(list)).containsExactly(1L, 2L, 3L, 1L, 24L, 3L); } @Test public void testAdd() throws InterruptedException { final RListRx<Long> list = redisson.getList("list"); final CountDownLatch latch = new CountDownLatch(1); list.add(1L).subscribe((Boolean value, Throwable error) -> { if (error != null) { Assertions.fail(error.getMessage()); return; } list.add(2L).subscribe((Boolean va, Throwable err) -> { if (err != null) { Assertions.fail(err.getMessage()); return; } latch.countDown(); }); }); latch.await(); assertThat(sync(list)).containsExactly(1L, 2L); } @Test public void testLong() { RListRx<Long> list = redisson.getList("list"); sync(list.add(1L)); sync(list.add(2L)); assertThat(sync(list)).containsExactly(1L, 2L); } @Test public void testListIteratorIndex() { RListRx<Integer> list = redisson.getList("list2"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.add(0)); sync(list.add(7)); sync(list.add(8)); sync(list.add(0)); sync(list.add(10)); Iterator<Integer> iterator = toIterator(list.iterator()); Assertions.assertTrue(1 == iterator.next()); Assertions.assertTrue(2 == iterator.next()); Assertions.assertTrue(3 == iterator.next()); Assertions.assertTrue(4 == iterator.next()); Assertions.assertTrue(5 == iterator.next()); Assertions.assertTrue(0 == iterator.next()); Assertions.assertTrue(7 == iterator.next()); Assertions.assertTrue(8 == iterator.next()); Assertions.assertTrue(0 == iterator.next()); Assertions.assertTrue(10 == iterator.next()); Assertions.assertFalse(iterator.hasNext()); } @Test public void testListIteratorPrevious() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.add(0)); sync(list.add(7)); sync(list.add(8)); sync(list.add(0)); sync(list.add(10)); Iterator<Integer> iterator = toIterator(list.descendingIterator()); Assertions.assertTrue(10 == iterator.next()); Assertions.assertTrue(0 == iterator.next()); Assertions.assertTrue(8 == iterator.next()); Assertions.assertTrue(7 == iterator.next()); Assertions.assertTrue(0 == iterator.next()); Assertions.assertTrue(5 == iterator.next()); Assertions.assertTrue(4 == iterator.next()); Assertions.assertTrue(3 == iterator.next()); Assertions.assertTrue(2 == iterator.next()); Assertions.assertTrue(1 == iterator.next()); Assertions.assertFalse(iterator.hasNext()); } @Test public void testLastIndexOfNone() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertEquals(-1, sync(list.lastIndexOf(10)).intValue()); } @Test public void testLastIndexOf2() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.add(0)); sync(list.add(7)); sync(list.add(8)); sync(list.add(0)); sync(list.add(10)); long index = sync(list.lastIndexOf(3)); Assertions.assertEquals(2, index); } @Test public void testLastIndexOf1() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.add(3)); sync(list.add(7)); sync(list.add(8)); sync(list.add(0)); sync(list.add(10)); long index = sync(list.lastIndexOf(3)); Assertions.assertEquals(5, index); } @Test public void testLastIndexOf() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.add(3)); sync(list.add(7)); sync(list.add(8)); sync(list.add(3)); sync(list.add(10)); int index = sync(list.lastIndexOf(3)); Assertions.assertEquals(8, index); } @Test public void testIndexOf() { RListRx<Integer> list = redisson.getList("list"); for (int i = 1; i < 200; i++) { sync(list.add(i)); } Assertions.assertTrue(55 == sync(list.indexOf(56))); Assertions.assertTrue(99 == sync(list.indexOf(100))); Assertions.assertTrue(-1 == sync(list.indexOf(200))); Assertions.assertTrue(-1 == sync(list.indexOf(0))); } @Test public void testRemove() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Integer val = sync(list.remove(0)); Assertions.assertTrue(1 == val); assertThat(sync(list)).containsExactly(2, 3, 4, 5); } @Test public void testSet() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.set(4, 6)); assertThat(sync(list)).containsExactly(1, 2, 3, 4, 6); } @Test public void testSetFail() throws InterruptedException { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); sync(list.set(5, 6)); }); } @Test public void testRemoveAllEmpty() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertFalse(sync(list.removeAll(Collections.emptyList()))); Assertions.assertFalse(Arrays.asList(1).removeAll(Collections.emptyList())); } @Test public void testRemoveAll() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertFalse(sync(list.removeAll(Collections.emptyList()))); Assertions.assertTrue(sync(list.removeAll(Arrays.asList(3, 2, 10, 6)))); assertThat(sync(list)).containsExactly(1, 4, 5); Assertions.assertTrue(sync(list.removeAll(Arrays.asList(4)))); assertThat(sync(list)).containsExactly(1, 5); Assertions.assertTrue(sync(list.removeAll(Arrays.asList(1, 5, 1, 5)))); Assertions.assertEquals(0, sync(list.size()).longValue()); } @Test public void testRetainAll() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertTrue(sync(list.retainAll(Arrays.asList(3, 2, 10, 6)))); assertThat(sync(list)).containsExactly(2, 3); Assertions.assertEquals(2, sync(list.size()).longValue()); } @Test public void testFastSet() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.fastSet(0, 3)); Assertions.assertEquals(3, (int)sync(list.get(0))); } @Test public void testRetainAllEmpty() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertTrue(sync(list.retainAll(Collections.<Integer>emptyList()))); Assertions.assertEquals(0, sync(list.size()).intValue()); } @Test public void testRetainAllNoModify() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); Assertions.assertFalse(sync(list.retainAll(Arrays.asList(1, 2)))); // nothing changed assertThat(sync(list)).containsExactly(1, 2); } @Test public void testAddAllIndexError() { Assertions.assertThrows(RedisException.class, () -> { RListRx<Integer> list = redisson.getList("list"); sync(list.addAll(2, Arrays.asList(7, 8, 9))); }); } @Test public void testAddAllIndex() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertEquals(true, sync(list.addAll(2, Arrays.asList(7, 8, 9)))); assertThat(sync(list)).containsExactly(1, 2, 7, 8, 9, 3, 4, 5); sync(list.addAll(sync(list.size())-1, Arrays.asList(9, 1, 9))); assertThat(sync(list)).containsExactly(1, 2, 7, 8, 9, 3, 4, 9, 1, 9, 5); sync(list.addAll(sync(list.size()), Arrays.asList(0, 5))); assertThat(sync(list)).containsExactly(1, 2, 7, 8, 9, 3, 4, 9, 1, 9, 5, 0, 5); Assertions.assertEquals(true, sync(list.addAll(0, Arrays.asList(6, 7)))); assertThat(sync(list)).containsExactly(6,7,1, 2, 7, 8, 9, 3, 4, 9, 1, 9, 5, 0, 5); } @Test public void testAddAll() { RListRx<Integer> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2)); sync(list.add(3)); sync(list.add(4)); sync(list.add(5)); Assertions.assertEquals(true, sync(list.addAll(Arrays.asList(7, 8, 9)))); Assertions.assertEquals(true, sync(list.addAll(Arrays.asList(9, 1, 9)))); assertThat(sync(list)).containsExactly(1, 2, 3, 4, 5, 7, 8, 9, 9, 1, 9); } @Test public void testAddAllEmpty() { RListRx<Integer> list = redisson.getList("list"); Assertions.assertEquals(false, sync(list.addAll(Collections.<Integer>emptyList()))); Assertions.assertEquals(0, sync(list.size()).intValue()); } @Test public void testContainsAll() { RListRx<Integer> list = redisson.getList("list"); for (int i = 0; i < 200; i++) { sync(list.add(i)); } Assertions.assertTrue(sync(list.containsAll(Arrays.asList(30, 11)))); Assertions.assertFalse(sync(list.containsAll(Arrays.asList(30, 711, 11)))); Assertions.assertTrue(sync(list.containsAll(Arrays.asList(30)))); } @Test public void testContainsAllEmpty() { RListRx<Integer> list = redisson.getList("list"); for (int i = 0; i < 200; i++) { sync(list.add(i)); } Assertions.assertTrue(sync(list.containsAll(Collections.emptyList()))); Assertions.assertTrue(Arrays.asList(1).containsAll(Collections.emptyList())); } @Test public void testIteratorSequence() { RListRx<String> list = redisson.getList("list2"); sync(list.add("1")); sync(list.add("4")); sync(list.add("2")); sync(list.add("5")); sync(list.add("3")); checkIterator(list); // to test "memory effect" absence checkIterator(list); } private void checkIterator(RListRx<String> list) { int iteration = 0; for (Iterator<String> iterator = toIterator(list.iterator()); iterator.hasNext();) { String value = iterator.next(); String val = sync(list.get(iteration)); Assertions.assertEquals(val, value); iteration++; } Assertions.assertEquals(sync(list.size()).intValue(), iteration); } @Test public void testContains() { RListRx<String> list = redisson.getList("list"); sync(list.add("1")); sync(list.add("4")); sync(list.add("2")); sync(list.add("5")); sync(list.add("3")); Assertions.assertTrue(sync(list.contains("3"))); Assertions.assertFalse(sync(list.contains("31"))); Assertions.assertTrue(sync(list.contains("1"))); } // @Test(expected = RedisException.class) // public void testGetFail() { // RListRx<String> list = redisson.getList("list"); // // sync(list.get(0)); // } @Test public void testAddGet() { RListRx<String> list = redisson.getList("list"); sync(list.add("1")); sync(list.add("4")); sync(list.add("2")); sync(list.add("5")); sync(list.add("3")); String val1 = sync(list.get(0)); Assertions.assertEquals("1", val1); String val2 = sync(list.get(3)); Assertions.assertEquals("5", val2); } @Test public void testDuplicates() { RListRx<TestObject> list = redisson.getList("list"); sync(list.add(new TestObject("1", "2"))); sync(list.add(new TestObject("1", "2"))); sync(list.add(new TestObject("2", "3"))); sync(list.add(new TestObject("3", "4"))); sync(list.add(new TestObject("5", "6"))); Assertions.assertEquals(5, sync(list.size()).intValue()); } @Test public void testSize() { RListRx<String> list = redisson.getList("list"); sync(list.add("1")); sync(list.add("2")); sync(list.add("3")); sync(list.add("4")); sync(list.add("5")); sync(list.add("6")); assertThat(sync(list)).containsExactly("1", "2", "3", "4", "5", "6"); sync(list.remove("2")); assertThat(sync(list)).containsExactly("1", "3", "4", "5", "6"); sync(list.remove("4")); assertThat(sync(list)).containsExactly("1", "3", "5", "6"); } @Test public void testCodec() { RListRx<Object> list = redisson.getList("list"); sync(list.add(1)); sync(list.add(2L)); sync(list.add("3")); sync(list.add("e")); assertThat(sync(list)).containsExactly(1, 2L, "3", "e"); } }
RedissonListRxTest
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/pytorch/process/PyTorchBuilder.java
{ "start": 698, "end": 2768 }
class ____ { public static final String PROCESS_NAME = "pytorch_inference"; private static final String PROCESS_PATH = "./" + PROCESS_NAME; private static final String LICENSE_KEY_VALIDATED_ARG = "--validElasticLicenseKeyConfirmed="; private static final String NUM_THREADS_PER_ALLOCATION_ARG = "--numThreadsPerAllocation="; private static final String NUM_ALLOCATIONS_ARG = "--numAllocations="; private static final String CACHE_MEMORY_LIMIT_BYTES_ARG = "--cacheMemorylimitBytes="; private static final String LOW_PRIORITY_ARG = "--lowPriority"; private final NativeController nativeController; private final ProcessPipes processPipes; private final StartTrainedModelDeploymentAction.TaskParams taskParams; public PyTorchBuilder( NativeController nativeController, ProcessPipes processPipes, StartTrainedModelDeploymentAction.TaskParams taskParams ) { this.nativeController = Objects.requireNonNull(nativeController); this.processPipes = Objects.requireNonNull(processPipes); this.taskParams = Objects.requireNonNull(taskParams); } public void build() throws IOException, InterruptedException { List<String> command = buildCommand(); processPipes.addArgs(command); nativeController.startProcess(command); } private List<String> buildCommand() { List<String> command = new ArrayList<>(); command.add(PROCESS_PATH); // License was validated when the trained model was started command.add(LICENSE_KEY_VALIDATED_ARG + true); command.add(NUM_THREADS_PER_ALLOCATION_ARG + taskParams.getThreadsPerAllocation()); command.add(NUM_ALLOCATIONS_ARG + taskParams.getNumberOfAllocations()); if (taskParams.getCacheSizeBytes() > 0) { command.add(CACHE_MEMORY_LIMIT_BYTES_ARG + taskParams.getCacheSizeBytes()); } if (taskParams.getPriority() == Priority.LOW) { command.add(LOW_PRIORITY_ARG); } return command; } }
PyTorchBuilder
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java
{ "start": 15685, "end": 15808 }
class ____ { } @SelectMethod(name = "testMethod", parameterTypes = int.class, parameterTypeNames = "int")
TypeAndTypeName
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/AdsDumpTest_0.java
{ "start": 313, "end": 1838 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "/*+dump-merge=true*/DUMP DATA SELECT amp.buyer_add_cart_info.buyer_id,amp.buyer_add_cart_info.pre_score,amp.buyer_add_cart_info.cart_price FROM amp.buyer_add_cart_info " + "JOIN amp.crm_user_base_info " + "ON amp.crm_user_base_info.user_id = amp.buyer_add_cart_info.buyer_id " + "where (((amp.buyer_add_cart_info.seller_id=1921906956)) " + "AND ((amp.buyer_add_cart_info.auction_id=562769960283)) " + "AND ((amp.buyer_add_cart_info.show_price>=13300))) " + "LIMIT 144800 "; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLDumpStatement stmt = (SQLDumpStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("/*+dump-merge=true*/\n" + "DUMP DATA SELECT amp.buyer_add_cart_info.buyer_id, amp.buyer_add_cart_info.pre_score, amp.buyer_add_cart_info.cart_price\n" + "FROM amp.buyer_add_cart_info\n" + "\tJOIN amp.crm_user_base_info ON amp.crm_user_base_info.user_id = amp.buyer_add_cart_info.buyer_id\n" + "WHERE ((amp.buyer_add_cart_info.seller_id = 1921906956)\n" + "\tAND (amp.buyer_add_cart_info.auction_id = 562769960283)\n" + "\tAND (amp.buyer_add_cart_info.show_price >= 13300))\n" + "LIMIT 144800", stmt.toString()); } }
AdsDumpTest_0
java
spring-projects__spring-boot
module/spring-boot-jersey/src/test/java/org/springframework/boot/jersey/autoconfigure/JerseyAutoConfigurationCustomLoadOnStartupTests.java
{ "start": 1905, "end": 2193 }
class ____ { @Autowired private ApplicationContext context; @Test void contextLoads() { assertThat(this.context.getBean("jerseyServletRegistration")).hasFieldOrPropertyWithValue("loadOnStartup", 5); } @MinimalWebConfiguration static
JerseyAutoConfigurationCustomLoadOnStartupTests
java
apache__camel
tooling/openapi-rest-dsl-generator/src/test/java/org/apache/camel/generator/openapi/RestDslXmlGeneratorV3SimpleTest.java
{ "start": 1284, "end": 2076 }
class ____ { static OpenAPI document; @BeforeAll public static void readOpenApiDoc() throws Exception { document = new OpenAPIV3Parser().read("src/test/resources/org/apache/camel/generator/openapi/openapi-spec-simple.json"); } @Test public void shouldGenerateXmlWithDefaults() throws Exception { final CamelContext context = new DefaultCamelContext(); final String xml = RestDslGenerator.toXml(document).generate(context); final URI file = RestDslXmlGeneratorV3Test.class.getResource("/OpenApiV3PetstoreSimpleXml.txt").toURI(); final String expectedContent = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8); assertThat(xml).isXmlEqualTo(expectedContent); } }
RestDslXmlGeneratorV3SimpleTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/StickyAssignor.java
{ "start": 5840, "end": 7015 }
class ____ implements ConsumerRebalanceListener { * * void onPartitionsRevoked(Collection<TopicPartition> partitions) { * for (TopicPartition partition: partitions) { * commitOffsets(partition); * cleanupState(partition); * } * } * * void onPartitionsAssigned(Collection<TopicPartition> partitions) { * for (TopicPartition partition: partitions) { * initializeState(partition); * initializeOffset(partition); * } * } * } * } * </pre> * * As mentioned above, one advantage of the sticky assignor is that, in general, it reduces the number of partitions that * actually move from one consumer to another during a reassignment. Therefore, it allows consumers to do their cleanup * more efficiently. Of course, they still can perform the partition cleanup in the <code>onPartitionsRevoked()</code> * listener, but they can be more efficient and make a note of their partitions before and after the rebalance, and do the * cleanup after the rebalance only on the partitions they have lost (which is normally not a lot). The code snippet below * clarifies this point: * <pre> * {@code *
TheOldRebalanceListener
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/exc/DefaultExceptionHandlerProvider.java
{ "start": 451, "end": 1830 }
class ____ implements ExceptionHandlerProvider { private final AuthExceptionHandlerProvider authExceptionHandlerProvider; public DefaultExceptionHandlerProvider(Instance<AuthExceptionHandlerProvider> authExceptionHandlerProviderInstance) { if (authExceptionHandlerProviderInstance.isResolvable()) { this.authExceptionHandlerProvider = authExceptionHandlerProviderInstance.get(); } else { this.authExceptionHandlerProvider = null; } } @Override public <ReqT, RespT> ExceptionHandler<ReqT, RespT> createHandler(ServerCall.Listener<ReqT> listener, ServerCall<ReqT, RespT> call, Metadata metadata) { return new DefaultExceptionHandler<>(listener, call, metadata, authExceptionHandlerProvider); } @Override public Throwable transform(Throwable t) { return toStatusException(authExceptionHandlerProvider, t); } private static Throwable toStatusException(AuthExceptionHandlerProvider authExceptionHandlerProvider, Throwable t) { if (authExceptionHandlerProvider != null && authExceptionHandlerProvider.handlesException(t)) { return authExceptionHandlerProvider.transformToStatusException(t); } else { return ExceptionHandlerProvider.toStatusException(t, false); } } private static
DefaultExceptionHandlerProvider
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java
{ "start": 27167, "end": 27840 }
class ____ { * * &#064;Bean * &#064;DubboService(group="demo", version="1.2.3") * public DemoService demoService() { * return new DemoServiceImpl(); * } * * } * </pre> * * @param refServiceBeanName * @param refServiceBeanDefinition * @param attributes */ private void processAnnotatedBeanDefinition( String refServiceBeanName, AnnotatedBeanDefinition refServiceBeanDefinition, Map<String, Object> attributes) { Map<String, Object> serviceAnnotationAttributes = new LinkedHashMap<>(attributes); // get bean
ProviderConfig
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/SetExchangePatternTest.java
{ "start": 1260, "end": 6712 }
class ____ extends ContextTestSupport { @Test public void testInOut() throws Exception { assertMessageReceivedWithPattern("direct:testInOut", ExchangePattern.InOut); } @Test public void testInOnly() throws Exception { assertMessageReceivedWithPattern("direct:testInOnly", ExchangePattern.InOnly); } @Test public void testSetToInOnlyThenTo() throws Exception { assertMessageReceivedWithPattern("direct:testSetToInOnlyThenTo", ExchangePattern.InOnly); } @Test public void testSetToInOutThenTo() throws Exception { assertMessageReceivedWithPattern("direct:testSetToInOutThenTo", ExchangePattern.InOut); } @Test public void testToWithInOnlyParam() throws Exception { assertMessageReceivedWithPattern("direct:testToWithInOnlyParam", ExchangePattern.InOnly); } @Test public void testToWithInOutParam() throws Exception { assertMessageReceivedWithPattern("direct:testToWithInOutParam", ExchangePattern.InOut); } @Test public void testSetExchangePatternInOnly() throws Exception { assertMessageReceivedWithPattern("direct:testSetExchangePatternInOnly", ExchangePattern.InOnly); } @Test public void testSetAsString() throws Exception { assertMessageReceivedWithPattern("direct:asString", ExchangePattern.InOut); } @Test public void testPreserveOldMEPInOut() throws Exception { // the mock should get an InOut MEP getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").message(0).exchangePattern().isEqualTo(ExchangePattern.InOut); // we send an InOnly Exchange out = template.send("direct:testInOut", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setBody("Hello World"); exchange.setPattern(ExchangePattern.InOnly); } }); // the MEP should be preserved assertNotNull(out); assertEquals(ExchangePattern.InOnly, out.getPattern()); assertMockEndpointsSatisfied(); } @Test public void testPreserveOldMEPInOnly() throws Exception { // the mock should get an InOnly MEP getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").message(0).exchangePattern().isEqualTo(ExchangePattern.InOnly); // we send an InOut Exchange out = template.send("direct:testInOnly", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setBody("Hello World"); exchange.setPattern(ExchangePattern.InOut); } }); // the MEP should be preserved assertNotNull(out); assertEquals(ExchangePattern.InOut, out.getPattern()); assertMockEndpointsSatisfied(); } protected void assertMessageReceivedWithPattern(String sendUri, ExchangePattern expectedPattern) throws InterruptedException { ExchangePattern sendPattern; switch (expectedPattern) { case InOut: sendPattern = ExchangePattern.InOnly; break; case InOnly: sendPattern = ExchangePattern.InOut; break; default: sendPattern = ExchangePattern.InOnly; } MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); String expectedBody = "InOnlyMessage"; resultEndpoint.expectedBodiesReceived(expectedBody); resultEndpoint.expectedHeaderReceived("foo", "bar"); template.sendBodyAndHeader(sendUri, sendPattern, expectedBody, "foo", "bar"); resultEndpoint.assertIsSatisfied(); ExchangePattern actualPattern = resultEndpoint.getExchanges().get(0).getPattern(); assertEquals(actualPattern, expectedPattern, "received exchange pattern"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: example // Send to an endpoint using InOut from("direct:testInOut").to(ExchangePattern.InOut, "mock:result"); // Send to an endpoint using InOut from("direct:testInOnly").to(ExchangePattern.InOnly, "mock:result"); // Set the exchange pattern to InOut, then send it from // direct:inOnly to mock:result endpoint from("direct:testSetToInOnlyThenTo").setExchangePattern(ExchangePattern.InOnly).to("mock:result"); from("direct:testSetToInOutThenTo").setExchangePattern(ExchangePattern.InOut).to("mock:result"); // Or we can pass the pattern as a parameter to the to() method from("direct:testToWithInOnlyParam").to(ExchangePattern.InOnly, "mock:result"); from("direct:testToWithInOutParam").to(ExchangePattern.InOut, "mock:result"); // Set the exchange pattern to InOut, then send it on from("direct:testSetExchangePatternInOnly").setExchangePattern(ExchangePattern.InOnly).to("mock:result"); // END SNIPPET: example from("direct:asString").setExchangePattern("InOut").to("mock:result"); } }; } }
SetExchangePatternTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleMultiInsertTest.java
{ "start": 971, "end": 4877 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "INSERT ALL" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date, sales_sun)" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date+1, sales_mon)" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date+2, sales_tue)" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date+3, sales_wed)" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date+4, sales_thu)" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date+5, sales_fri)" + " INTO sales (prod_id, cust_id, time_id, amount)" + " VALUES (product_id, customer_id, weekly_start_date+6, sales_sat)" + " SELECT product_id, customer_id, weekly_start_date, sales_sun," + " sales_mon, sales_tue, sales_wed, sales_thu, sales_fri, sales_sat" + " FROM sales_input_table;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("sales"))); assertTrue(visitor.getTables().containsKey(new TableStat.Name("sales_input_table"))); assertEquals(2, visitor.getTables().size()); assertEquals(14, visitor.getColumns().size()); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales", "prod_id"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales", "cust_id"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales", "time_id"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales", "amount"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "product_id"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "customer_id"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "weekly_start_date"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_sun"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_mon"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_tue"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_wed"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_thu"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_fri"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("sales_input_table", "sales_sat"))); } }
OracleMultiInsertTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/MultipleBoundsTest.java
{ "start": 3270, "end": 3727 }
class ____ extends AbstractTranslationEntity<User> { @Column(name = "TRANSLATION_COLUMN") private String translation; public UserTranslation() { } public UserTranslation(Long id, String translation, User user) { super( id, user ); this.translation = translation; } public String getTranslation() { return translation; } public void setTranslation(String translation) { this.translation = translation; } } }
UserTranslation
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java
{ "start": 21339, "end": 22603 }
class ____ extends AbstractOAuth2AuthorizationRowMapper { private final JsonMapper jsonMapper; public JsonMapperOAuth2AuthorizationRowMapper(RegisteredClientRepository registeredClientRepository) { this(registeredClientRepository, Jackson3.createJsonMapper()); } public JsonMapperOAuth2AuthorizationRowMapper(RegisteredClientRepository registeredClientRepository, JsonMapper jsonMapper) { super(registeredClientRepository); Assert.notNull(jsonMapper, "jsonMapper cannot be null"); this.jsonMapper = jsonMapper; } @Override Map<String, Object> readValue(String data) { final ParameterizedTypeReference<Map<String, Object>> typeReference = new ParameterizedTypeReference<>() { }; tools.jackson.databind.JavaType javaType = this.jsonMapper.getTypeFactory() .constructType(typeReference.getType()); return this.jsonMapper.readValue(data, javaType); } } /** * A {@link RowMapper} that maps the current row in {@code java.sql.ResultSet} to * {@link OAuth2Authorization} using Jackson 2's {@link ObjectMapper}. * * @deprecated Use {@link JsonMapperOAuth2AuthorizationRowMapper} to switch to Jackson * 3. */ @Deprecated(forRemoval = true, since = "7.0") public static
JsonMapperOAuth2AuthorizationRowMapper