language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/enumerated/EnumeratedSmokeTest.java
{ "start": 1013, "end": 3163 }
class ____ { /** * I personally have been unable to repeoduce the bug as reported in HHH-10402. This test * is equivalent to what the reporters say happens, but these tests pass fine. */ @Test @JiraKey( "HHH-10402" ) public void testEnumeratedTypeResolutions(ServiceRegistryScope serviceRegistryScope) { final MetadataImplementor mappings = (MetadataImplementor) new MetadataSources( serviceRegistryScope.getRegistry() ) .addAnnotatedClass( EntityWithEnumeratedAttributes.class ) .buildMetadata(); mappings.orderColumns( false ); mappings.validate(); final JdbcTypeRegistry jdbcTypeRegistry = mappings.getTypeConfiguration().getJdbcTypeRegistry(); final PersistentClass entityBinding = mappings.getEntityBinding( EntityWithEnumeratedAttributes.class.getName() ); validateEnumMapping( jdbcTypeRegistry, entityBinding.getProperty( "notAnnotated" ), EnumType.ORDINAL ); validateEnumMapping( jdbcTypeRegistry, entityBinding.getProperty( "noEnumType" ), EnumType.ORDINAL ); validateEnumMapping( jdbcTypeRegistry, entityBinding.getProperty( "ordinalEnumType" ), EnumType.ORDINAL ); validateEnumMapping( jdbcTypeRegistry, entityBinding.getProperty( "stringEnumType" ), EnumType.STRING ); } private void validateEnumMapping(JdbcTypeRegistry jdbcRegistry, Property property, EnumType expectedJpaEnumType) { final BasicType<?> propertyType = (BasicType<?>) property.getType(); // final EnumValueConverter<?, ?> valueConverter = (EnumValueConverter<?, ?>) propertyType.getValueConverter(); final JdbcMapping jdbcMapping = propertyType.getJdbcMapping(); final JdbcType jdbcType = jdbcMapping.getJdbcType(); assert expectedJpaEnumType != null; if ( expectedJpaEnumType == EnumType.ORDINAL ) { // Assertions.assertThat( valueConverter ).isInstanceOf( OrdinalEnumValueConverter.class ); Assertions.assertThat( jdbcType.isInteger() ).isTrue(); } else { // Assertions.assertThat( valueConverter ).isInstanceOf( NamedEnumValueConverter.class ); Assertions.assertThat( jdbcType.isString() || jdbcType.getDefaultSqlTypeCode() == SqlTypes.ENUM ).isTrue(); } } @Entity public static
EnumeratedSmokeTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/introspection/CaseFormatUtils.java
{ "start": 975, "end": 2595 }
class ____ { private static final String WORD_SEPARATOR_REGEX = "[ _-]"; private CaseFormatUtils() {} /** * Converts an input string into camelCase. * <p> * The input string may use any of the well known case styles: Pascal, Snake, Kebab or even Camel. * Already camelCased strings will be returned as is. * Mix and match is also an option; the algorithm will try its best to give an acceptable answer. * Mixed case will be preserved, i.e {@code assertThat(toCamelCase("miXedCAse")).isEqualTo("miXedCAse")} * * @param s the string to be converted * @return the input string converted to camelCase */ public static String toCamelCase(String s) { List<String> words = extractWords(requireNonNull(s)); return IntStream.range(0, words.size()) .mapToObj(i -> adjustWordCase(words.get(i), i > 0)) .collect(joining()); } private static List<String> extractWords(String s) { String[] chunks = s.split(WORD_SEPARATOR_REGEX); return Arrays.stream(chunks) .map(String::trim) .filter(w -> !w.isEmpty()) .collect(toList()); } private static String adjustWordCase(String s, boolean firstLetterUpperCased) { String firstLetter = s.substring(0, 1); String trailingLetters = s.substring(1); return (firstLetterUpperCased ? firstLetter.toUpperCase() : firstLetter.toLowerCase()) + (isAllCaps(s) ? trailingLetters.toLowerCase() : trailingLetters); } private static boolean isAllCaps(String s) { return s.toUpperCase().equals(s); } }
CaseFormatUtils
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/TopologyMetadata.java
{ "start": 28085, "end": 29472 }
class ____ implements Comparable<Subtopology> { final int nodeGroupId; final String namedTopology; public Subtopology(final int nodeGroupId, final String namedTopology) { this.nodeGroupId = nodeGroupId; this.namedTopology = namedTopology; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Subtopology that = (Subtopology) o; return nodeGroupId == that.nodeGroupId && Objects.equals(namedTopology, that.namedTopology); } @Override public int hashCode() { return Objects.hash(nodeGroupId, namedTopology); } @Override public int compareTo(final Subtopology other) { if (nodeGroupId != other.nodeGroupId) { return Integer.compare(nodeGroupId, other.nodeGroupId); } if (namedTopology == null) { return other.namedTopology == null ? 0 : -1; } if (other.namedTopology == null) { return 1; } // Both not null return namedTopology.compareTo(other.namedTopology); } } }
Subtopology
java
mockito__mockito
mockito-core/src/testFixtures/java/org/mockitoutil/ClassLoaders.java
{ "start": 18340, "end": 22009 }
class ____ { private ClassLoader classLoader; private Set<String> qualifiedNameSubstring = new HashSet<String>(); ReachableClassesFinder(ClassLoader classLoader) { this.classLoader = classLoader; } public ReachableClassesFinder omit(String... qualifiedNameSubstring) { this.qualifiedNameSubstring.addAll(Arrays.asList(qualifiedNameSubstring)); return this; } public Set<String> listOwnedClasses() throws IOException, URISyntaxException { Enumeration<URL> roots = classLoader.getResources(""); Set<String> classes = new HashSet<String>(); while (roots.hasMoreElements()) { URI uri = roots.nextElement().toURI(); if (uri.getScheme().equalsIgnoreCase("file")) { addFromFileBasedClassLoader(classes, uri); } else if (uri.getScheme().equalsIgnoreCase(InMemoryClassLoader.SCHEME)) { addFromInMemoryBasedClassLoader(classes, uri); } else if (uri.getScheme().equalsIgnoreCase("jar")) { // Java 9+ returns "jar:file:" style urls for modules. // It's not a classes owned by mockito itself. // Just ignore it. continue; } else { throw new IllegalArgumentException( format( "Given ClassLoader '%s' don't have reachable by File or vi ClassLoaders.inMemory", classLoader)); } } return classes; } private void addFromFileBasedClassLoader(Set<String> classes, URI uri) { File root = new File(uri); classes.addAll(findClassQualifiedNames(root, root, qualifiedNameSubstring)); } private void addFromInMemoryBasedClassLoader(Set<String> classes, URI uri) { String qualifiedName = uri.getSchemeSpecificPart(); if (excludes(qualifiedName, qualifiedNameSubstring)) { classes.add(qualifiedName); } } private Set<String> findClassQualifiedNames( File root, File file, Set<String> packageFilters) { if (file.isDirectory()) { File[] files = file.listFiles(); Set<String> classes = new HashSet<String>(); for (File children : files) { classes.addAll(findClassQualifiedNames(root, children, packageFilters)); } return classes; } else { if (file.getName().endsWith(".class")) { String qualifiedName = classNameFor(root, file); if (excludes(qualifiedName, packageFilters)) { return Collections.singleton(qualifiedName); } } } return Collections.emptySet(); } private boolean excludes(String qualifiedName, Set<String> packageFilters) { for (String filter : packageFilters) { if (qualifiedName.contains(filter)) return false; } return true; } private String classNameFor(File root, File file) { String temp = file.getAbsolutePath() .substring(root.getAbsolutePath().length() + 1) .replace(File.separatorChar, '.'); return temp.subSequence(0, temp.indexOf(".class")).toString(); } } }
ReachableClassesFinder
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/LifecycleInterceptor.java
{ "start": 452, "end": 1933 }
class ____ { static final List<Object> AROUND_CONSTRUCTS = new CopyOnWriteArrayList<>(); static final List<Object> POST_CONSTRUCTS = new CopyOnWriteArrayList<>(); static final List<Object> PRE_DESTROYS = new CopyOnWriteArrayList<>(); @PostConstruct void simpleInit(InvocationContext ctx) throws Exception { Object bindings = ctx.getContextData().get(ArcInvocationContext.KEY_INTERCEPTOR_BINDINGS); if (bindings == null) { throw new IllegalArgumentException("No bindings found"); } POST_CONSTRUCTS.add(ctx.getTarget()); ctx.proceed(); } @PreDestroy void simpleDestroy(InvocationContext ctx) throws Exception { Object bindings = ctx.getContextData().get(ArcInvocationContext.KEY_INTERCEPTOR_BINDINGS); if (bindings == null) { throw new IllegalArgumentException("No bindings found"); } PRE_DESTROYS.add(ctx.getTarget()); ctx.proceed(); } @AroundConstruct void simpleAroundConstruct(InvocationContext ctx) throws Exception { Object bindings = ctx.getContextData().get(ArcInvocationContext.KEY_INTERCEPTOR_BINDINGS); if (bindings == null) { throw new IllegalArgumentException("No bindings found"); } try { AROUND_CONSTRUCTS.add(ctx.getConstructor()); ctx.proceed(); } catch (Exception e) { e.printStackTrace(); } } }
LifecycleInterceptor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/typedonetoone/TypedOneToOneTest.java
{ "start": 723, "end": 3238 }
class ____ { @Test public void testCreateQuery(SessionFactoryScope scope) { scope.inTransaction( session -> { Customer cust = new Customer(); cust.setCustomerId( "abc123" ); cust.setName( "Matt" ); Address ship = new Address(); ship.setStreet( "peachtree rd" ); ship.setState( "GA" ); ship.setCity( "ATL" ); ship.setZip( "30326" ); ship.setAddressId( new AddressId( "SHIPPING", "abc123" ) ); ship.setCustomer( cust ); Address bill = new Address(); bill.setStreet( "peachtree rd" ); bill.setState( "GA" ); bill.setCity( "ATL" ); bill.setZip( "30326" ); bill.setAddressId( new AddressId( "BILLING", "abc123" ) ); bill.setCustomer( cust ); cust.setBillingAddress( bill ); cust.setShippingAddress( ship ); session.persist( cust ); } ); scope.inTransaction( session -> { List<Customer> results = session.createQuery( "from Customer cust left join fetch cust.billingAddress where cust.customerId='abc123'" ) .list(); //List results = s.createQuery("from Customer cust left join fetch cust.billingAddress left join fetch cust.shippingAddress").list(); Customer cust = results.get( 0 ); assertTrue( Hibernate.isInitialized( cust.getShippingAddress() ) ); assertTrue( Hibernate.isInitialized( cust.getBillingAddress() ) ); assertEquals( "30326", cust.getBillingAddress().getZip() ); assertEquals( "30326", cust.getShippingAddress().getZip() ); assertEquals( "BILLING", cust.getBillingAddress().getAddressId().getType() ); assertEquals( "SHIPPING", cust.getShippingAddress().getAddressId().getType() ); session.remove( cust ); } ); } @Test public void testCreateQueryNull(SessionFactoryScope scope) { scope.inTransaction( session -> { Customer cust = new Customer(); cust.setCustomerId( "xyz123" ); cust.setName( "Matt" ); session.persist( cust ); } ); scope.inTransaction( session -> { List<Customer> results = session.createQuery( "from Customer cust left join fetch cust.billingAddress where cust.customerId='xyz123'" ) .list(); //List results = s.createQuery("from Customer cust left join fetch cust.billingAddress left join fetch cust.shippingAddress").list(); Customer cust = results.get( 0 ); assertNull( cust.getShippingAddress() ); assertNull( cust.getBillingAddress() ); session.remove( cust ); } ); } }
TypedOneToOneTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/injectionstrategy/jakarta/_default/JakartaAndJsr330DefaultCompileOptionFieldMapperTest.java
{ "start": 1321, "end": 2086 }
class ____ { @RegisterExtension final GeneratedSource generatedSource = new GeneratedSource(); @ProcessorTest public void shouldHaveJakartaInjection() { generatedSource.forMapper( CustomerJakartaDefaultCompileOptionFieldMapper.class ) .content() .contains( "import jakarta.inject.Inject;" ) .contains( "import jakarta.inject.Named;" ) .contains( "import jakarta.inject.Singleton;" ) .contains( "@Inject" + lineSeparator() + " private GenderJakartaDefaultCompileOptionFieldMapper" ) .doesNotContain( "public CustomerJakartaDefaultCompileOptionFieldMapperImpl(" ) .doesNotContain( "javax.inject" ); } }
JakartaAndJsr330DefaultCompileOptionFieldMapperTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/future/CompletableFutureAssert_isNotCompleted_Test.java
{ "start": 1091, "end": 2492 }
class ____ { @Test void should_pass_if_completable_future_is_incomplete() { // GIVEN CompletableFuture<String> future = new CompletableFuture<>(); // THEN then(future).isNotCompleted(); } @Test void should_pass_if_completable_future_has_failed() { // GIVEN CompletableFuture<String> future = new CompletableFuture<>(); // WHEN future.completeExceptionally(new RuntimeException()); // THEN then(future).isNotCompleted(); } @Test void should_pass_if_completable_future_was_cancelled() { // GIVEN CompletableFuture<String> future = new CompletableFuture<>(); // WHEN future.cancel(true); // THEN then(future).isNotCompleted(); } @Test void should_fail_when_completable_future_is_null() { // GIVEN CompletableFuture<String> future = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(future).isNotCompleted()); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_if_completable_future_is_completed() { // GIVEN CompletableFuture<String> future = CompletableFuture.completedFuture("done"); // WHEN var assertionError = expectAssertionError(() -> assertThat(future).isNotCompleted()); // THEN then(assertionError).hasMessage(shouldNotBeCompleted(future).create()); } }
CompletableFutureAssert_isNotCompleted_Test
java
quarkusio__quarkus
integration-tests/vertx-http-compressors/app/src/main/java/io/quarkus/compressors/it/DecompressResource.java
{ "start": 748, "end": 2197 }
class ____ { @POST @Path("/text") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public String textPost(String text) { return text; } @PUT @Path("/text") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public String textPut(String text) { return text; } @POST @Path("/json") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String jsonPost(String json) { return json; } @PUT @Path("/json") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String jsonPut(String json) { return json; } @POST @Path("/xml") @Produces(MediaType.TEXT_XML) @Consumes(MediaType.TEXT_XML) public String xmlPost(String xml) { return xml; } @PUT @Path("/xml") @Produces(MediaType.TEXT_XML) @Consumes(MediaType.TEXT_XML) public String xmlPut(String xml) { return xml; } @POST @Path("/xhtml") @Produces(MediaType.APPLICATION_XHTML_XML) @Consumes(MediaType.APPLICATION_XHTML_XML) public String xhtmlPost(String xhtml) { return xhtml; } @PUT @Path("/xhtml") @Produces(MediaType.APPLICATION_XHTML_XML) @Consumes(MediaType.APPLICATION_XHTML_XML) public String xhtmlPut(String xhtml) { return xhtml; } }
DecompressResource
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/resource/basic/WiderMappingNegativeTest.java
{ "start": 1183, "end": 2567 }
class ____ { static Client client; private String generateURL(String path) { return PortProviderUtil.generateURL(path, WiderMappingNegativeTest.class.getSimpleName()); } @RegisterExtension static ResteasyReactiveUnitTest testExtension = new ResteasyReactiveUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { JavaArchive war = ShrinkWrap.create(JavaArchive.class); war.addClasses(PortProviderUtil.class, WiderMappingResource.class, WiderMappingDefaultOptions.class); return war; } }); @BeforeAll public static void setup() { client = ClientBuilder.newClient(); } @AfterAll public static void cleanup() { client.close(); } /** * @tpTestDetails Two resources used, more general resource should not be used * @tpSince RESTEasy 3.0.16 */ @Test @DisplayName("Test Options") public void testOptions() { Response response = client.target(generateURL("/hello/int")).request().options(); Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); Assertions.assertNotEquals(response.readEntity(String.class), "hello"); response.close(); } }
WiderMappingNegativeTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/DefaultCheckpointStatsTracker.java
{ "start": 2718, "end": 2970 }
interface ____ { StatsSummary extract(TaskStateStats.TaskStateStatsSummary taskStateStatsSummary); } /** Function that extracts a (long) metric value from {@link SubtaskStateStats}. */ @FunctionalInterface
TaskStatsSummaryExtractor
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/storage/TieredStorageMemoryManagerImpl.java
{ "start": 2801, "end": 17779 }
class ____ implements TieredStorageMemoryManager { /** Time to wait for requesting new buffers before triggering buffer reclaiming. */ private static final int INITIAL_REQUEST_BUFFER_TIMEOUT_FOR_RECLAIMING_MS = 50; /** The maximum delay time before triggering buffer reclaiming. */ private static final int MAX_DELAY_TIME_TO_TRIGGER_RECLAIM_BUFFER_MS = 1000; /** The tiered storage memory specs of each memory user owner. */ private final Map<Object, TieredStorageMemorySpec> tieredMemorySpecs; /** Listeners used to listen the requests for reclaiming buffer in different tiered storage. */ private final List<Runnable> bufferReclaimRequestListeners; /** The buffer pool usage ratio of triggering the registered storages to reclaim buffers. */ private final float numTriggerReclaimBuffersRatio; /** * Indicates whether reclaiming of buffers is supported. If supported, when there's a * contention, we may try reclaim buffers from the memory owners. */ private final boolean mayReclaimBuffer; /** * The number of requested buffers from {@link BufferPool}. This field can be touched both by * the task thread and the netty thread, so it is an atomic type. */ private final AtomicInteger numRequestedBuffers; /** * The number of requested buffers from {@link BufferPool} for each memory owner. This field * should be thread-safe because it can be touched both by the task thread and the netty thread. */ private final Map<Object, Integer> numOwnerRequestedBuffers; /** * The queue that contains all available buffers. This field should be thread-safe because it * can be touched both by the task thread and the netty thread. */ private final BlockingQueue<MemorySegment> bufferQueue; /** The lock guarding concurrency issues during releasing. */ private final ReadWriteLock releasedStateLock; /** The number of buffers that are guaranteed to be reclaimed. */ private int numGuaranteedReclaimableBuffers; /** * Time gauge to measure that hard backpressure time. Pre-create it to avoid checkNotNull in * hot-path for performance purpose. */ private TimerGauge hardBackpressureTimerGauge = new TimerGauge(); /** * This is for triggering buffer reclaiming while blocked on requesting new buffers. * * <p>Note: This can be null iff buffer reclaiming is not supported. */ @Nullable private ScheduledExecutorService executor; /** The buffer pool where the buffer is requested or recycled. */ private BufferPool bufferPool; /** * Indicates whether the {@link TieredStorageMemoryManagerImpl} is initialized. Before setting * up, this field is false. * * <p>Note that before requesting buffers or getting the maximum allowed buffers, this * initialized state should be checked. */ private boolean isInitialized; /** * Indicates whether the {@link TieredStorageMemoryManagerImpl} is released. * * <p>Note that before recycling buffers, this released state should be checked to determine * whether to recycle the buffer back to the internal queue or to the buffer pool. */ @GuardedBy("readWriteLock") private boolean isReleased; /** * The constructor of the {@link TieredStorageMemoryManagerImpl}. * * @param numTriggerReclaimBuffersRatio the buffer pool usage ratio of requesting each tiered * storage to reclaim buffers * @param mayReclaimBuffer indicate whether buffer reclaiming is supported */ public TieredStorageMemoryManagerImpl( float numTriggerReclaimBuffersRatio, boolean mayReclaimBuffer) { this.numTriggerReclaimBuffersRatio = numTriggerReclaimBuffersRatio; this.mayReclaimBuffer = mayReclaimBuffer; this.tieredMemorySpecs = new HashMap<>(); this.numRequestedBuffers = new AtomicInteger(0); this.numOwnerRequestedBuffers = new ConcurrentHashMap<>(); this.bufferReclaimRequestListeners = new ArrayList<>(); this.bufferQueue = new LinkedBlockingQueue<>(); this.releasedStateLock = new ReentrantReadWriteLock(); this.isReleased = false; this.isInitialized = false; } @Override public void setup(BufferPool bufferPool, List<TieredStorageMemorySpec> storageMemorySpecs) { this.bufferPool = bufferPool; for (TieredStorageMemorySpec memorySpec : storageMemorySpecs) { checkState( !tieredMemorySpecs.containsKey(memorySpec.getOwner()), "Duplicated memory spec."); tieredMemorySpecs.put(memorySpec.getOwner(), memorySpec); numGuaranteedReclaimableBuffers += memorySpec.isGuaranteedReclaimable() ? memorySpec.getNumGuaranteedBuffers() : 0; } if (mayReclaimBuffer) { this.executor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("buffer reclaim checker") .setUncaughtExceptionHandler(FatalExitExceptionHandler.INSTANCE) .build()); } this.isInitialized = true; } @Override public void setMetricGroup(TaskIOMetricGroup metricGroup) { this.hardBackpressureTimerGauge = checkNotNull(metricGroup.getHardBackPressuredTimePerSecond()); } @Override public void listenBufferReclaimRequest(Runnable onBufferReclaimRequest) { bufferReclaimRequestListeners.add(onBufferReclaimRequest); } @Override public BufferPool getBufferPool() { return bufferPool; } @Override public BufferBuilder requestBufferBlocking(Object owner) { checkIsInitialized(); reclaimBuffersIfNeeded(0); MemorySegment memorySegment = bufferQueue.poll(); if (memorySegment == null) { memorySegment = requestBufferBlockingFromPool(); } if (memorySegment == null) { memorySegment = checkNotNull(requestBufferBlockingFromQueue()); } incNumRequestedBuffer(owner); return new BufferBuilder( checkNotNull(memorySegment), segment -> recycleBuffer(owner, segment)); } @Override public int getMaxNonReclaimableBuffers(Object owner) { checkIsInitialized(); int numBuffersUsedOrReservedForOtherOwners = 0; for (Map.Entry<Object, TieredStorageMemorySpec> memorySpecEntry : tieredMemorySpecs.entrySet()) { Object userOwner = memorySpecEntry.getKey(); TieredStorageMemorySpec storageMemorySpec = memorySpecEntry.getValue(); if (!userOwner.equals(owner)) { int numGuaranteed = storageMemorySpec.getNumGuaranteedBuffers(); int numRequested = numOwnerRequestedBuffer(userOwner); numBuffersUsedOrReservedForOtherOwners += Math.max(numGuaranteed, numRequested); } } // Note that a sudden reduction in the size of the buffer pool may result in non-reclaimable // buffer memory occupying the guaranteed buffers of other users. However, this occurrence // is limited to the memory tier, which is only utilized when downstream registration is in // effect. Furthermore, the buffers within the memory tier can be recycled quickly enough, // thereby minimizing the impact on the guaranteed buffers of other tiers. return bufferPool.getNumBuffers() - numBuffersUsedOrReservedForOtherOwners; } @Override public boolean ensureCapacity(int numAdditionalBuffers) { checkIsInitialized(); final int numRequestedByGuaranteedReclaimableOwners = tieredMemorySpecs.values().stream() .filter(TieredStorageMemorySpec::isGuaranteedReclaimable) .mapToInt(spec -> numOwnerRequestedBuffer(spec.getOwner())) .sum(); while (bufferQueue.size() + numRequestedByGuaranteedReclaimableOwners < numGuaranteedReclaimableBuffers + numAdditionalBuffers) { if (numRequestedBuffers.get() >= bufferPool.getNumBuffers()) { return false; } MemorySegment memorySegment = requestBufferBlockingFromPool(); if (memorySegment == null) { return false; } bufferQueue.add(memorySegment); } return true; } @Override public int numOwnerRequestedBuffer(Object owner) { return numOwnerRequestedBuffers.getOrDefault(owner, 0); } @Override public void transferBufferOwnership(Object oldOwner, Object newOwner, Buffer buffer) { checkState(buffer.isBuffer(), "Only buffer supports transfer ownership."); decNumRequestedBuffer(oldOwner); incNumRequestedBuffer(newOwner); buffer.setRecycler(memorySegment -> recycleBuffer(newOwner, memorySegment)); } @Override public void release() { try { releasedStateLock.writeLock().lock(); isReleased = true; } finally { releasedStateLock.writeLock().unlock(); } if (executor != null) { executor.shutdown(); try { if (!executor.awaitTermination(5L, TimeUnit.MINUTES)) { throw new TimeoutException( "Timeout for shutting down the buffer reclaim checker executor."); } } catch (Exception e) { ExceptionUtils.rethrow(e); } } while (!bufferQueue.isEmpty()) { MemorySegment segment = bufferQueue.poll(); bufferPool.recycle(segment); numRequestedBuffers.decrementAndGet(); } } /** * @return a memory segment from the buffer pool or null if the memory manager has requested all * segments of the buffer pool. */ @Nullable private MemorySegment requestBufferBlockingFromPool() { MemorySegment memorySegment = null; hardBackpressureTimerGauge.markStart(); while (numRequestedBuffers.get() < bufferPool.getNumBuffers()) { memorySegment = bufferPool.requestMemorySegment(); if (memorySegment == null) { try { // Wait until a buffer is available or timeout before entering the next loop // iteration. bufferPool.getAvailableFuture().get(100, TimeUnit.MILLISECONDS); } catch (TimeoutException ignored) { } catch (Exception e) { ExceptionUtils.rethrow(e); } } else { numRequestedBuffers.incrementAndGet(); break; } } hardBackpressureTimerGauge.markEnd(); return memorySegment; } /** * @return a memory segment from the internal buffer queue. */ private MemorySegment requestBufferBlockingFromQueue() { CompletableFuture<Void> requestBufferFuture = new CompletableFuture<>(); scheduleCheckRequestBufferFuture( requestBufferFuture, INITIAL_REQUEST_BUFFER_TIMEOUT_FOR_RECLAIMING_MS); MemorySegment memorySegment = null; try { memorySegment = bufferQueue.take(); } catch (InterruptedException e) { ExceptionUtils.rethrow(e); } finally { requestBufferFuture.complete(null); } return memorySegment; } private void scheduleCheckRequestBufferFuture( CompletableFuture<Void> requestBufferFuture, long delayMs) { if (!mayReclaimBuffer || requestBufferFuture.isDone()) { return; } checkNotNull(executor) .schedule( // The delay time will be doubled after each check to avoid checking the // future too frequently. () -> internalCheckRequestBufferFuture(requestBufferFuture, delayMs * 2), delayMs, TimeUnit.MILLISECONDS); } private void internalCheckRequestBufferFuture( CompletableFuture<Void> requestBufferFuture, long delayForNextCheckMs) { if (requestBufferFuture.isDone()) { return; } reclaimBuffersIfNeeded(delayForNextCheckMs); scheduleCheckRequestBufferFuture(requestBufferFuture, delayForNextCheckMs); } private void incNumRequestedBuffer(Object owner) { numOwnerRequestedBuffers.compute( owner, (ignore, numRequested) -> numRequested == null ? 1 : numRequested + 1); } private void decNumRequestedBuffer(Object owner) { numOwnerRequestedBuffers.compute( owner, (ignore, numRequested) -> checkNotNull(numRequested) - 1); } private void reclaimBuffersIfNeeded(long delayForNextCheckMs) { if (shouldReclaimBuffersBeforeRequesting(delayForNextCheckMs)) { bufferReclaimRequestListeners.forEach(Runnable::run); } } private boolean shouldReclaimBuffersBeforeRequesting(long delayForNextCheckMs) { // The accuracy of the memory usage ratio may be compromised due to the varying buffer pool // sizes. However, this only impacts a single iteration of the buffer usage check. Upon the // next iteration, the buffer reclaim will eventually be triggered. int numTotal = bufferPool.getNumBuffers(); int numRequested = numRequestedBuffers.get(); // Because we do the checking before requesting buffers, we need add additional one // buffer when calculating the usage ratio. return (numRequested + 1 - bufferQueue.size()) * 1.0 / numTotal > numTriggerReclaimBuffersRatio || delayForNextCheckMs > MAX_DELAY_TIME_TO_TRIGGER_RECLAIM_BUFFER_MS && bufferQueue.size() == 0; } /** Note that this method may be called by the netty thread. */ private void recycleBuffer(Object owner, MemorySegment buffer) { try { releasedStateLock.readLock().lock(); if (!isReleased && numRequestedBuffers.get() <= bufferPool.getNumBuffers()) { bufferQueue.add(buffer); } else { bufferPool.recycle(buffer); numRequestedBuffers.decrementAndGet(); } } finally { releasedStateLock.readLock().unlock(); } decNumRequestedBuffer(owner); } private void checkIsInitialized() { checkState(isInitialized, "The memory manager is not in the running state."); } }
TieredStorageMemoryManagerImpl
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/InheritedTypeAssociationJoinedFetchTest.java
{ "start": 5557, "end": 5958 }
class ____ { @Id private Long id; @OneToOne( mappedBy = "zoo", fetch = FetchType.LAZY ) private Tiger tiger; @OneToMany( mappedBy = "zoo", fetch = FetchType.LAZY ) private List<Elephant> elephants; public Zoo() { } public Zoo(Long id) { this.id = id; } public Tiger getTiger() { return tiger; } public List<Elephant> getElephants() { return elephants; } } }
Zoo
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurer.java
{ "start": 7139, "end": 14680 }
class ____ { private OAuth2AuthorizationRequestResolver authorizationRequestResolver; private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository; private RedirectStrategy authorizationRedirectStrategy; private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient; private AuthorizationCodeGrantConfigurer() { } /** * Sets the resolver used for resolving {@link OAuth2AuthorizationRequest}'s. * @param authorizationRequestResolver the resolver used for resolving * {@link OAuth2AuthorizationRequest}'s * @return the {@link AuthorizationCodeGrantConfigurer} for further configuration */ public AuthorizationCodeGrantConfigurer authorizationRequestResolver( OAuth2AuthorizationRequestResolver authorizationRequestResolver) { Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null"); this.authorizationRequestResolver = authorizationRequestResolver; return this; } /** * Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s. * @param authorizationRequestRepository the repository used for storing * {@link OAuth2AuthorizationRequest}'s * @return the {@link AuthorizationCodeGrantConfigurer} for further configuration */ public AuthorizationCodeGrantConfigurer authorizationRequestRepository( AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) { Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null"); this.authorizationRequestRepository = authorizationRequestRepository; return this; } /** * Sets the redirect strategy for Authorization Endpoint redirect URI. * @param authorizationRedirectStrategy the redirect strategy * @return the {@link AuthorizationCodeGrantConfigurer} for further configuration */ public AuthorizationCodeGrantConfigurer authorizationRedirectStrategy( RedirectStrategy authorizationRedirectStrategy) { this.authorizationRedirectStrategy = authorizationRedirectStrategy; return this; } /** * Sets the client used for requesting the access token credential from the Token * Endpoint. * @param accessTokenResponseClient the client used for requesting the access * token credential from the Token Endpoint * @return the {@link AuthorizationCodeGrantConfigurer} for further configuration */ public AuthorizationCodeGrantConfigurer accessTokenResponseClient( OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) { Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null"); this.accessTokenResponseClient = accessTokenResponseClient; return this; } private void init(B builder) { OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider = new OAuth2AuthorizationCodeAuthenticationProvider( getAccessTokenResponseClient()); builder.authenticationProvider(postProcess(authorizationCodeAuthenticationProvider)); } private void configure(B builder) { OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter = createAuthorizationRequestRedirectFilter( builder); builder.addFilter(postProcess(authorizationRequestRedirectFilter)); OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = createAuthorizationCodeGrantFilter( builder); builder.addFilter(postProcess(authorizationCodeGrantFilter)); } private OAuth2AuthorizationRequestRedirectFilter createAuthorizationRequestRedirectFilter(B builder) { OAuth2AuthorizationRequestResolver resolver = getAuthorizationRequestResolver(); OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter = new OAuth2AuthorizationRequestRedirectFilter( resolver); if (this.authorizationRequestRepository != null) { authorizationRequestRedirectFilter .setAuthorizationRequestRepository(this.authorizationRequestRepository); } if (this.authorizationRedirectStrategy != null) { authorizationRequestRedirectFilter.setAuthorizationRedirectStrategy(this.authorizationRedirectStrategy); } RequestCache requestCache = builder.getSharedObject(RequestCache.class); if (requestCache != null) { authorizationRequestRedirectFilter.setRequestCache(requestCache); } return authorizationRequestRedirectFilter; } private OAuth2AuthorizationRequestResolver getAuthorizationRequestResolver() { if (this.authorizationRequestResolver != null) { return this.authorizationRequestResolver; } ClientRegistrationRepository clientRegistrationRepository = getClientRegistrationRepository(getBuilder()); ResolvableType resolvableType = ResolvableType.forClass(OAuth2AuthorizationRequestResolver.class); OAuth2AuthorizationRequestResolver bean = getBeanOrNull(resolvableType); return (bean != null) ? bean : new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI); } private OAuth2AuthorizationCodeGrantFilter createAuthorizationCodeGrantFilter(B builder) { AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class); OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = new OAuth2AuthorizationCodeGrantFilter( getClientRegistrationRepository(builder), getAuthorizedClientRepository(builder), authenticationManager); if (this.authorizationRequestRepository != null) { authorizationCodeGrantFilter.setAuthorizationRequestRepository(this.authorizationRequestRepository); } authorizationCodeGrantFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy()); RequestCache requestCache = builder.getSharedObject(RequestCache.class); if (requestCache != null) { authorizationCodeGrantFilter.setRequestCache(requestCache); } return authorizationCodeGrantFilter; } private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> getAccessTokenResponseClient() { if (this.accessTokenResponseClient != null) { return this.accessTokenResponseClient; } ResolvableType resolvableType = ResolvableType.forClassWithGenerics(OAuth2AccessTokenResponseClient.class, OAuth2AuthorizationCodeGrantRequest.class); OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> bean = getBeanOrNull(resolvableType); return (bean != null) ? bean : new RestClientAuthorizationCodeTokenResponseClient(); } private ClientRegistrationRepository getClientRegistrationRepository(B builder) { return (OAuth2ClientConfigurer.this.clientRegistrationRepository != null) ? OAuth2ClientConfigurer.this.clientRegistrationRepository : OAuth2ClientConfigurerUtils.getClientRegistrationRepository(builder); } private OAuth2AuthorizedClientRepository getAuthorizedClientRepository(B builder) { return (OAuth2ClientConfigurer.this.authorizedClientRepository != null) ? OAuth2ClientConfigurer.this.authorizedClientRepository : OAuth2ClientConfigurerUtils.getAuthorizedClientRepository(builder); } @SuppressWarnings("unchecked") private <T> T getBeanOrNull(ResolvableType type) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return null; } return (T) context.getBeanProvider(type).getIfUnique(); } } }
AuthorizationCodeGrantConfigurer
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client-jaxrs/runtime/src/main/java/io/quarkus/jaxrs/client/reactive/runtime/ParameterDescriptorFromClassSupplier.java
{ "start": 279, "end": 1743 }
class ____ implements Supplier<Map<String, ParameterDescriptorFromClassSupplier.ParameterDescriptor>> { private final Class clazz; private volatile Map<String, ParameterDescriptor> value; public ParameterDescriptorFromClassSupplier(Class clazz) { this.clazz = clazz; } @Override public Map<String, ParameterDescriptor> get() { if (value == null) { value = new HashMap<>(); Class currentClass = clazz; while (currentClass != null && currentClass != Object.class) { for (Field field : currentClass.getDeclaredFields()) { ParameterDescriptor descriptor = new ParameterDescriptor(); descriptor.annotations = field.getAnnotations(); descriptor.genericType = field.getGenericType(); value.put(field.getName(), descriptor); } for (Method method : currentClass.getDeclaredMethods()) { ParameterDescriptor descriptor = new ParameterDescriptor(); descriptor.annotations = method.getAnnotations(); descriptor.genericType = method.getGenericReturnType(); value.put(method.getName(), descriptor); } currentClass = currentClass.getSuperclass(); } } return value; } public static
ParameterDescriptorFromClassSupplier
java
dropwizard__dropwizard
dropwizard-auth/src/test/java/io/dropwizard/auth/basic/BasicAuthProviderTest.java
{ "start": 505, "end": 1824 }
class ____ extends AbstractAuthResourceConfig { public BasicAuthTestResourceConfig() { register(AuthResource.class); } @Override protected ContainerRequestFilter getAuthFilter() { BasicCredentialAuthFilter.Builder<Principal> builder = new BasicCredentialAuthFilter.Builder<>(); builder.setAuthorizer(AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE)); builder.setAuthenticator(AuthUtil.getBasicAuthenticator(Arrays.asList(ADMIN_USER, ORDINARY_USER))); return builder.buildAuthFilter(); } } @Override protected DropwizardResourceConfig getDropwizardResourceConfig() { return new BasicAuthTestResourceConfig(); } @Override protected Class<BasicAuthTestResourceConfig> getDropwizardResourceConfigClass() { return BasicAuthTestResourceConfig.class; } @Override protected String getPrefix() { return BASIC_PREFIX; } @Override protected String getOrdinaryGuyValidToken() { return ORDINARY_USER_ENCODED_TOKEN; } @Override protected String getGoodGuyValidToken() { return GOOD_USER_ENCODED_TOKEN; } @Override protected String getBadGuyToken() { return BAD_USER_ENCODED_TOKEN; } }
BasicAuthTestResourceConfig
java
apache__camel
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/KafkaConsumerFatalException.java
{ "start": 1219, "end": 1394 }
class ____ extends RuntimeException { public KafkaConsumerFatalException(String message, Throwable cause) { super(message, cause); } }
KafkaConsumerFatalException
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/cleaner/CleanerService.java
{ "start": 7678, "end": 8267 }
class ____ implements ExecutionScheduler { @Override public TimeValue nextExecutionDelay(ZonedDateTime now) { // Runs at 01:00 AM today or the next day if it's too late ZonedDateTime next = now.toLocalDate().atStartOfDay(now.getZone()).plusHours(1); // if it's not after now, then it needs to be the next day! if (next.isAfter(now) == false) { next = next.plusDays(1); } return TimeValue.timeValueMillis(Duration.between(now, next).toMillis()); } } }
DefaultExecutionScheduler
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/enums/EnumSameName4302Test.java
{ "start": 1011, "end": 2709 }
class ____ { public Field4302Enum wrapped; Field4302Wrapper() { } public Field4302Wrapper(Field4302Enum w) { wrapped = w; } } private final ObjectMapper MAPPER = jsonMapperBuilder() .propertyNamingStrategy(PropertyNamingStrategies.LOWER_CASE) .build(); @Test void testStandaloneShouldWork() throws Exception { // First, try roundtrip with same-ignore-case name field assertEquals(Field4302Enum.FOO, MAPPER.readValue("\"FOO\"", Field4302Enum.class)); assertEquals(q("FOO"), MAPPER.writeValueAsString(Field4302Enum.FOO)); // Now, try roundtrip with same-ignore-case name getter assertEquals(Getter4302Enum.BAR, MAPPER.readValue("\"BAR\"", Getter4302Enum.class)); assertEquals(q("BAR"), MAPPER.writeValueAsString(Getter4302Enum.BAR)); // Now, try roundtrip with same-ignore-case name setter Setter4302Enum.CAT.setCat("cat"); assertEquals(Setter4302Enum.CAT, MAPPER.readValue("\"CAT\"", Setter4302Enum.class)); assertEquals(q("CAT"), MAPPER.writeValueAsString(Setter4302Enum.CAT)); } @Test void testWrappedShouldWork() throws Exception { // First, try roundtrip with same-ignore-case name field Field4302Wrapper input = new Field4302Wrapper(Field4302Enum.FOO); String json = MAPPER.writeValueAsString(input); assertEquals(a2q("{'wrapped':'FOO'}"), json); Field4302Wrapper result = MAPPER.readValue(json, Field4302Wrapper.class); assertEquals(Field4302Enum.FOO, result.wrapped); } }
Field4302Wrapper
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/date/DateExtractConstantMillisEvaluator.java
{ "start": 1152, "end": 4307 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(DateExtractConstantMillisEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator value; private final ChronoField chronoField; private final ZoneId zone; private final DriverContext driverContext; private Warnings warnings; public DateExtractConstantMillisEvaluator(Source source, EvalOperator.ExpressionEvaluator value, ChronoField chronoField, ZoneId zone, DriverContext driverContext) { this.source = source; this.value = value; this.chronoField = chronoField; this.zone = zone; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock valueBlock = (LongBlock) value.eval(page)) { LongVector valueVector = valueBlock.asVector(); if (valueVector == null) { return eval(page.getPositionCount(), valueBlock); } return eval(page.getPositionCount(), valueVector).asBlock(); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += value.baseRamBytesUsed(); return baseRamBytesUsed; } public LongBlock eval(int positionCount, LongBlock valueBlock) { try(LongBlock.Builder result = driverContext.blockFactory().newLongBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (valueBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } long value = valueBlock.getLong(valueBlock.getFirstValueIndex(p)); result.appendLong(DateExtract.processMillis(value, this.chronoField, this.zone)); } return result.build(); } } public LongVector eval(int positionCount, LongVector valueVector) { try(LongVector.FixedBuilder result = driverContext.blockFactory().newLongVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { long value = valueVector.getLong(p); result.appendLong(p, DateExtract.processMillis(value, this.chronoField, this.zone)); } return result.build(); } } @Override public String toString() { return "DateExtractConstantMillisEvaluator[" + "value=" + value + ", chronoField=" + chronoField + ", zone=" + zone + "]"; } @Override public void close() { Releasables.closeExpectNoException(value); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
DateExtractConstantMillisEvaluator
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveResourceMethodEntriesBuildItem.java
{ "start": 498, "end": 707 }
class ____ method that correspond * to the JAX-RS Resource Method, giving extensions access to the entire set of metadata * thus allowing them to build additionally build-time functionality. */ public final
and
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/memory/PersistentMetadataCheckpointStorageLocation.java
{ "start": 1558, "end": 3287 }
class ____ extends MemCheckpointStreamFactory implements CheckpointStorageLocation { private final FileSystem fileSystem; private final Path checkpointDirectory; private final Path metadataFilePath; /** * Creates a checkpoint storage persists metadata to a file system and stores state in line in * state handles with the metadata. * * @param fileSystem The file system to which the metadata will be written. * @param checkpointDir The directory where the checkpoint metadata will be written. */ public PersistentMetadataCheckpointStorageLocation( FileSystem fileSystem, Path checkpointDir, int maxStateSize) { super(maxStateSize); this.fileSystem = checkNotNull(fileSystem); this.checkpointDirectory = checkNotNull(checkpointDir); this.metadataFilePath = new Path(checkpointDir, AbstractFsCheckpointStorageAccess.METADATA_FILE_NAME); } // ------------------------------------------------------------------------ @Override public CheckpointMetadataOutputStream createMetadataOutputStream() throws IOException { return new FsCheckpointMetadataOutputStream( fileSystem, metadataFilePath, checkpointDirectory); } @Override public void disposeOnFailure() throws IOException { // on a failure, no chunk in the checkpoint directory needs to be saved, so // we can drop it as a whole fileSystem.delete(checkpointDirectory, true); } @Override public CheckpointStorageLocationReference getLocationReference() { return CheckpointStorageLocationReference.getDefault(); } }
PersistentMetadataCheckpointStorageLocation
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/DirectIOCapableFlatVectorsFormat.java
{ "start": 985, "end": 2360 }
class ____ extends AbstractFlatVectorsFormat { protected DirectIOCapableFlatVectorsFormat(String name) { super(name); } protected abstract FlatVectorsReader createReader(SegmentReadState state) throws IOException; protected static boolean canUseDirectIO(SegmentReadState state) { return FsDirectoryFactory.isHybridFs(state.directory); } @Override public FlatVectorsReader fieldsReader(SegmentReadState state) throws IOException { return fieldsReader(state, false); } public FlatVectorsReader fieldsReader(SegmentReadState state, boolean useDirectIO) throws IOException { if (state.context.context() == IOContext.Context.DEFAULT && useDirectIO && canUseDirectIO(state)) { // only override the context for the random-access use case SegmentReadState directIOState = new SegmentReadState( state.directory, state.segmentInfo, state.fieldInfos, new DirectIOContext(state.context.hints()), state.segmentSuffix ); // Use mmap for merges and direct I/O for searches. return new MergeReaderWrapper(createReader(directIOState), createReader(state)); } else { return createReader(state); } } protected static
DirectIOCapableFlatVectorsFormat
java
apache__camel
components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/BoxComponentConfigurer.java
{ "start": 730, "end": 10979 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("ClientId", java.lang.String.class); map.put("Configuration", org.apache.camel.component.box.BoxConfiguration.class); map.put("EnterpriseId", java.lang.String.class); map.put("UserId", java.lang.String.class); map.put("BridgeErrorHandler", boolean.class); map.put("LazyStartProducer", boolean.class); map.put("AutowiredEnabled", boolean.class); map.put("HttpParams", java.util.Map.class); map.put("AuthenticationType", java.lang.String.class); map.put("AccessTokenCache", com.box.sdk.IAccessTokenCache.class); map.put("ClientSecret", java.lang.String.class); map.put("EncryptionAlgorithm", com.box.sdk.EncryptionAlgorithm.class); map.put("MaxCacheEntries", int.class); map.put("PrivateKeyFile", java.lang.String.class); map.put("PrivateKeyPassword", java.lang.String.class); map.put("PublicKeyId", java.lang.String.class); map.put("SslContextParameters", org.apache.camel.support.jsse.SSLContextParameters.class); map.put("UserName", java.lang.String.class); map.put("UserPassword", java.lang.String.class); ALL_OPTIONS = map; } private org.apache.camel.component.box.BoxConfiguration getOrCreateConfiguration(BoxComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.box.BoxConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { BoxComponent target = (BoxComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstokencache": case "accessTokenCache": getOrCreateConfiguration(target).setAccessTokenCache(property(camelContext, com.box.sdk.IAccessTokenCache.class, value)); return true; case "authenticationtype": case "authenticationType": getOrCreateConfiguration(target).setAuthenticationType(property(camelContext, java.lang.String.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "clientid": case "clientId": getOrCreateConfiguration(target).setClientId(property(camelContext, java.lang.String.class, value)); return true; case "clientsecret": case "clientSecret": getOrCreateConfiguration(target).setClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.box.BoxConfiguration.class, value)); return true; case "encryptionalgorithm": case "encryptionAlgorithm": getOrCreateConfiguration(target).setEncryptionAlgorithm(property(camelContext, com.box.sdk.EncryptionAlgorithm.class, value)); return true; case "enterpriseid": case "enterpriseId": getOrCreateConfiguration(target).setEnterpriseId(property(camelContext, java.lang.String.class, value)); return true; case "httpparams": case "httpParams": getOrCreateConfiguration(target).setHttpParams(property(camelContext, java.util.Map.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxcacheentries": case "maxCacheEntries": getOrCreateConfiguration(target).setMaxCacheEntries(property(camelContext, int.class, value)); return true; case "privatekeyfile": case "privateKeyFile": getOrCreateConfiguration(target).setPrivateKeyFile(property(camelContext, java.lang.String.class, value)); return true; case "privatekeypassword": case "privateKeyPassword": getOrCreateConfiguration(target).setPrivateKeyPassword(property(camelContext, java.lang.String.class, value)); return true; case "publickeyid": case "publicKeyId": getOrCreateConfiguration(target).setPublicKeyId(property(camelContext, java.lang.String.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": getOrCreateConfiguration(target).setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; case "userid": case "userId": getOrCreateConfiguration(target).setUserId(property(camelContext, java.lang.String.class, value)); return true; case "username": case "userName": getOrCreateConfiguration(target).setUserName(property(camelContext, java.lang.String.class, value)); return true; case "userpassword": case "userPassword": getOrCreateConfiguration(target).setUserPassword(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesstokencache": case "accessTokenCache": return com.box.sdk.IAccessTokenCache.class; case "authenticationtype": case "authenticationType": return java.lang.String.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "clientid": case "clientId": return java.lang.String.class; case "clientsecret": case "clientSecret": return java.lang.String.class; case "configuration": return org.apache.camel.component.box.BoxConfiguration.class; case "encryptionalgorithm": case "encryptionAlgorithm": return com.box.sdk.EncryptionAlgorithm.class; case "enterpriseid": case "enterpriseId": return java.lang.String.class; case "httpparams": case "httpParams": return java.util.Map.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "maxcacheentries": case "maxCacheEntries": return int.class; case "privatekeyfile": case "privateKeyFile": return java.lang.String.class; case "privatekeypassword": case "privateKeyPassword": return java.lang.String.class; case "publickeyid": case "publicKeyId": return java.lang.String.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; case "userid": case "userId": return java.lang.String.class; case "username": case "userName": return java.lang.String.class; case "userpassword": case "userPassword": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { BoxComponent target = (BoxComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstokencache": case "accessTokenCache": return getOrCreateConfiguration(target).getAccessTokenCache(); case "authenticationtype": case "authenticationType": return getOrCreateConfiguration(target).getAuthenticationType(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "clientid": case "clientId": return getOrCreateConfiguration(target).getClientId(); case "clientsecret": case "clientSecret": return getOrCreateConfiguration(target).getClientSecret(); case "configuration": return target.getConfiguration(); case "encryptionalgorithm": case "encryptionAlgorithm": return getOrCreateConfiguration(target).getEncryptionAlgorithm(); case "enterpriseid": case "enterpriseId": return getOrCreateConfiguration(target).getEnterpriseId(); case "httpparams": case "httpParams": return getOrCreateConfiguration(target).getHttpParams(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxcacheentries": case "maxCacheEntries": return getOrCreateConfiguration(target).getMaxCacheEntries(); case "privatekeyfile": case "privateKeyFile": return getOrCreateConfiguration(target).getPrivateKeyFile(); case "privatekeypassword": case "privateKeyPassword": return getOrCreateConfiguration(target).getPrivateKeyPassword(); case "publickeyid": case "publicKeyId": return getOrCreateConfiguration(target).getPublicKeyId(); case "sslcontextparameters": case "sslContextParameters": return getOrCreateConfiguration(target).getSslContextParameters(); case "userid": case "userId": return getOrCreateConfiguration(target).getUserId(); case "username": case "userName": return getOrCreateConfiguration(target).getUserName(); case "userpassword": case "userPassword": return getOrCreateConfiguration(target).getUserPassword(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "httpparams": case "httpParams": return java.lang.Object.class; default: return null; } } }
BoxComponentConfigurer
java
elastic__elasticsearch
libs/geo/src/main/java/org/elasticsearch/geometry/simplify/StreamingGeometrySimplifier.java
{ "start": 5021, "end": 8012 }
interface ____ { default PointError resetPoint(PointError point, int index, double x, double y) { return point.reset(index, x, y); } } private PointError makePointErrorFor(int index, double x, double y) { if (index == maxPoints) { if (lastRemoved == null) { this.objCount++; return pointConstructor.newPoint(index, x, y); } else { return pointResetter.resetPoint(lastRemoved, index, x, y); } } else { if (points[index] == null) { this.objCount++; return pointConstructor.newPoint(index, x, y); } else { return points[index] = pointResetter.resetPoint(points[index], index, x, y); } } } private void removeAndAdd(int toRemove, PointError pointError) { assert toRemove > 0; // priority queue can never include first point as that always has zero error by definition this.lastRemoved = this.points[toRemove]; // Shift all points to the right of the removed point over it in the array System.arraycopy(this.points, toRemove + 1, this.points, toRemove, maxPoints - toRemove - 1); // Add the new point to the end of the array this.points[length - 1] = pointError; // Reset all point indexes for points moved in the array for (int i = toRemove; i < length; i++) { points[i].index = i; } // Recalculate errors for points on either side of the removed point updateErrorAt(toRemove - 1); updateErrorAt(toRemove); // Update second last point error since we have a new last point if (toRemove < maxPoints - 1) { // if we removed the last point, we already updated it above, so don't bother here updateErrorAt(maxPoints - 2); } } private void updateErrorAt(int index) { if (index > 0 && index < length - 1) { // do not reset first and last points as they always have error 0 by definition double error = calculator.calculateError(points[index - 1], points[index], points[index + 1]); double delta = Math.abs(error - points[index].error); points[index].error = error; if (delta > 1e-10) { // If the error has changed, re-index the priority queue if (queue.remove(points[index])) { queue.add(points[index]); } } } } /** * Each point on the geometry has an error estimate, which is a measure of how much error would be introduced * to the geometry should this point be removed from the geometry. This is a measure of how far from the * line connecting the previous and next points, this geometry lies. If it is on that line, the error would * be zero, since removing the point does not change the geometry. */ public static
PointResetter
java
apache__hadoop
hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-blockgen/src/main/java/org/apache/hadoop/tools/dynamometer/blockgenerator/XMLParser.java
{ "start": 1346, "end": 2240 }
class ____ an fsimage file in XML format. It accepts the file * line-by-line and maintains an internal state machine to keep track of * contextual information. A single parser must process the entire file with the * lines in the order they appear in the original file. * * A file may be spread across multiple lines, so we need to track the * replication of the file we are currently processing to be aware of what the * replication factor is for each block we encounter. This is why we require a * single mapper. * * The format is illustrated below (line breaks for readability): * <pre>{@code * <inode><id>inode_ID<id/> <type>inode_type</type> * <replication>inode_replication</replication> [file attributes] <blocks> * <block><id>XXX</id><genstamp>XXX</genstamp><numBytes>XXX</numBytes><block/> * <blocks/> <inode/> * }</pre> * * This is true in both Hadoop 2 and 3. */
parses
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/ExtractUnit.java
{ "start": 628, "end": 1106 }
class ____ implements Expression, SqlAstNode { private final TemporalUnit unit; private final BasicValuedMapping type; public ExtractUnit(TemporalUnit unit, BasicValuedMapping type) { this.unit = unit; this.type = type; } public TemporalUnit getUnit() { return unit; } @Override public BasicValuedMapping getExpressionType() { return type; } @Override public void accept(SqlAstWalker sqlTreeWalker) { sqlTreeWalker.visitExtractUnit( this ); } }
ExtractUnit
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/utils/Base64Decode.java
{ "start": 765, "end": 4083 }
class ____ { private static final char[] BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); private static final int[] BASE64_IALPHABET = new int[256]; private static final int IALPHABET_MAX_INDEX = BASE64_IALPHABET.length - 1; private static final int[] IALPHABET = BASE64_IALPHABET; static { Arrays.fill(BASE64_IALPHABET, -1); for (int i = 0, iS = BASE64_ALPHABET.length; i < iS; i++) { BASE64_IALPHABET[BASE64_ALPHABET[i]] = i; } BASE64_IALPHABET['='] = 0; } /** * Decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme. * * @param input the string to decode * @return a byte array containing binary data */ public static byte[] decode(String input) { // Check special case if (input == null || input.equals("")) { return new byte[0]; } char[] sArr = input.toCharArray(); int sLen = sArr.length; if (sLen == 0) { return new byte[0]; } int sIx = 0; // Start and end index after trimming. int eIx = sLen - 1; // Trim illegal chars from start while (sIx < eIx && IALPHABET[sArr[sIx]] < 0) { sIx++; } // Trim illegal chars from end while (eIx > 0 && IALPHABET[sArr[eIx]] < 0) { eIx--; } // get the padding count (=) (0, 1 or 2) // Count '=' at end. int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Content count including possible separators int cCnt = eIx - sIx + 1; int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; // The number of decoded bytes int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // Preallocate byte[] of exact length byte[] dArr = new byte[len]; // Decode all but the last 0 - 2 bytes. int d = 0; int three = 3; int eight = 8; for (int cc = 0, eLen = (len / three) * three; d < eLen; ) { // Assemble three bytes into an int from four "valid" characters. int i = ctoi(sArr[sIx++]) << 18 | ctoi(sArr[sIx++]) << 12 | ctoi(sArr[sIx++]) << 6 | ctoi(sArr[sIx++]); // Add the bytes dArr[d++] = (byte) (i >> 16); dArr[d++] = (byte) (i >> 8); dArr[d++] = (byte) i; // If line separator, jump over it. if (sepCnt > 0 && ++cc == 19) { sIx += 2; cc = 0; } } if (d < len) { // Decode last 1-3 bytes (incl '=') into 1-3 bytes int i = 0; for (int j = 0; sIx <= eIx - pad; j++) { i |= ctoi(sArr[sIx++]) << (18 - j * 6); } for (int r = 16; d < len; r -= eight) { dArr[d++] = (byte) (i >> r); } } return dArr; } private static int ctoi(char c) { int i = c > IALPHABET_MAX_INDEX ? -1 : IALPHABET[c]; if (i < 0) { String msg = "Illegal base64 character: '" + c + "'"; throw new IllegalArgumentException(msg); } return i; } }
Base64Decode
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/derivedidentities/e4/a/FinancialHistory.java
{ "start": 448, "end": 716 }
class ____ implements Serializable { @Id //@JoinColumn(name = "FK") @ManyToOne Person patient; @Temporal(TemporalType.DATE) Date lastUpdate; public FinancialHistory() { } public FinancialHistory(Person patient) { this.patient = patient; } }
FinancialHistory
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMinBytesRefEvaluator.java
{ "start": 902, "end": 5385 }
class ____ extends AbstractMultivalueFunction.AbstractEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(MvMinBytesRefEvaluator.class); public MvMinBytesRefEvaluator(EvalOperator.ExpressionEvaluator field, DriverContext driverContext) { super(driverContext, field); } @Override public String name() { return "MvMin"; } /** * Evaluate blocks containing at least one multivalued field. */ @Override public Block evalNullable(Block fieldVal) { if (fieldVal.mvSortedAscending()) { return evalAscendingNullable(fieldVal); } BytesRefBlock v = (BytesRefBlock) fieldVal; int positionCount = v.getPositionCount(); try (BytesRefBlock.Builder builder = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) { BytesRef firstScratch = new BytesRef(); BytesRef nextScratch = new BytesRef(); for (int p = 0; p < positionCount; p++) { int valueCount = v.getValueCount(p); if (valueCount == 0) { builder.appendNull(); continue; } int first = v.getFirstValueIndex(p); int end = first + valueCount; BytesRef value = v.getBytesRef(first, firstScratch); for (int i = first + 1; i < end; i++) { BytesRef next = v.getBytesRef(i, nextScratch); MvMin.process(value, next); } BytesRef result = value; builder.appendBytesRef(result); } return builder.build(); } } /** * Evaluate blocks containing at least one multivalued field. */ @Override public Block evalNotNullable(Block fieldVal) { if (fieldVal.mvSortedAscending()) { return evalAscendingNotNullable(fieldVal); } BytesRefBlock v = (BytesRefBlock) fieldVal; int positionCount = v.getPositionCount(); try (BytesRefVector.Builder builder = driverContext.blockFactory().newBytesRefVectorBuilder(positionCount)) { BytesRef firstScratch = new BytesRef(); BytesRef nextScratch = new BytesRef(); for (int p = 0; p < positionCount; p++) { int valueCount = v.getValueCount(p); int first = v.getFirstValueIndex(p); int end = first + valueCount; BytesRef value = v.getBytesRef(first, firstScratch); for (int i = first + 1; i < end; i++) { BytesRef next = v.getBytesRef(i, nextScratch); MvMin.process(value, next); } BytesRef result = value; builder.appendBytesRef(result); } return builder.build().asBlock(); } } /** * Evaluate blocks containing at least one multivalued field and all multivalued fields are in ascending order. */ private Block evalAscendingNullable(Block fieldVal) { BytesRefBlock v = (BytesRefBlock) fieldVal; int positionCount = v.getPositionCount(); try (BytesRefBlock.Builder builder = driverContext.blockFactory().newBytesRefBlockBuilder(positionCount)) { BytesRef firstScratch = new BytesRef(); BytesRef nextScratch = new BytesRef(); for (int p = 0; p < positionCount; p++) { int valueCount = v.getValueCount(p); if (valueCount == 0) { builder.appendNull(); continue; } int first = v.getFirstValueIndex(p); int idx = MvMin.ascendingIndex(valueCount); BytesRef result = v.getBytesRef(first + idx, firstScratch); builder.appendBytesRef(result); } return builder.build(); } } /** * Evaluate blocks containing at least one multivalued field and all multivalued fields are in ascending order. */ private Block evalAscendingNotNullable(Block fieldVal) { BytesRefBlock v = (BytesRefBlock) fieldVal; int positionCount = v.getPositionCount(); try (BytesRefVector.Builder builder = driverContext.blockFactory().newBytesRefVectorBuilder(positionCount)) { BytesRef firstScratch = new BytesRef(); BytesRef nextScratch = new BytesRef(); for (int p = 0; p < positionCount; p++) { int valueCount = v.getValueCount(p); int first = v.getFirstValueIndex(p); int idx = MvMin.ascendingIndex(valueCount); BytesRef result = v.getBytesRef(first + idx, firstScratch); builder.appendBytesRef(result); } return builder.build().asBlock(); } } @Override public long baseRamBytesUsed() { return BASE_RAM_BYTES_USED + field.baseRamBytesUsed(); } public static
MvMinBytesRefEvaluator
java
quarkusio__quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/MethodLevelComputedPermissionsAllowedTest.java
{ "start": 13949, "end": 14838 }
class ____ extends Permission { private final boolean pass; public InheritancePermission(String name, Parent obj) { super(name); this.pass = obj != null && obj.shouldPass(); } @Override public boolean implies(Permission permission) { return pass; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InheritancePermission that = (InheritancePermission) o; return pass == that.pass; } @Override public int hashCode() { return Objects.hash(pass); } @Override public String getActions() { return null; } } public static
InheritancePermission
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/archive/ArchiveFeatureSetUsageTests.java
{ "start": 424, "end": 1472 }
class ____ extends AbstractWireSerializingTestCase<ArchiveFeatureSetUsage> { @Override protected ArchiveFeatureSetUsage createTestInstance() { boolean available = randomBoolean(); return new ArchiveFeatureSetUsage(available, randomIntBetween(0, 100000)); } @Override protected ArchiveFeatureSetUsage mutateInstance(ArchiveFeatureSetUsage instance) { boolean available = instance.available(); int numArchiveIndices = instance.getNumberOfArchiveIndices(); switch (between(0, 1)) { case 0 -> available = available == false; case 1 -> numArchiveIndices = randomValueOtherThan(numArchiveIndices, () -> randomIntBetween(0, 100000)); default -> throw new AssertionError("Illegal randomisation branch"); } return new ArchiveFeatureSetUsage(available, numArchiveIndices); } @Override protected Writeable.Reader<ArchiveFeatureSetUsage> instanceReader() { return ArchiveFeatureSetUsage::new; } }
ArchiveFeatureSetUsageTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/taobao/TradeTest.java
{ "start": 1139, "end": 1321 }
class ____<T> extends BaseObject { private static final long serialVersionUID = 669395861117027110L; public T min; public T max; } public static
Range
java
google__guava
android/guava-tests/benchmark/com/google/common/util/concurrent/MoreExecutorsDirectExecutorBenchmark.java
{ "start": 1817, "end": 3528 }
class ____ implements Runnable { AtomicInteger integer = new AtomicInteger(); @Override public void run() { integer.incrementAndGet(); } } CountingRunnable countingRunnable = new CountingRunnable(); Set<Thread> threads = new HashSet<>(); @BeforeExperiment void before() { executor = impl.executor(); for (int i = 0; i < 4; i++) { Thread thread = new Thread() { @Override public void run() { CountingRunnable localRunnable = new CountingRunnable(); while (!isInterrupted()) { executor.execute(localRunnable); } countingRunnable.integer.addAndGet(localRunnable.integer.get()); } }; threads.add(thread); } } @AfterExperiment void after() { for (Thread thread : threads) { thread.interrupt(); // try to get them to exit } threads.clear(); } @Footprint Object measureSize() { return executor; } @Benchmark int timeUncontendedExecute(int reps) { Executor executor = this.executor; CountingRunnable countingRunnable = this.countingRunnable; for (int i = 0; i < reps; i++) { executor.execute(countingRunnable); } return countingRunnable.integer.get(); } @Benchmark int timeContendedExecute(int reps) { Executor executor = this.executor; for (Thread thread : threads) { if (!thread.isAlive()) { thread.start(); } } CountingRunnable countingRunnable = this.countingRunnable; for (int i = 0; i < reps; i++) { executor.execute(countingRunnable); } return countingRunnable.integer.get(); } }
CountingRunnable
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/doublearrays/DoubleArrays_assertIsSortedAccordingToComparator_Test.java
{ "start": 1512, "end": 3892 }
class ____ extends DoubleArraysBaseTest { private Comparator<Double> doubleDescendingOrderComparator; private Comparator<Double> doubleSquareComparator; @Override @BeforeEach public void setUp() { super.setUp(); actual = new double[] { 4.0, 3.0, 2.0, 2.0, 1.0 }; doubleDescendingOrderComparator = (double1, double2) -> -double1.compareTo(double2); doubleSquareComparator = Comparator.comparing(aDouble -> aDouble * aDouble); } @Test void should_pass_if_actual_is_sorted_according_to_given_comparator() { arrays.assertIsSortedAccordingToComparator(someInfo(), actual, doubleDescendingOrderComparator); } @Test void should_pass_if_actual_is_empty_whatever_given_comparator_is() { arrays.assertIsSortedAccordingToComparator(someInfo(), emptyArray(), doubleDescendingOrderComparator); arrays.assertIsSortedAccordingToComparator(someInfo(), emptyArray(), doubleSquareComparator); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertIsSortedAccordingToComparator(someInfo(), null, doubleDescendingOrderComparator)) .withMessage(actualIsNull()); } @Test void should_fail_if_comparator_is_null() { assertThatNullPointerException().isThrownBy(() -> arrays.assertIsSortedAccordingToComparator(someInfo(), emptyArray(), null)); } @Test void should_fail_if_actual_is_not_sorted_according_to_given_comparator() { actual = new double[] { 3.0, 2.0, 1.0, 9.0 }; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertIsSortedAccordingToComparator(someInfo(), actual, doubleDescendingOrderComparator)) .withMessage(shouldBeSortedAccordingToGivenComparator(2, actual, doubleDescendingOrderComparator).create()); } }
DoubleArrays_assertIsSortedAccordingToComparator_Test
java
apache__camel
components/camel-github/src/test/java/org/apache/camel/component/github/consumer/EventConsumerWithStrategyTest.java
{ "start": 1584, "end": 3322 }
class ____ extends GitHubComponentTestBase { private CountDownLatch latch = new CountDownLatch(1); @BindToRegistry("strategy") private GitHubEventFetchStrategy strategy = new GitHubEventFetchStrategy() { @Override public PageIterator<Event> fetchEvents(EventService eventService) { latch.countDown(); return eventService.pageUserEvents("someguy"); } }; @Test public void customFetchStrategy() throws Exception { Event watchEvent = new Event(); watchEvent.setId("1"); watchEvent.setPayload(new WatchPayload()); watchEvent.setType("watchEvent"); eventService.addEvent(watchEvent); Event pushEvent = new Event(); pushEvent.setId("2"); pushEvent.setPayload(new PushPayload()); pushEvent.setType("pushEvent"); eventService.addEvent(pushEvent); Event issueCommentEvent = new Event(); issueCommentEvent.setId("3"); issueCommentEvent.setPayload(new IssueCommentPayload()); issueCommentEvent.setType("issueCommentEvent"); eventService.addEvent(issueCommentEvent); mockResultEndpoint.expectedBodiesReceivedInAnyOrder("watchEvent", "pushEvent", "issueCommentEvent"); latch.await(5, TimeUnit.SECONDS); mockResultEndpoint.assertIsSatisfied(5000); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("github:event?repoOwner=anotherguy&repoName=somerepo&eventFetchStrategy=#strategy") .to(mockResultEndpoint); } }; } }
EventConsumerWithStrategyTest
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/tls/letsencrypt/LetsEncryptFlowTestBase.java
{ "start": 1096, "end": 9584 }
class ____ { static final File SELF_SIGNED_CERT = new File("target/certs/lets-encrypt/self-signed.crt"); static final File SELF_SIGNED_KEY = new File("target/certs/lets-encrypt/self-signed.key"); static final File SELF_SIGNED_CA = new File("target/certs/lets-encrypt/self-signed-ca.crt"); static final File ACME_CERT = new File("target/certs/lets-encrypt/acme.crt"); static final File ACME_KEY = new File("target/certs/lets-encrypt/acme.key"); static final File ACME_CA = new File("target/certs/lets-encrypt/acme-ca.crt"); private Vertx vertx; private String tlsConfigurationName; static <T> T await(Future<T> future) { return future.toCompletionStage().toCompletableFuture().join(); } public void initFlow(Vertx vertx, String tlsConfigurationName) { this.vertx = vertx; this.tlsConfigurationName = tlsConfigurationName; } abstract void updateCerts() throws IOException; abstract String getApplicationEndpoint(); abstract String getLetsEncryptManagementEndpoint(); abstract String getLetsEncryptCertsEndpoint(); abstract String getChallengeEndpoint(); void testLetsEncryptFlow() throws IOException { WebClientOptions options = new WebClientOptions().setSsl(true) .setTrustOptions(new PemTrustOptions().addCertPath(SELF_SIGNED_CA.getAbsolutePath())); WebClient client = WebClient.create(vertx, options); String readyEndpoint = getLetsEncryptManagementEndpoint(); if (tlsConfigurationName != null) { readyEndpoint = readyEndpoint + "?key=" + tlsConfigurationName; } String reloadEndpoint = getLetsEncryptCertsEndpoint(); if (tlsConfigurationName != null) { reloadEndpoint = reloadEndpoint + "?key=" + tlsConfigurationName; } // Verify the application is serving the application HttpResponse<Buffer> response = await(client.getAbs(getApplicationEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(200); String body = response.bodyAsString(); // We will need it later. // Verify if the application is ready to serve the challenge response = await(client.getAbs(readyEndpoint).send()); Assertions.assertThat(response.statusCode()).isEqualTo(204); // Make sure invalid tokens are rejected response = await(client.postAbs(getLetsEncryptManagementEndpoint()).sendJsonObject( new JsonObject())); Assertions.assertThat(response.statusCode()).isEqualTo(400); response = await(client.postAbs(getLetsEncryptManagementEndpoint()).sendJsonObject( new JsonObject() .put("challenge-content", "aaa"))); Assertions.assertThat(response.statusCode()).isEqualTo(400); response = await(client.postAbs(getLetsEncryptManagementEndpoint()).sendJsonObject( new JsonObject() .put("challenge-resource", "aaa"))); Assertions.assertThat(response.statusCode()).isEqualTo(400); // Set the challenge String challengeContent = UUID.randomUUID().toString(); String challengeToken = UUID.randomUUID().toString(); response = await(client.postAbs(getLetsEncryptManagementEndpoint()).sendJsonObject( new JsonObject() .put("challenge-content", challengeContent) .put("challenge-resource", challengeToken))); Assertions.assertThat(response.statusCode()).isEqualTo(204); // Verify that the challenge is set response = await(client.getAbs(readyEndpoint).send()); Assertions.assertThat(response.statusCode()).isEqualTo(200); Assertions.assertThat(response.bodyAsJsonObject()).isEqualTo(new JsonObject() .put("challenge-content", challengeContent) .put("challenge-resource", challengeToken)); // Make sure the challenge cannot be set again response = await(client.postAbs(getLetsEncryptManagementEndpoint()).sendJsonObject( new JsonObject().put("challenge-resource", "again").put("challenge-content", "again"))); Assertions.assertThat(response.statusCode()).isEqualTo(400); // Verify that the let's encrypt management endpoint only support GET, POST and DELETE // Make sure the challenge cannot be set again response = await(client.patchAbs(getLetsEncryptManagementEndpoint()).sendBuffer(Buffer.buffer("again"))); Assertions.assertThat(response.statusCode()).isEqualTo(405); // Verify that the application is serving the challenge response = await(client.getAbs(getChallengeEndpoint() + "/" + challengeToken).send()); Assertions.assertThat(response.statusCode()).isEqualTo(200); Assertions.assertThat(response.bodyAsString()).isEqualTo(challengeContent); // Verify that other path and token are not valid response = await(client.getAbs(getChallengeEndpoint() + "/" + "whatever").send()); Assertions.assertThat(response.statusCode()).isEqualTo(404); response = await(client.getAbs(getChallengeEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(404); // Verify that only GET is supported when serving the challenge response = await(client.postAbs(getChallengeEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(405); response = await(client.deleteAbs(getChallengeEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(405); response = await(client.postAbs(getChallengeEndpoint() + "/" + challengeToken).send()); Assertions.assertThat(response.statusCode()).isEqualTo(405); response = await(client.deleteAbs(getChallengeEndpoint() + "/" + challengeToken).send()); Assertions.assertThat(response.statusCode()).isEqualTo(405); // Verify that the challenge can be served multiple times response = await(client.getAbs(getChallengeEndpoint() + "/" + challengeToken).send()); Assertions.assertThat(response.statusCode()).isEqualTo(200); Assertions.assertThat(response.bodyAsString()).isEqualTo(challengeContent); // Replace the certs on disk updateCerts(); // Clear the challenge response = await(client.deleteAbs(getLetsEncryptManagementEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(204); // Check we cannot clear the challenge again response = await(client.deleteAbs(getLetsEncryptManagementEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(404); // Check we cannot retrieve the challenge again response = await(client.getAbs(getChallengeEndpoint()).send()); Assertions.assertThat(response.statusCode()).isEqualTo(404); // Reload the certificate response = await(client.postAbs(reloadEndpoint).send()); Assertions.assertThat(response.statusCode()).isEqualTo(204); // Verify that reload cannot be call with other verb response = await(client.getAbs(reloadEndpoint).send()); Assertions.assertThat(response.statusCode()).isEqualTo(405); // Verify the application is serving the new certificate // We should not use the WebClient as the connection are still established with the old certificate. URL url = new URL(getApplicationEndpoint()); assertThatThrownBy(() -> vertx.createHttpClient( new HttpClientOptions().setSsl(true).setDefaultPort(url.getPort()) .setTrustOptions(new PemTrustOptions().addCertPath(SELF_SIGNED_CA.getAbsolutePath()))) .request(HttpMethod.GET, "/tls") .flatMap(HttpClientRequest::send) .flatMap(HttpClientResponse::body) .map(Buffer::toString) .toCompletionStage().toCompletableFuture().join()).hasCauseInstanceOf(SSLHandshakeException.class); WebClient newWebClient = WebClient.create(vertx, options.setTrustOptions(new PemTrustOptions().addCertPath(ACME_CA.getAbsolutePath()))); String newBody = await(newWebClient.getAbs(url.toString()).send()).bodyAsString(); Assertions.assertThat(newBody).isNotEqualTo(body); } @ApplicationScoped public static
LetsEncryptFlowTestBase
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/role/RestPutRoleActionTests.java
{ "start": 1184, "end": 2508 }
class ____ extends ESTestCase { public void testFailureWhenNativeRolesDisabled() throws Exception { final Settings securityDisabledSettings = Settings.builder().put(NativeRolesStore.NATIVE_ROLES_ENABLED, false).build(); final XPackLicenseState licenseState = mock(XPackLicenseState.class); when(licenseState.getOperationMode()).thenReturn(License.OperationMode.BASIC); final RestPutRoleAction action = new RestPutRoleAction(securityDisabledSettings, licenseState, mock()); final FakeRestRequest request = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY) // .withParams(Map.of("name", "dice")) .withContent(new BytesArray("{ }"), XContentType.JSON) .build(); final FakeRestChannel channel = new FakeRestChannel(request, true, 1); try (var threadPool = createThreadPool()) { final var nodeClient = new NoOpNodeClient(threadPool); action.handleRequest(request, channel, nodeClient); } assertThat(channel.capturedResponse(), notNullValue()); assertThat(channel.capturedResponse().status(), equalTo(RestStatus.GONE)); assertThat(channel.capturedResponse().content().utf8ToString(), containsString("Native role management is not enabled")); } }
RestPutRoleActionTests
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/security/ContainerTokenSelector.java
{ "start": 1271, "end": 2042 }
class ____ implements TokenSelector<ContainerTokenIdentifier> { private static final Logger LOG = LoggerFactory .getLogger(ContainerTokenSelector.class); @SuppressWarnings("unchecked") @Override public Token<ContainerTokenIdentifier> selectToken(Text service, Collection<Token<? extends TokenIdentifier>> tokens) { if (service == null) { return null; } for (Token<? extends TokenIdentifier> token : tokens) { LOG.debug("Looking for service: {}. Current token is {}", service, token); if (ContainerTokenIdentifier.KIND.equals(token.getKind()) && service.equals(token.getService())) { return (Token<ContainerTokenIdentifier>) token; } } return null; } }
ContainerTokenSelector
java
elastic__elasticsearch
x-pack/plugin/repositories-metering-api/src/main/java/org/elasticsearch/xpack/repositories/metering/action/RepositoriesMeteringAction.java
{ "start": 375, "end": 711 }
class ____ extends ActionType<RepositoriesMeteringResponse> { public static final RepositoriesMeteringAction INSTANCE = new RepositoriesMeteringAction(); static final String NAME = "cluster:monitor/xpack/repositories_metering/get_metrics"; RepositoriesMeteringAction() { super(NAME); } }
RepositoriesMeteringAction
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/streaming/api/FileReadingWatermarkITCase.java
{ "start": 1924, "end": 4560 }
class ____ extends TestLogger { private static final Logger LOG = LoggerFactory.getLogger(FileReadingWatermarkITCase.class); private static final int WATERMARK_INTERVAL_MILLIS = 1_000; private static final int EXPECTED_WATERMARKS = 5; @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public final SharedObjects sharedObjects = SharedObjects.create(); /** * Adds an infinite split that causes the input of {@link * org.apache.flink.streaming.api.functions.source.ContinuousFileReaderOperator} to instantly go * idle while data is still being processed. * * <p>Before FLINK-19109, watermarks would not be emitted at this point. */ @Test public void testWatermarkEmissionWithChaining() throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(1); env.getConfig().setAutoWatermarkInterval(WATERMARK_INTERVAL_MILLIS); SharedReference<CountDownLatch> latch = sharedObjects.add(new CountDownLatch(EXPECTED_WATERMARKS)); checkState(env.isChainingEnabled()); env.createInput(new InfiniteIntegerInputFormat(true)) .assignTimestampsAndWatermarks( WatermarkStrategy.<Integer>forMonotonousTimestamps() .withTimestampAssigner(context -> getExtractorAssigner())) .addSink(getWatermarkCounter(latch)); env.executeAsync(); latch.get().await(); } private static TimestampAssigner<Integer> getExtractorAssigner() { return new TimestampAssigner<Integer>() { private long counter = 1; @Override public long extractTimestamp(Integer element, long recordTimestamp) { return counter++; } }; } private static SinkFunction<Integer> getWatermarkCounter( final SharedReference<CountDownLatch> latch) { return new RichSinkFunction<Integer>() { @Override public void invoke(Integer value, SinkFunction.Context context) { try { Thread.sleep(1000); LOG.info("Sink received record"); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Override public void writeWatermark(Watermark watermark) { LOG.info("Sink received watermark {}", watermark); latch.get().countDown(); } }; } }
FileReadingWatermarkITCase
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/ProjectBuilderRequest.java
{ "start": 8790, "end": 12013 }
class ____ extends BaseRequest<Session> implements ProjectBuilderRequest { private final Path path; private final Source source; private final boolean allowStubModel; private final boolean recursive; private final boolean processPlugins; private final List<RemoteRepository> repositories; @SuppressWarnings("checkstyle:ParameterNumber") DefaultProjectBuilderRequest( @Nonnull Session session, @Nullable RequestTrace trace, @Nullable Path path, @Nullable Source source, boolean allowStubModel, boolean recursive, boolean processPlugins, @Nullable List<RemoteRepository> repositories) { super(session, trace); this.path = path; this.source = source; this.allowStubModel = allowStubModel; this.recursive = recursive; this.processPlugins = processPlugins; this.repositories = validate(repositories); } @Nonnull @Override public Optional<Path> getPath() { return Optional.ofNullable(path); } @Nonnull @Override public Optional<Source> getSource() { return Optional.ofNullable(source); } @Override public boolean isAllowStubModel() { return allowStubModel; } @Override public boolean isRecursive() { return recursive; } @Override public boolean isProcessPlugins() { return processPlugins; } @Override public List<RemoteRepository> getRepositories() { return repositories; } @Override public boolean equals(Object o) { return o instanceof DefaultProjectBuilderRequest that && allowStubModel == that.allowStubModel && recursive == that.recursive && processPlugins == that.processPlugins && Objects.equals(path, that.path) && Objects.equals(source, that.source) && Objects.equals(repositories, that.repositories); } @Override public int hashCode() { return Objects.hash(path, source, allowStubModel, recursive, processPlugins, repositories); } @Override public String toString() { return "ProjectBuilderRequest[" + "path=" + path + ", source=" + source + ", allowStubModel=" + allowStubModel + ", recursive=" + recursive + ", processPlugins=" + processPlugins + ", repositories=" + repositories + ']'; } } } }
DefaultProjectBuilderRequest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localtime/LocalTimeAssert_isStrictlyBetween_with_String_parameters_Test.java
{ "start": 979, "end": 2192 }
class ____ extends org.assertj.core.api.LocalTimeAssertBaseTest { private LocalTime before = now.minusSeconds(1); private LocalTime after = now.plusSeconds(1); @Override protected LocalTimeAssert invoke_api_method() { return assertions.isStrictlyBetween(before.toString(), after.toString()); } @Override protected void verify_internal_effects() { verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), before, after, false, false); } @Test void should_throw_a_DateTimeParseException_if_start_String_parameter_cant_be_converted() { // GIVEN String abc = "abc"; // WHEN Throwable thrown = catchThrowable(() -> assertions.isStrictlyBetween(abc, after.toString())); // THEN assertThat(thrown).isInstanceOf(DateTimeParseException.class); } @Test void should_throw_a_DateTimeParseException_if_end_String_parameter_cant_be_converted() { // GIVEN String abc = "abc"; // WHEN Throwable thrown = catchThrowable(() -> assertions.isStrictlyBetween(before.toString(), abc)); // THEN assertThat(thrown).isInstanceOf(DateTimeParseException.class); } }
LocalTimeAssert_isStrictlyBetween_with_String_parameters_Test
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PutTrainedModelDefinitionPartAction.java
{ "start": 7333, "end": 8228 }
class ____ { private BytesReference definition; private long totalDefinitionLength; private int totalParts; public Builder setDefinition(byte[] definition) { this.definition = new BytesArray(definition); return this; } public Builder setTotalDefinitionLength(long totalDefinitionLength) { this.totalDefinitionLength = totalDefinitionLength; return this; } public Builder setTotalParts(int totalParts) { this.totalParts = totalParts; return this; } public Request build(String modelId, int part, boolean allowOverwriting) { return new Request(modelId, definition, part, totalDefinitionLength, totalParts, allowOverwriting); } } } }
Builder
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/lob/LargeObjectMappingTest.java
{ "start": 1076, "end": 1142 }
class ____ { @Entity @Audited public static
LargeObjectMappingTest
java
google__guava
android/guava/src/com/google/common/primitives/Longs.java
{ "start": 1853, "end": 11838 }
class ____ { private Longs() {} /** * The number of bytes required to represent a primitive {@code long} value. * * <p>Prefer {@link Long#BYTES} instead. */ public static final int BYTES = Long.BYTES; /** * The largest power of two that can be represented as a {@code long}. * * @since 10.0 */ public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns a hash code for {@code value}; obsolete alternative to {@link Long#hashCode(long)}. * * @param value a primitive {@code long} value * @return a hash code for the value */ @InlineMe(replacement = "Long.hashCode(value)") public static int hashCode(long value) { return Long.hashCode(value); } /** * Compares the two specified {@code long} values. The sign of the value returned is the same as * that of {@code ((Long) a).compareTo(b)}. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the * equivalent {@link Long#compare} method instead. * * @param a the first {@code long} to compare * @param b the second {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ @InlineMe(replacement = "Long.compare(a, b)") public static int compare(long a, long b) { return Long.compare(a, b); } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(long[] array, long target) { for (long value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(long[] array, long target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(long[] array, long target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(long[] array, long[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(long[] array, long target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(long[] array, long target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. * * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code * value} is greater than {@code max}, {@code max} is returned. * * <p><b>Java 21+ users:</b> Use {@code Math.clamp} instead. Note that that method is capable of * constraining a {@code long} input to an {@code int} range. * * @param value the {@code long} value to constrain * @param min the lower bound (inclusive) of the range to constrain {@code value} to * @param max the upper bound (inclusive) of the range to constrain {@code value} to * @throws IllegalArgumentException if {@code min > max} * @since 21.0 */ public static long constrainToRange(long value, long min, long max) { checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); return Math.min(Math.max(value, min), max); } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code long} arrays * @return a single array containing all the values from the source arrays, in order * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit * in an {@code int} */ public static long[] concat(long[]... arrays) { long length = 0; for (long[] array : arrays) { length += array.length; } long[] result = new long[checkNoOverflow(length)]; int pos = 0; for (long[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static int checkNoOverflow(long result) { checkArgument( result == (int) result, "the total number of elements (%s) in the arrays must fit in an int", result); return (int) result; } /** * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code * 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, * 0x18, 0x19}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use {@link * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ public static byte[] toByteArray(long value) { // Note that this code needs to stay compatible with GWT, which has known // bugs when narrowing byte casts of long values occur. byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte) (value & 0xffL); value >>= 8; } return result; } /** * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the * {@code long} value {@code 0x1213141516171819L}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more * flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements */ public static long fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes( bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]); } /** * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. * * @since 7.0 */ public static long fromBytes( byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); } /* * Moving asciiDigits into this static holder
Longs
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/streams/IteratorTest.java
{ "start": 3632, "end": 6598 }
class ____ implements ReadStream<Integer> { private Handler<Integer> handler; private Handler<Void> endHandler; private long demand = Long.MAX_VALUE; private final Lock lock = new ReentrantLock(); private final Condition producerSignal = lock.newCondition(); @Override public ReadStream<Integer> exceptionHandler(Handler<Throwable> handler) { return this; } public void write(Integer element) throws InterruptedException { lock.lock(); Handler<Integer> h; try { while (true) { long d = demand; if (d > 0L) { if (d != Long.MAX_VALUE) { demand = d - 1; } h = handler; break; } else { producerSignal.await(); } } } finally { lock.unlock(); } if (h != null) { h.handle(element); } } public void end() throws InterruptedException { lock.lock(); Handler<Void> h; try { while (true) { long d = demand; if (d > 0L) { h = endHandler; break; } else { producerSignal.await(); } } } finally { lock.unlock(); } if (h != null) { h.handle(null); } } @Override public ReadStream<Integer> handler(Handler<Integer> handler) { lock.lock(); try { this.handler = handler; } finally { lock.unlock(); } return this; } @Override public ReadStream<Integer> endHandler(Handler<Void> endHandler) { lock.lock(); try { this.endHandler = endHandler; } finally { lock.unlock(); } return this; } @Override public ReadStream<Integer> pause() { lock.lock(); try { demand = 0L; } finally { lock.unlock(); } return this; } @Override public ReadStream<Integer> resume() { return fetch(Long.MAX_VALUE); } @Override public ReadStream<Integer> fetch(long amount) { if (amount < 0L) { throw new IllegalArgumentException(); } if (amount > 0L) { lock.lock(); try { long d = demand; d += amount; if (d < 0L) { d = Long.MAX_VALUE; } demand = d; producerSignal.signal(); } finally { lock.unlock(); } } return this; } } Stream stream = new Stream(); Iterator<Integer> iterator = ReadStreamIterator.iterator(stream); int numThreads = 8; int numElements = 16384; CyclicBarrier barrier = new CyclicBarrier(numThreads + 1);
Stream
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/stereotypes/StereotypeAlternativeTest.java
{ "start": 2316, "end": 2482 }
class ____ extends NonAlternative { @Override public String getId() { return "OK"; } } @Dependent static
IamAlternative
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java
{ "start": 27721, "end": 31189 }
class ____ implements BeanFactoryInitializationAotContribution { private static final String BEAN_FACTORY_VARIABLE = BeanFactoryInitializationCode.BEAN_FACTORY_VARIABLE; private static final ParameterizedTypeName STRING_STRING_MAP = ParameterizedTypeName.get(Map.class, String.class, String.class); private static final String MAPPINGS_VARIABLE = "mappings"; private static final String BEAN_DEFINITION_VARIABLE = "beanDefinition"; private static final String BEAN_NAME = "org.springframework.context.annotation.internalImportAwareAotProcessor"; private final ConfigurableListableBeanFactory beanFactory; public ImportAwareAotContribution(ConfigurableListableBeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public void applyTo(GenerationContext generationContext, BeanFactoryInitializationCode beanFactoryInitializationCode) { Map<String, String> mappings = buildImportAwareMappings(); if (!mappings.isEmpty()) { GeneratedMethod generatedMethod = beanFactoryInitializationCode.getMethods().add( "addImportAwareBeanPostProcessors", method -> generateAddPostProcessorMethod(method, mappings)); beanFactoryInitializationCode.addInitializer(generatedMethod.toMethodReference()); ResourceHints hints = generationContext.getRuntimeHints().resources(); mappings.forEach((target, from) -> hints.registerType(TypeReference.of(from))); } } private void generateAddPostProcessorMethod(MethodSpec.Builder method, Map<String, String> mappings) { method.addJavadoc("Add ImportAwareBeanPostProcessor to support ImportAware beans."); method.addModifiers(Modifier.PRIVATE); method.addParameter(DefaultListableBeanFactory.class, BEAN_FACTORY_VARIABLE); method.addCode(generateAddPostProcessorCode(mappings)); } private CodeBlock generateAddPostProcessorCode(Map<String, String> mappings) { CodeBlock.Builder code = CodeBlock.builder(); code.addStatement("$T $L = new $T<>()", STRING_STRING_MAP, MAPPINGS_VARIABLE, HashMap.class); mappings.forEach((type, from) -> code.addStatement("$L.put($S, $S)", MAPPINGS_VARIABLE, type, from)); code.addStatement("$T $L = new $T($T.class)", RootBeanDefinition.class, BEAN_DEFINITION_VARIABLE, RootBeanDefinition.class, ImportAwareAotBeanPostProcessor.class); code.addStatement("$L.setRole($T.ROLE_INFRASTRUCTURE)", BEAN_DEFINITION_VARIABLE, BeanDefinition.class); code.addStatement("$L.setInstanceSupplier(() -> new $T($L))", BEAN_DEFINITION_VARIABLE, ImportAwareAotBeanPostProcessor.class, MAPPINGS_VARIABLE); code.addStatement("$L.registerBeanDefinition($S, $L)", BEAN_FACTORY_VARIABLE, BEAN_NAME, BEAN_DEFINITION_VARIABLE); return code.build(); } private Map<String, String> buildImportAwareMappings() { ImportRegistry importRegistry = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class); Map<String, String> mappings = new LinkedHashMap<>(); for (String name : this.beanFactory.getBeanDefinitionNames()) { Class<?> beanType = this.beanFactory.getType(name); if (beanType != null && ImportAware.class.isAssignableFrom(beanType)) { String target = ClassUtils.getUserClass(beanType).getName(); AnnotationMetadata from = importRegistry.getImportingClassFor(target); if (from != null) { mappings.put(target, from.getClassName()); } } } return mappings; } } private static
ImportAwareAotContribution
java
apache__camel
components/camel-mail/src/test/java/org/apache/camel/component/mail/MailBindingAttachmentDuplicateFileNameTest.java
{ "start": 1324, "end": 3796 }
class ____ { private final MailBinding binding = new MailBinding(); @Test public void shouldFailOnDuplicateFilenames() throws Exception { binding.setFailOnDuplicateAttachment(true); final Session session = Session.getInstance(new Properties()); final Message message = new MimeMessage(session); String filename = "file.txt"; String filename2 = "file.txt"; setAttachments(message, filename, filename2); extractAttachmentsAndValidate(message, filename, filename2); filename = "file.txt"; filename2 = "../file.txt"; setAttachments(message, filename, filename2); extractAttachmentsAndValidate(message, filename, filename2); filename = "file.txt"; filename2 = "..\\file.txt"; setAttachments(message, filename, filename2); extractAttachmentsAndValidate(message, filename, filename2); filename = "file.txt"; filename2 = "/absolute/file.txt"; setAttachments(message, filename, filename2); extractAttachmentsAndValidate(message, filename, filename2); filename = "file.txt"; filename2 = "c:\\absolute\\file.txt"; setAttachments(message, filename, filename2); extractAttachmentsAndValidate(message, filename, filename2); filename = "..\\file.txt"; filename2 = "c:\\absolute\\file.txt"; setAttachments(message, filename, filename2); extractAttachmentsAndValidate(message, filename, filename2); } private void extractAttachmentsAndValidate(Message message, String filename, String filename2) throws Exception { MessagingException thrown; setAttachments(message, filename, filename2); thrown = assertThrows(MessagingException.class, () -> binding.extractAttachmentsFromMail(message, new HashMap<>()), "Duplicate attachment names should cause an exception"); assertTrue(thrown.getMessage().contains("Duplicate file attachment")); } private void setAttachments(Message message, String name1, String name2) throws Exception { Multipart multipart = new MimeMultipart(); MimeBodyPart part = new MimeBodyPart(); part.attachFile(name1); multipart.addBodyPart(part); part = new MimeBodyPart(); part.attachFile(name2); multipart.addBodyPart(part); message.setContent(multipart); } }
MailBindingAttachmentDuplicateFileNameTest
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstanceFactoryTests.java
{ "start": 2856, "end": 12531 }
class ____ extends AbstractJupiterTestEngineTests { private static final List<String> callSequence = new ArrayList<>(); @BeforeEach void resetCallSequence() { callSequence.clear(); } @Test void multipleFactoriesRegisteredOnSingleTestClass() { Class<?> testClass = MultipleFactoriesRegisteredOnSingleTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(0, executionResults.testEvents().started().count(), "# tests started"); assertEquals(0, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(container(testClass), finishedWithFailure(instanceOf(ExtensionConfigurationException.class), message("The following TestInstanceFactory extensions were registered for test class [" + testClass.getName() + "], but only one is permitted: " + nullSafeToString(FooInstanceFactory.class, BarInstanceFactory.class)))), // event(engine(), finishedSuccessfully())); } @Test void multipleFactoriesRegisteredWithinTestClassHierarchy() { Class<?> testClass = MultipleFactoriesRegisteredWithinClassHierarchyTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(0, executionResults.testEvents().started().count(), "# tests started"); assertEquals(0, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(container(testClass), finishedWithFailure(instanceOf(ExtensionConfigurationException.class), message("The following TestInstanceFactory extensions were registered for test class [" + testClass.getName() + "], but only one is permitted: " + nullSafeToString(FooInstanceFactory.class, BarInstanceFactory.class)))), // event(engine(), finishedSuccessfully())); } @Test void multipleFactoriesRegisteredWithinNestedClassStructure() { Class<?> outerClass = MultipleFactoriesRegisteredWithinNestedClassStructureTestCase.class; Class<?> nestedClass = MultipleFactoriesRegisteredWithinNestedClassStructureTestCase.InnerTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(outerClass); assertEquals(1, executionResults.testEvents().started().count(), "# tests started"); assertEquals(1, executionResults.testEvents().succeeded().count(), "# tests succeeded"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(outerClass), started()), // event(test("outerTest()"), started()), // event(test("outerTest()"), finishedSuccessfully()), // event(nestedContainer(nestedClass), started()), // event(nestedContainer(nestedClass), finishedWithFailure(instanceOf(ExtensionConfigurationException.class), message("The following TestInstanceFactory extensions were registered for test class [" + nestedClass.getName() + "], but only one is permitted: " + nullSafeToString(FooInstanceFactory.class, BarInstanceFactory.class)))), // event(container(outerClass), finishedSuccessfully()), // event(engine(), finishedSuccessfully())); } @Test void nullTestInstanceFactoryWithPerMethodLifecycle() { Class<?> testClass = NullTestInstanceFactoryTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(1, executionResults.testEvents().started().count(), "# tests started"); assertEquals(1, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(test("testShouldNotBeCalled"), started()), // event(test("testShouldNotBeCalled"), finishedWithFailure(instanceOf(TestInstantiationException.class), message(m -> m.equals("TestInstanceFactory [" + NullTestInstanceFactory.class.getName() + "] failed to return an instance of [" + testClass.getName() + "] and instead returned an instance of [null].")))), // event(container(testClass), finishedSuccessfully()), // event(engine(), finishedSuccessfully())); } @Test void nullTestInstanceFactoryWithPerClassLifecycle() { Class<?> testClass = PerClassLifecycleNullTestInstanceFactoryTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(0, executionResults.testEvents().started().count(), "# tests started"); assertEquals(0, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(container(testClass), finishedWithFailure(instanceOf(TestInstantiationException.class), message(m -> m.equals("TestInstanceFactory [" + NullTestInstanceFactory.class.getName() + "] failed to return an instance of [" + testClass.getName() + "] and instead returned an instance of [null].")))), // event(engine(), finishedSuccessfully())); } @Test void bogusTestInstanceFactoryWithPerMethodLifecycle() { Class<?> testClass = BogusTestInstanceFactoryTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(1, executionResults.testEvents().started().count(), "# tests started"); assertEquals(1, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(test("testShouldNotBeCalled"), started()), // event(test("testShouldNotBeCalled"), finishedWithFailure(instanceOf(TestInstantiationException.class), message(m -> m.equals("TestInstanceFactory [" + BogusTestInstanceFactory.class.getName() + "] failed to return an instance of [" + testClass.getName() + "] and instead returned an instance of [java.lang.String].")))), // event(container(testClass), finishedSuccessfully()), // event(engine(), finishedSuccessfully())); } @Test void bogusTestInstanceFactoryWithPerClassLifecycle() { Class<?> testClass = PerClassLifecycleBogusTestInstanceFactoryTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(0, executionResults.testEvents().started().count(), "# tests started"); assertEquals(0, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(container(testClass), finishedWithFailure(instanceOf(TestInstantiationException.class), message(m -> m.equals("TestInstanceFactory [" + BogusTestInstanceFactory.class.getName() + "] failed to return an instance of [" + testClass.getName() + "] and instead returned an instance of [java.lang.String].")))), // event(engine(), finishedSuccessfully())); } @Test void explosiveTestInstanceFactoryWithPerMethodLifecycle() { Class<?> testClass = ExplosiveTestInstanceFactoryTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(1, executionResults.testEvents().started().count(), "# tests started"); assertEquals(1, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(test("testShouldNotBeCalled"), started()), // event(test("testShouldNotBeCalled"), finishedWithFailure(instanceOf(TestInstantiationException.class), message("TestInstanceFactory [" + ExplosiveTestInstanceFactory.class.getName() + "] failed to instantiate test class [" + testClass.getName() + "]: boom!"))), // event(container(testClass), finishedSuccessfully()), // event(engine(), finishedSuccessfully())); } @Test void explosiveTestInstanceFactoryWithPerClassLifecycle() { Class<?> testClass = PerClassLifecycleExplosiveTestInstanceFactoryTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(0, executionResults.testEvents().started().count(), "# tests started"); assertEquals(0, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(container(testClass), // finishedWithFailure(instanceOf(TestInstantiationException.class), message("TestInstanceFactory [" + ExplosiveTestInstanceFactory.class.getName() + "] failed to instantiate test class [" + testClass.getName() + "]: boom!"))), // event(engine(), finishedSuccessfully())); } @Test void proxyTestInstanceFactoryFailsDueToUseOfDifferentClassLoader() { Class<?> testClass = ProxiedTestCase.class; EngineExecutionResults executionResults = executeTestsForClass(testClass); assertEquals(0, executionResults.testEvents().started().count(), "# tests started"); assertEquals(0, executionResults.testEvents().failed().count(), "# tests aborted"); executionResults.allEvents().assertEventsMatchExactly( // event(engine(), started()), // event(container(testClass), started()), // event(container(testClass), // // NOTE: the test
TestInstanceFactoryTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_extracting_Test.java
{ "start": 14227, "end": 25287 }
interface ____ { default String getName() { return "John Doe"; } } @Test void should_use_property_field_names_as_description_when_extracting_simple_value_list() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).extracting("name.first").isEmpty()) .withMessageContaining("[Extracted: name.first]"); } @Test void should_use_property_field_names_as_description_when_extracting_typed_simple_value_list() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).extracting("name.first", String.class) .isEmpty()) .withMessageContaining("[Extracted: name.first]"); } @Test void should_use_property_field_names_as_description_when_extracting_tuples_list() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).extracting("name.first", "name.last") .isEmpty()) .withMessageContaining("[Extracted: name.first, name.last]"); } @Test void should_keep_existing_description_if_set_when_extracting_typed_simple_value_list() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).as("check employees first name") .extracting("name.first", String.class) .isEmpty()) .withMessageContaining("[check employees first name]"); } @Test void should_keep_existing_description_if_set_when_extracting_tuples_list() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).as("check employees name") .extracting("name.first", "name.last") .isEmpty()) .withMessageContaining("[check employees name]"); } @Test void should_keep_existing_description_if_set_when_extracting_simple_value_list() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).as("check employees first name") .extracting("name.first").isEmpty()) .withMessageContaining("[check employees first name]"); } @Test void should_keep_existing_description_if_set_when_extracting_using_extractor() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).as("check employees first name") .extracting(input -> input.getName() .getFirst()) .isEmpty()) .withMessageContaining("[check employees first name]"); } @Test void should_keep_existing_description_if_set_when_extracting_using_throwing_extractor() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(jedis).as("expected exception") .extracting(THROWING_EXTRACTOR).isEmpty()) .withMessageContaining("[expected exception]"); } @Test void extracting_by_several_functions_should_keep_assertion_state() { // WHEN // not all comparators are used but we want to test that they are passed correctly after extracting AbstractListAssert<?, ?, ?, ?> assertion = assertThat(jedis).as("test description") .withFailMessage("error message") .withRepresentation(UNICODE_REPRESENTATION) .usingComparatorForType(ALWAYS_EQUALS_TUPLE, Tuple.class) .extracting(firstNameFunction, lastNameFunction) .contains(tuple("YODA", null), tuple("Luke", "Skywalker")); // THEN assertThat(assertion.descriptionText()).isEqualTo("test description"); assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION); assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message"); assertThat(comparatorsByTypeOf(assertion).getComparatorForType(Tuple.class)).isSameAs(ALWAYS_EQUALS_TUPLE); } @Test void extracting_by_name_should_keep_assertion_state() { // WHEN // not all comparators are used but we want to test that they are passed correctly after extracting AbstractListAssert<?, ?, ?, ?> assertion = assertThat(jedis).as("test description") .withFailMessage("error message") .withRepresentation(UNICODE_REPRESENTATION) .usingComparatorForType(ALWAYS_EQUALS_STRING, String.class) .extracting("name.first") .contains("YODA", "Luke"); // THEN assertThat(assertion.descriptionText()).isEqualTo("test description"); assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION); assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message"); assertThat(comparatorsByTypeOf(assertion).getComparatorForType(String.class)).isSameAs(ALWAYS_EQUALS_STRING); } @Test void extracting_by_strongly_typed_name_should_keep_assertion_state() { // WHEN // not all comparators are used but we want to test that they are passed correctly after extracting AbstractListAssert<?, ?, ?, ?> assertion = assertThat(jedis).as("test description") .withFailMessage("error message") .withRepresentation(UNICODE_REPRESENTATION) .usingComparatorForType(ALWAYS_EQUALS_STRING, String.class) .extracting("name.first", String.class) .contains("YODA", "Luke"); // THEN assertThat(assertion.descriptionText()).isEqualTo("test description"); assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION); assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message"); assertThat(comparatorsByTypeOf(assertion).getComparatorForType(String.class)).isSameAs(ALWAYS_EQUALS_STRING); } @Test void extracting_by_multiple_names_should_keep_assertion_state() { // WHEN // not all comparators are used but we want to test that they are passed correctly after extracting AbstractListAssert<?, ?, ?, ?> assertion = assertThat(jedis).as("test description") .withFailMessage("error message") .withRepresentation(UNICODE_REPRESENTATION) .usingComparatorForType(ALWAYS_EQUALS_TUPLE, Tuple.class) .extracting("name.first", "name.last") .contains(tuple("YODA", null), tuple("Luke", "Skywalker")); // THEN assertThat(assertion.descriptionText()).isEqualTo("test description"); assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION); assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message"); assertThat(comparatorsByTypeOf(assertion).getComparatorForType(Tuple.class)).isSameAs(ALWAYS_EQUALS_TUPLE); } @Test void extracting_by_single_extractor_should_keep_assertion_state() { // WHEN // not all comparators are used but we want to test that they are passed correctly after extracting AbstractListAssert<?, ?, ?, ?> assertion = assertThat(jedis).as("test description") .withFailMessage("error message") .withRepresentation(UNICODE_REPRESENTATION) .usingComparatorForType(ALWAYS_EQUALS_STRING, String.class) .extracting(byName("name.first")) .contains("YODA", "Luke"); // THEN assertThat(assertion.descriptionText()).isEqualTo("test description"); assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION); assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message"); assertThat(comparatorsByTypeOf(assertion).getComparatorForType(String.class)).isSameAs(ALWAYS_EQUALS_STRING); } @Test void extracting_by_throwing_extractor_should_keep_assertion_state() { // WHEN // not all comparators are used but we want to test that they are passed correctly after extracting AbstractListAssert<?, ?, ?, ?> assertion = assertThat(jedis).as("test description") .withFailMessage("error message") .withRepresentation(UNICODE_REPRESENTATION) .usingComparatorForType(ALWAYS_EQUALS_STRING, String.class) .extracting(throwingFirstNameExtractor) .contains("YODA", "Luke"); // THEN assertThat(assertion.descriptionText()).isEqualTo("test description"); assertThat(assertion.info.representation()).isEqualTo(UNICODE_REPRESENTATION); assertThat(assertion.info.overridingErrorMessage()).isEqualTo("error message"); assertThat(comparatorsByTypeOf(assertion).getComparatorForType(String.class)).isSameAs(ALWAYS_EQUALS_STRING); } }
DefaultName
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/enums/EnumSetDeserializer5203Test.java
{ "start": 925, "end": 1221 }
class ____ { private EnumSet<MyEnum> set; public EnumSet<MyEnum> getSet() { return set; } public void setSet(EnumSet<MyEnum> set) { this.set = set; } } // Custom deserializer that converts empty strings to null static
Dst
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/DeleteAllWithTablePerClassAndDefaultSchemaTest.java
{ "start": 2855, "end": 3303 }
class ____ extends SuperEntity { private String subProperty1; public SubEntity1() { } public SubEntity1(Long id, String superProperty, String subProperty) { super(id, superProperty); this.subProperty1 = subProperty; } public String getSubProperty1() { return subProperty1; } public void setSubProperty1(String subProperty1) { this.subProperty1 = subProperty1; } } @Entity(name = "subent2") public static
SubEntity1
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/counters/FrameworkCounterGroup.java
{ "start": 1705, "end": 1797 }
enum ____ * @param <C> type of the counter */ @InterfaceAudience.Private public abstract
class
java
quarkusio__quarkus
extensions/agroal/deployment/src/test/java/io/quarkus/agroal/test/ConfigUrlMissingDefaultDatasourceDynamicInjectionTest.java
{ "start": 487, "end": 2051 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() // The URL won't be missing if dev services are enabled .overrideConfigKey("quarkus.devservices.enabled", "false"); @Inject InjectableInstance<DataSource> dataSource; @Inject InjectableInstance<AgroalDataSource> agroalDataSource; @Test public void dataSource() { doTest(dataSource); } @Test public void agroalDataSource() { doTest(agroalDataSource); } private void doTest(InjectableInstance<? extends DataSource> instance) { // The bean is always available to be injected during static init // since we don't know whether the datasource will be active at runtime. // So the bean proxy cannot be null. var ds = instance.get(); assertThat(ds).isNotNull(); // However, any attempt to use it at runtime will fail. assertThatThrownBy(() -> ds.getConnection()) .isInstanceOf(InactiveBeanException.class) .hasMessageContainingAll("Datasource '<default>' was deactivated automatically because its URL is not set.", "To avoid this exception while keeping the bean inactive", // Message from Arc with generic hints "To activate the datasource, set configuration property 'quarkus.datasource.jdbc.url'", "Refer to https://quarkus.io/guides/datasource for guidance."); } }
ConfigUrlMissingDefaultDatasourceDynamicInjectionTest
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/external/response/streaming/ServerSentEventParserTests.java
{ "start": 512, "end": 4560 }
class ____ extends ESTestCase { public void testRetryAndIdAreUnimplemented() { var payload = """ id: 2 retry: 2 """.getBytes(StandardCharsets.UTF_8); var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertTrue(events.isEmpty()); } public void testEmptyEventDefaultsToMessage() { var payload = """ data: hello """.getBytes(StandardCharsets.UTF_8); var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertEvents(events, List.of(new ServerSentEvent("message", "hello"))); } public void testEmptyData() { var payload = """ data data """.getBytes(StandardCharsets.UTF_8); var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertEvents(events, List.of(new ServerSentEvent("message", "\n"))); } public void testParseDataEventsWithAllEndOfLines() { var payload = """ event: message\n\ data: test\n\ \n\ event: message\r\ data: test2\r\ \r\ event: message\r\n\ data: test3\r\n\ \r\n\ """.getBytes(StandardCharsets.UTF_8); var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertEvents( events, List.of( new ServerSentEvent("message", "test"), new ServerSentEvent("message", "test2"), new ServerSentEvent("message", "test3") ) ); } public void testParseMultiLineDataEvents() { var payload = """ event: message data: hello data: there """.getBytes(StandardCharsets.UTF_8); var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertEvents(events, List.of(new ServerSentEvent("message", "hello\nthere"))); } private void assertEvents(Deque<ServerSentEvent> actualEvents, List<ServerSentEvent> expectedEvents) { assertThat(actualEvents.size(), equalTo(expectedEvents.size())); var expectedEvent = expectedEvents.iterator(); actualEvents.forEach(event -> assertThat(event, equalTo(expectedEvent.next()))); } // by default, Java's UTF-8 decode does not remove the byte order mark public void testByteOrderMarkIsRemoved() { // these are the bytes for "<byte-order mark>data: hello\n\n" var payload = new byte[] { -17, -69, -65, 100, 97, 116, 97, 58, 32, 104, 101, 108, 108, 111, 10, 10 }; var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertEvents(events, List.of(new ServerSentEvent("message", "hello"))); } public void testEmptyEventIsSetAsEmptyString() { var payload = """ event: event:\s """.getBytes(StandardCharsets.UTF_8); var parser = new ServerSentEventParser(); var events = parser.parse(payload); assertTrue(events.isEmpty()); } public void testCommentsAreIgnored() { var parser = new ServerSentEventParser(); var events = parser.parse(""" :some cool comment :event: message """.getBytes(StandardCharsets.UTF_8)); assertTrue(events.isEmpty()); } public void testCarryOverBytes() { var parser = new ServerSentEventParser(); var events = parser.parse(""" event: message data""".getBytes(StandardCharsets.UTF_8)); // no newline after 'data' so the parser won't split the message up assertTrue(events.isEmpty()); events = parser.parse(""" :test """.getBytes(StandardCharsets.UTF_8)); assertEvents(events, List.of(new ServerSentEvent("test"))); } }
ServerSentEventParserTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/impl/AbstractFSBuilderImpl.java
{ "start": 2597, "end": 11210 }
class ____<S, B extends FSBuilder<S, B>> implements FSBuilder<S, B> { public static final String UNKNOWN_MANDATORY_KEY = "Unknown mandatory key"; @VisibleForTesting static final String E_BOTH_A_PATH_AND_A_PATH_HANDLE = "Both a path and a pathHandle has been provided to the constructor"; private final Optional<Path> optionalPath; private final Optional<PathHandle> optionalPathHandle; /** * Contains optional and mandatory parameters. * * It does not load default configurations from default files. */ private final Configuration options = new Configuration(false); /** Keep track of the keys for mandatory options. */ private final Set<String> mandatoryKeys = new HashSet<>(); /** Keep track of the optional keys. */ private final Set<String> optionalKeys = new HashSet<>(); /** * Constructor with both optional path and path handle. * Either or both argument may be empty, but it is an error for * both to be defined. * @param optionalPath a path or empty * @param optionalPathHandle a path handle/empty * @throws IllegalArgumentException if both parameters are set. */ protected AbstractFSBuilderImpl( @Nonnull Optional<Path> optionalPath, @Nonnull Optional<PathHandle> optionalPathHandle) { checkArgument(!(checkNotNull(optionalPath).isPresent() && checkNotNull(optionalPathHandle).isPresent()), E_BOTH_A_PATH_AND_A_PATH_HANDLE); this.optionalPath = optionalPath; this.optionalPathHandle = optionalPathHandle; } protected AbstractFSBuilderImpl(@Nonnull final Path path) { this(Optional.of(path), Optional.empty()); } protected AbstractFSBuilderImpl(@Nonnull final PathHandle pathHandle) { this(Optional.empty(), Optional.of(pathHandle)); } /** * Get the cast builder. * @return this object, typecast */ public B getThisBuilder() { return (B)this; } /** * Get the optional path; may be empty. * @return the optional path field. */ public Optional<Path> getOptionalPath() { return optionalPath; } /** * Get the path: only valid if constructed with a path. * @return the path * @throws NoSuchElementException if the field is empty. */ public Path getPath() { return optionalPath.get(); } /** * Get the optional path handle; may be empty. * @return the optional path handle field. */ public Optional<PathHandle> getOptionalPathHandle() { return optionalPathHandle; } /** * Get the PathHandle: only valid if constructed with a PathHandle. * @return the PathHandle * @throws NoSuchElementException if the field is empty. */ public PathHandle getPathHandle() { return optionalPathHandle.get(); } /** * Set optional Builder parameter. */ @Override public B opt(@Nonnull final String key, @Nonnull final String value) { mandatoryKeys.remove(key); optionalKeys.add(key); options.set(key, value); return getThisBuilder(); } /** * Set optional boolean parameter for the Builder. * * @see #opt(String, String) */ @Override public B opt(@Nonnull final String key, boolean value) { return opt(key, Boolean.toString(value)); } /** * Set optional int parameter for the Builder. * * @see #opt(String, String) */ @Override public B opt(@Nonnull final String key, int value) { return optLong(key, value); } @Override public B opt(@Nonnull final String key, final long value) { return optLong(key, value); } @Override public B optLong(@Nonnull final String key, final long value) { return opt(key, Long.toString(value)); } /** * Set optional float parameter for the Builder. * * @see #opt(String, String) */ @Override public B opt(@Nonnull final String key, float value) { return optLong(key, (long) value); } /** * Set optional double parameter for the Builder. * * @see #opt(String, String) */ @Override public B opt(@Nonnull final String key, double value) { return optLong(key, (long) value); } /** * Set optional double parameter for the Builder. * * @see #opt(String, String) */ @Override public B optDouble(@Nonnull final String key, double value) { return opt(key, Double.toString(value)); } /** * Set an array of string values as optional parameter for the Builder. * * @see #opt(String, String) */ @Override public B opt(@Nonnull final String key, @Nonnull final String... values) { mandatoryKeys.remove(key); optionalKeys.add(key); options.setStrings(key, values); return getThisBuilder(); } /** * Set mandatory option to the Builder. * * If the option is not supported or unavailable on the {@link FileSystem}, * the client should expect {@link #build()} throws IllegalArgumentException. */ @Override public B must(@Nonnull final String key, @Nonnull final String value) { mandatoryKeys.add(key); options.set(key, value); return getThisBuilder(); } /** * Set mandatory boolean option. * * @see #must(String, String) */ @Override public B must(@Nonnull final String key, boolean value) { return must(key, Boolean.toString(value)); } @Override public B mustLong(@Nonnull final String key, final long value) { return must(key, Long.toString(value)); } /** * Set optional double parameter for the Builder. * * @see #opt(String, String) */ @Override public B mustDouble(@Nonnull final String key, double value) { return must(key, Double.toString(value)); } /** * Set mandatory int option. * * @see #must(String, String) */ @Override public B must(@Nonnull final String key, int value) { return mustLong(key, value); } @Override public B must(@Nonnull final String key, final long value) { return mustLong(key, value); } @Override public B must(@Nonnull final String key, final float value) { return mustLong(key, (long) value); } @Override public B must(@Nonnull final String key, double value) { return mustLong(key, (long) value); } /** * Set a string array as mandatory option. * * @see #must(String, String) */ @Override public B must(@Nonnull final String key, @Nonnull final String... values) { mandatoryKeys.add(key); optionalKeys.remove(key); options.setStrings(key, values); return getThisBuilder(); } /** * Get the mutable option configuration. * @return the option configuration. */ public Configuration getOptions() { return options; } /** * Get all the keys that are set as mandatory keys. * @return mandatory keys. */ public Set<String> getMandatoryKeys() { return Collections.unmodifiableSet(mandatoryKeys); } /** * Get all the keys that are set as optional keys. * @return optional keys. */ public Set<String> getOptionalKeys() { return Collections.unmodifiableSet(optionalKeys); } /** * Reject a configuration if one or more mandatory keys are * not in the set of mandatory keys. * The first invalid key raises the exception; the order of the * scan and hence the specific key raising the exception is undefined. * @param knownKeys a possibly empty collection of known keys * @param extraErrorText extra error text to include. * @throws IllegalArgumentException if any key is unknown. */ protected void rejectUnknownMandatoryKeys(final Collection<String> knownKeys, String extraErrorText) throws IllegalArgumentException { rejectUnknownMandatoryKeys(mandatoryKeys, knownKeys, extraErrorText); } /** * Reject a configuration if one or more mandatory keys are * not in the set of mandatory keys. * The first invalid key raises the exception; the order of the * scan and hence the specific key raising the exception is undefined. * @param mandatory the set of mandatory keys * @param knownKeys a possibly empty collection of known keys * @param extraErrorText extra error text to include. * @throws IllegalArgumentException if any key is unknown. */ public static void rejectUnknownMandatoryKeys( final Set<String> mandatory, final Collection<String> knownKeys, final String extraErrorText) throws IllegalArgumentException { final String eText = extraErrorText.isEmpty() ? "" : (extraErrorText + " "); mandatory.forEach((key) -> checkArgument(knownKeys.contains(key), UNKNOWN_MANDATORY_KEY + " %s\"%s\"", eText, key)); } }
AbstractFSBuilderImpl
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/defaultbean/ambiguous/DefaultBeanPriorityAmbiguousTest.java
{ "start": 567, "end": 1169 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(MyBean.class, FooInterface.class, FooImpl1.class, FooImpl2.class) .shouldFail() .build(); @Test public void testAmbiguousResolution() { Throwable error = container.getFailure(); assertNotNull(error); assertTrue(error instanceof DeploymentException); assertTrue(error.getMessage().contains("AmbiguousResolutionException: Ambiguous dependencies")); } @Singleton static
DefaultBeanPriorityAmbiguousTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DiskBalancer.java
{ "start": 2552, "end": 3137 }
class ____ Disk Balancer. * <p> * Here is the high level logic executed by this class. Users can submit disk * balancing plans using submitPlan calls. After a set of sanity checks the plan * is admitted and put into workMap. * <p> * The executePlan launches a thread that picks up work from workMap and hands * it over to the BlockMover#copyBlocks function. * <p> * Constraints : * <p> * Only one plan can be executing in a datanode at any given time. This is * ensured by checking the future handle of the worker thread in submitPlan. */ @InterfaceAudience.Private public
for
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnProperty.java
{ "start": 2770, "end": 3207 }
class ____ { * } * </pre> * * It is better to use a custom condition for such cases. * * @author Maciej Walkowiak * @author Stephane Nicoll * @author Phillip Webb * @since 1.1.0 * @see ConditionalOnBooleanProperty */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(OnPropertyCondition.class) @Repeatable(ConditionalOnProperties.class) public @
ExampleAutoConfiguration
java
apache__camel
components/camel-tracing/src/test/java/org/apache/camel/tracing/decorators/AzureServiceBusSpanDecoratorTest.java
{ "start": 1193, "end": 5246 }
class ____ { @Test public void testGetMessageId() { String messageId = "abcd"; Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.MESSAGE_ID, String.class)).thenReturn(messageId); AbstractMessagingSpanDecorator decorator = new AzureServiceBusSpanDecorator(); assertEquals(messageId, decorator.getMessageId(exchange)); } @Test public void testPre() { String contentType = "application/json"; String correlationId = "1234"; Long deliveryCount = 27L; Long enqueuedSequenceNumber = 1L; OffsetDateTime enqueuedTime = OffsetDateTime.now(); OffsetDateTime expiresAt = OffsetDateTime.now(); String partitionKey = "MyPartitionKey"; String replyToSessionId = "MyReplyToSessionId"; String sessionId = "4321"; Duration ttl = Duration.ofDays(7); Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("azure-servicebus:topicOrQueueName"); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.CONTENT_TYPE, String.class)).thenReturn(contentType); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.CORRELATION_ID, String.class)).thenReturn(correlationId); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.DELIVERY_COUNT, Long.class)).thenReturn(deliveryCount); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.ENQUEUED_SEQUENCE_NUMBER, Long.class)) .thenReturn(enqueuedSequenceNumber); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.ENQUEUED_TIME, OffsetDateTime.class)) .thenReturn(enqueuedTime); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.EXPIRES_AT, OffsetDateTime.class)).thenReturn(expiresAt); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.PARTITION_KEY, String.class)).thenReturn(partitionKey); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.REPLY_TO_SESSION_ID, String.class)) .thenReturn(replyToSessionId); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.SESSION_ID, String.class)).thenReturn(sessionId); Mockito.when(message.getHeader(AzureServiceBusSpanDecorator.TIME_TO_LIVE, Duration.class)).thenReturn(ttl); AbstractMessagingSpanDecorator decorator = new AzureServiceBusSpanDecorator(); MockSpanAdapter span = new MockSpanAdapter(); decorator.pre(span, exchange, endpoint); assertEquals(contentType, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_CONTENT_TYPE)); assertEquals(correlationId, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_CORRELATION_ID)); assertEquals(deliveryCount, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_DELIVERY_COUNT)); assertEquals(enqueuedSequenceNumber, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_ENQUEUED_SEQUENCE_NUMBER)); assertEquals(enqueuedTime.toString(), span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_ENQUEUED_TIME)); assertEquals(expiresAt.toString(), span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_EXPIRES_AT)); assertEquals(partitionKey, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_PARTITION_KEY)); assertEquals(replyToSessionId, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_REPLY_TO_SESSION_ID)); assertEquals(sessionId, span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_SESSION_ID)); assertEquals(ttl.toString(), span.tags().get(AzureServiceBusSpanDecorator.SERVICEBUS_TIME_TO_LIVE)); } }
AzureServiceBusSpanDecoratorTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/naming/EmbeddedColumnNamingTests.java
{ "start": 8014, "end": 8343 }
class ____ { @Id private Integer id; private String name; @Embedded @EmbeddedColumnNaming("%s_home_%s") private Address homeAddress; @Embedded @EmbeddedColumnNaming("work_%s") private Address workAddress; } @Entity(name="BadPatternPerson2") @Table(name="bad_pattern_person_2") public static
BadPatternPerson1
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/PushingAsyncDataInput.java
{ "start": 1698, "end": 2103 }
interface ____<T> extends AvailabilityProvider { /** * Pushes elements to the output from current data input, and returns the input status to * indicate whether there are more available data in current input. * * <p>This method should be non blocking. */ DataInputStatus emitNext(DataOutput<T> output) throws Exception; /** * Basic data output
PushingAsyncDataInput
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/gateway/GatewayMetaStateTests.java
{ "start": 15132, "end": 15739 }
class ____ extends TestClusterCustomMetadata { public static final String TYPE = "custom_md_1"; CustomMetadata1(String data) { super(data); } @Override public String getWriteableName() { return TYPE; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.current(); } @Override public EnumSet<Metadata.XContentContext> context() { return EnumSet.of(Metadata.XContentContext.GATEWAY); } } private static
CustomMetadata1
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/StandardWebSocketHandlerAdapterTests.java
{ "start": 1382, "end": 2723 }
class ____ { private WebSocketHandler webSocketHandler = mock(); private Session session = mock(); private StandardWebSocketSession webSocketSession = new StandardWebSocketSession(null, null, null, null); private StandardWebSocketHandlerAdapter adapter = new StandardWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession); @Test void onOpen() throws Throwable { URI uri = URI.create("https://example.org"); given(this.session.getRequestURI()).willReturn(uri); this.adapter.onOpen(this.session, null); verify(this.webSocketHandler).afterConnectionEstablished(this.webSocketSession); verify(this.session, atLeast(2)).addMessageHandler(any(MessageHandler.Whole.class)); given(this.session.getRequestURI()).willReturn(uri); assertThat(this.webSocketSession.getUri()).isEqualTo(uri); } @Test void onClose() throws Throwable { this.adapter.onClose(this.session, new CloseReason(CloseCodes.NORMAL_CLOSURE, "reason")); verify(this.webSocketHandler).afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL.withReason("reason")); } @Test void onError() throws Throwable { Exception exception = new Exception(); this.adapter.onError(this.session, exception); verify(this.webSocketHandler).handleTransportError(this.webSocketSession, exception); } }
StandardWebSocketHandlerAdapterTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/util/DeserializationUtils.java
{ "start": 1280, "end": 2460 }
class ____ { /** * Iterates over the provided records to deserialize, verifies the results and stats the number * of full records. * * @param records records to be deserialized * @param deserializer the record deserializer * @return the number of full deserialized records */ public static int deserializeRecords( ArrayDeque<SerializationTestType> records, RecordDeserializer<SerializationTestType> deserializer) throws Exception { int deserializedRecords = 0; while (!records.isEmpty()) { SerializationTestType expected = records.poll(); SerializationTestType actual = expected.getClass().newInstance(); final DeserializationResult result = deserializer.getNextRecord(actual); if (result.isFullRecord()) { assertThat(actual).isEqualTo(expected); deserializedRecords++; } else { records.addFirst(expected); } if (result.isBufferConsumed()) { break; } } return deserializedRecords; } }
DeserializationUtils
java
netty__netty
handler/src/test/java/io/netty/handler/pcap/PcapWriteHandlerTest.java
{ "start": 64624, "end": 64878 }
class ____ extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { //Discard ReferenceCountUtil.release(msg); } } static
DiscardingReadsHandler
java
quarkusio__quarkus
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/devui/ArcBeanInfoBuildItem.java
{ "start": 104, "end": 377 }
class ____ extends SimpleBuildItem { private final DevBeanInfos beanInfos; public ArcBeanInfoBuildItem(DevBeanInfos beanInfos) { this.beanInfos = beanInfos; } public DevBeanInfos getBeanInfos() { return beanInfos; } }
ArcBeanInfoBuildItem
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/TargetType.java
{ "start": 389, "end": 555 }
enum ____ { /** * Export to the database. */ DATABASE, /** * Write to a script file. */ SCRIPT, /** * Write to {@link System#out} */ STDOUT }
TargetType
java
apache__flink
flink-end-to-end-tests/flink-state-evolution-test/src/main/java/org/apache/flink/test/StatefulStreamingJob.java
{ "start": 2100, "end": 2270 }
class ____ { private static final String EXPECTED_DEFAULT_VALUE = "123"; /** Stub source that emits one record per second. */ public static
StatefulStreamingJob
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java
{ "start": 9933, "end": 10637 }
class ____ extends AbstractBindHandler { ConfigurationPropertiesBindHandler(BindHandler handler) { super(handler); } @Override public <T> Bindable<T> onStart(ConfigurationPropertyName name, Bindable<T> target, BindContext context) { return isConfigurationProperties(target.getType().resolve()) ? target.withBindRestrictions(BindRestriction.NO_DIRECT_PROPERTY) : target; } private boolean isConfigurationProperties(@Nullable Class<?> target) { return target != null && MergedAnnotations.from(target).isPresent(ConfigurationProperties.class); } } /** * {@link FactoryBean} to create the {@link ConfigurationPropertiesBinder}. */ static
ConfigurationPropertiesBindHandler
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/inlinedirtychecking/ManyToOnePropertyAccessByFieldTest.java
{ "start": 12090, "end": 12744 }
class ____ { @Id private Long id; private String type; @NaturalId @Column(name = "`number`") private String number; public Phone() { } public Phone(Long id, String type, String number) { this.id = id; this.type = type; this.number = number; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } } @Entity(name = "Client") public static
Phone
java
apache__logging-log4j2
log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/TempLoggingDirectory.java
{ "start": 8590, "end": 9951 }
class ____ implements CloseableResource { private final Path path; private final CleanupMode cleanupMode; private final ExtensionContext mainContext; private final Map<ExtensionContext, Boolean> contexts = new ConcurrentHashMap<>(); public PathHolder(final Path path, final CleanupMode cleanup, final ExtensionContext context) { this.path = path; this.cleanupMode = cleanup; this.contexts.put(context, Boolean.TRUE); this.mainContext = context; } public void addContext(final ExtensionContext context) { this.contexts.put(context, Boolean.TRUE); } public Path getPath() { return path; } public ExtensionContext getMainContext() { return mainContext; } @Override public void close() throws IOException { if (cleanupMode == NEVER || (cleanupMode == ON_SUCCESS && contexts.keySet().stream().anyMatch(context -> context.getExecutionException() .isPresent()))) { StatusLogger.getLogger().debug("Skipping cleanup of directory {}.", path); return; } DirectoryCleaner.deleteDirectory(path); } } }
PathHolder
java
spring-projects__spring-boot
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/status/ExitStatus.java
{ "start": 834, "end": 2494 }
class ____ { /** * Generic "OK" exit status with zero exit code and {@literal hangup=false}. */ public static final ExitStatus OK = new ExitStatus(0, "OK"); /** * Generic "not OK" exit status with non-zero exit code and {@literal hangup=true}. */ public static final ExitStatus ERROR = new ExitStatus(-1, "ERROR", true); private final int code; private final String name; private final boolean hangup; /** * Create a new {@link ExitStatus} instance. * @param code the exit code * @param name the name */ public ExitStatus(int code, String name) { this(code, name, false); } /** * Create a new {@link ExitStatus} instance. * @param code the exit code * @param name the name * @param hangup true if it is OK for the caller to hangup */ public ExitStatus(int code, String name, boolean hangup) { this.code = code; this.name = name; this.hangup = hangup; } /** * An exit code appropriate for use in {@code System.exit()}. * @return an exit code */ public int getCode() { return this.code; } /** * A name describing the outcome. * @return a name */ public String getName() { return this.name; } /** * Flag to signal that the caller can (or should) hangup. A server process with * non-daemon threads should set this to false. * @return the flag */ public boolean isHangup() { return this.hangup; } /** * Convert the existing code to a hangup. * @return a new ExitStatus with hangup=true */ public ExitStatus hangup() { return new ExitStatus(this.code, this.name, true); } @Override public String toString() { return getName() + ":" + getCode(); } }
ExitStatus
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/FileServiceAccountTokenStore.java
{ "start": 2064, "end": 8358 }
class ____ extends CachingServiceAccountTokenStore implements NodeLocalServiceAccountTokenStore { private static final Logger logger = LogManager.getLogger(FileServiceAccountTokenStore.class); private final Path file; private final ClusterService clusterService; private final CopyOnWriteArrayList<Runnable> refreshListeners; private volatile Map<String, char[]> tokenHashes; @SuppressWarnings("this-escape") public FileServiceAccountTokenStore( Environment env, ResourceWatcherService resourceWatcherService, ThreadPool threadPool, ClusterService clusterService, CacheInvalidatorRegistry cacheInvalidatorRegistry ) { super(env.settings(), threadPool); this.clusterService = clusterService; file = resolveFile(env); FileWatcher watcher = new PrivilegedFileWatcher(file.getParent()); watcher.addListener(new FileReloadListener(file, this::tryReload)); try { resourceWatcherService.add(watcher, ResourceWatcherService.Frequency.HIGH); } catch (IOException e) { throw new ElasticsearchException("failed to start watching service_tokens file [{}]", e, file.toAbsolutePath()); } try { tokenHashes = parseFile(file, logger); } catch (IOException e) { throw new IllegalStateException("Failed to load service_tokens file [" + file + "]", e); } refreshListeners = new CopyOnWriteArrayList<>(List.of(this::invalidateAll)); cacheInvalidatorRegistry.registerCacheInvalidator("file_service_account_token", this); } @Override public void doAuthenticate(ServiceAccountToken token, ActionListener<StoreAuthenticationResult> listener) { // This is done on the current thread instead of using a dedicated thread pool like API key does // because it is not expected to have a large number of service tokens. listener.onResponse( Optional.ofNullable(tokenHashes.get(token.getQualifiedName())) .map(hash -> StoreAuthenticationResult.fromBooleanResult(getTokenSource(), Hasher.verifyHash(token.getSecret(), hash))) .orElse(StoreAuthenticationResult.failed(getTokenSource())) ); } @Override public TokenSource getTokenSource() { return TokenSource.FILE; } @Override public List<TokenInfo> findNodeLocalTokensFor(ServiceAccountId accountId) { final String principal = accountId.asPrincipal(); return tokenHashes.keySet() .stream() .filter(k -> k.startsWith(principal + "/")) .map( k -> TokenInfo.fileToken( Strings.substring(k, principal.length() + 1, k.length()), List.of(clusterService.localNode().getName()) ) ) .toList(); } public void addListener(Runnable listener) { refreshListeners.add(listener); } @Override public boolean shouldClearOnSecurityIndexStateChange() { return false; } private void notifyRefresh() { refreshListeners.forEach(Runnable::run); } private void tryReload() { final Map<String, char[]> previousTokenHashes = tokenHashes; tokenHashes = parseFileLenient(file, logger); if (false == Maps.deepEquals(tokenHashes, previousTokenHashes)) { logger.info("service tokens file [{}] changed. updating ...", file.toAbsolutePath()); notifyRefresh(); } } // package private for testing Map<String, char[]> getTokenHashes() { return tokenHashes; } static Path resolveFile(Environment env) { return XPackPlugin.resolveConfigFile(env, "service_tokens"); } static Map<String, char[]> parseFileLenient(Path path, @Nullable Logger logger) { try { return parseFile(path, logger); } catch (Exception e) { logger.error("failed to parse service tokens file [{}]. skipping/removing all tokens...", path.toAbsolutePath()); return Map.of(); } } static Map<String, char[]> parseFile(Path path, @Nullable Logger logger) throws IOException { final Logger thisLogger = logger == null ? NoOpLogger.INSTANCE : logger; thisLogger.trace("reading service_tokens file [{}]...", path.toAbsolutePath()); if (Files.exists(path) == false) { thisLogger.trace("file [{}] does not exist", path.toAbsolutePath()); return Map.of(); } final Map<String, char[]> parsedTokenHashes = new HashMap<>(); FileLineParser.parse(path, (lineNumber, line) -> { line = line.trim(); final int colon = line.indexOf(':'); if (colon == -1) { thisLogger.warn("invalid format at line #{} of service_tokens file [{}] - missing ':' character - ", lineNumber, path); throw new IllegalStateException("Missing ':' character at line #" + lineNumber); } final String key = line.substring(0, colon); // TODO: validate against known service accounts? char[] hash = new char[line.length() - (colon + 1)]; line.getChars(colon + 1, line.length(), hash, 0); if (Hasher.resolveFromHash(hash) == Hasher.NOOP) { thisLogger.warn("skipping plaintext service account token for key [{}]", key); } else { thisLogger.trace("parsed tokens for key [{}]", key); final char[] previousHash = parsedTokenHashes.put(key, hash); if (previousHash != null) { thisLogger.warn("found duplicated key [{}], earlier entries are overridden", key); } } }); thisLogger.debug("parsed [{}] tokens from file [{}]", parsedTokenHashes.size(), path.toAbsolutePath()); return Map.copyOf(parsedTokenHashes); } static void writeFile(Path path, Map<String, char[]> tokenHashes) { SecurityFiles.writeFileAtomically( path, tokenHashes, e -> String.format(Locale.ROOT, "%s:%s", e.getKey(), new String(e.getValue())) ); } }
FileServiceAccountTokenStore
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/support/jsse/KeyStoreParametersTest.java
{ "start": 1451, "end": 5391 }
class ____ extends AbstractJsseParametersTest { protected KeyStoreParameters createMinimalKeyStoreParameters() { KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("org/apache/camel/support/jsse/localhost.p12"); ksp.setPassword("changeit"); return ksp; } @Test public void testPropertyPlaceholders() throws Exception { CamelContext context = this.createPropertiesPlaceholderAwareContext(); KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setCamelContext(context); ksp.setType("{{keyStoreParameters.type}}"); ksp.setProvider("{{keyStoreParameters.provider}}"); ksp.setResource("{{keyStoreParameters.resource}}"); ksp.setPassword("{{keyStoreParameters.password}}"); KeyStore ks = ksp.createKeyStore(); assertNotNull(ks.getCertificate("localhost")); } @Test public void testValidParameters() throws GeneralSecurityException, IOException, URISyntaxException { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setCamelContext(new DefaultCamelContext()); KeyStore ks = ksp.createKeyStore(); assertNotNull(ks.getCertificate("localhost")); URL resourceUrl = this.getClass().getResource("/org/apache/camel/support/jsse/localhost.p12"); ksp.setResource(resourceUrl.toExternalForm()); ks = ksp.createKeyStore(); assertNotNull(ks.getCertificate("localhost")); resourceUrl = this.getClass().getResource("/org/apache/camel/support/jsse/localhost.p12"); File file = new File(resourceUrl.toURI()); ksp.setResource("file:" + file.getAbsolutePath()); ks = ksp.createKeyStore(); assertNotNull(ks.getCertificate("localhost")); } @Test public void testExplicitType() throws Exception { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setCamelContext(new DefaultCamelContext()); ksp.setType("jks"); KeyStore ks = ksp.createKeyStore(); assertNotNull(ks.getCertificate("localhost")); } @Test public void testExplicitProvider() throws Exception { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setCamelContext(new DefaultCamelContext()); ksp.setProvider(ksp.createKeyStore().getProvider().getName()); KeyStore ks = ksp.createKeyStore(); assertNotNull(ks.getCertificate("localhost")); } @Test public void testExplicitInvalidProvider() throws Exception { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setProvider("sdfdsfgfdsgdsfg"); try { ksp.createKeyStore(); fail(); } catch (NoSuchProviderException e) { // expected } } @Test public void testExplicitInvalidType() throws Exception { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setType("1234"); try { ksp.createKeyStore(); fail(); } catch (KeyStoreException e) { // expected } } @Test public void testIncorrectPassword() throws Exception { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setCamelContext(new DefaultCamelContext()); ksp.setPassword(""); try { ksp.createKeyStore(); fail(); } catch (IOException e) { // expected } } @Test public void testIncorrectResource() throws Exception { KeyStoreParameters ksp = this.createMinimalKeyStoreParameters(); ksp.setCamelContext(new DefaultCamelContext()); ksp.setResource(""); try { ksp.createKeyStore(); fail(); } catch (IOException e) { // expected } } }
KeyStoreParametersTest
java
elastic__elasticsearch
qa/packaging/src/test/java/org/elasticsearch/packaging/util/docker/Docker.java
{ "start": 3068, "end": 27100 }
class ____ { private static final Log logger = LogFactory.getLog(Docker.class); public static final Shell sh = new Shell(); public static final DockerShell dockerShell = new DockerShell(); public static final int STARTUP_SLEEP_INTERVAL_MILLISECONDS = 1000; public static final int STARTUP_ATTEMPTS_MAX = 45; /** * The length of the command exceeds what we can use for COLUMNS so we use * a workaround to find the process we're looking for */ private static final String ELASTICSEARCH_FULL_CLASSNAME = "org.elasticsearch.bootstrap.Elasticsearch"; private static final String FIND_ELASTICSEARCH_PROCESS = "for pid in $(ps -eo pid,comm | grep java | awk '\\''{print $1}'\\''); " + "do cmdline=$(tr \"\\0\" \" \" < /proc/$pid/cmdline 2>/dev/null); [[ $cmdline == *" + ELASTICSEARCH_FULL_CLASSNAME + "* ]] && echo \"$pid: $cmdline\"; done"; /** * Tracks the currently running Docker image. An earlier implementation used a fixed container name, * but that appeared to cause problems with repeatedly destroying and recreating containers with * the same name. */ static String containerId = null; /** * Checks whether the required Docker image exists. If not, the image is loaded from disk. No check is made * to see whether the image is up-to-date. * @param distribution details about the docker image to potentially load. */ public static void ensureImageIsLoaded(Distribution distribution) { final long count = sh.run("docker image ls --format '{{.Repository}}' " + getImageName(distribution)).stdout().lines().count(); if (count != 0) { return; } logger.info("Loading Docker image: " + distribution.path); sh.run("docker load -i " + distribution.path); } /** * Runs an Elasticsearch Docker container, and checks that it has started up * successfully. * * @param distribution details about the docker image being tested * @return an installation that models the running container */ public static Installation runContainer(Distribution distribution) { return runContainer(distribution, DockerRun.builder()); } /** * Runs an Elasticsearch Docker container, and checks that it has started up * successfully. * * @param distribution details about the docker image being tested * @param builder the command to run * @return an installation that models the running container */ public static Installation runContainer(Distribution distribution, DockerRun builder) { executeDockerRun(distribution, builder); waitForElasticsearchToStart(); return Installation.ofContainer(dockerShell, distribution); } /** * Runs an Elasticsearch Docker container without removing any existing containers first, * and checks that it has started up successfully. * * @param distribution details about the docker image being tested * @param builder the command to run * @param restPort the port to expose the REST endpoint on * @param transportPort the port to expose the transport endpoint on * @return an installation that models the running container */ public static Installation runAdditionalContainer(Distribution distribution, DockerRun builder, int restPort, int transportPort) { // TODO Maybe revisit this as part of https://github.com/elastic/elasticsearch/issues/79688 final String command = builder.distribution(distribution) .extraArgs("--publish", transportPort + ":9300", "--publish", restPort + ":9200") .build(); logger.info("Running command: " + command); containerId = sh.run(command).stdout().trim(); waitForElasticsearchToStart(); return Installation.ofContainer(dockerShell, distribution, restPort); } /** * Similar to {@link #runContainer(Distribution, DockerRun)} in that it runs an Elasticsearch Docker * container, expect that the container expecting it to exit e.g. due to configuration problem. * * @param distribution details about the docker image being tested. * @param builder the command to run * @return the docker logs of the container */ public static Shell.Result runContainerExpectingFailure(Distribution distribution, DockerRun builder) { executeDockerRun(distribution, builder); waitForElasticsearchToExit(); return getContainerLogs(); } private static void executeDockerRun(Distribution distribution, DockerRun builder) { removeContainer(); final String command = builder.distribution(distribution).build(); logger.info("Running command: " + command); containerId = sh.run(command).stdout().trim(); } /** * Waits for the Elasticsearch process to start executing in the container. * This is called every time a container is started. */ public static void waitForElasticsearchToStart() { boolean isElasticsearchRunning = false; int attempt = 0; String psOutput = null; do { try { // Give the container enough time for security auto-configuration or a chance to crash out Thread.sleep(STARTUP_SLEEP_INTERVAL_MILLISECONDS); psOutput = dockerShell.run("bash -c '" + FIND_ELASTICSEARCH_PROCESS + " | wc -l'").stdout(); if (psOutput.contains("1")) { isElasticsearchRunning = true; break; } } catch (Exception e) { logger.warn("Caught exception while waiting for ES to start", e); } } while (attempt++ < STARTUP_ATTEMPTS_MAX); if (isElasticsearchRunning == false) { final Shell.Result dockerLogs = getContainerLogs(); fail(String.format(Locale.ROOT, """ Elasticsearch container did not start successfully. ps output: %s Stdout: %s Stderr: %s Thread dump: %s\ """, psOutput, dockerLogs.stdout(), dockerLogs.stderr(), getThreadDump())); } } /** * @return output of jstack for currently running Java process */ private static String getThreadDump() { try { String pid = dockerShell.run("/usr/share/elasticsearch/jdk/bin/jps | grep -v 'Jps' | awk '{print $1}'").stdout(); if (pid.isEmpty() == false) { return dockerShell.run("/usr/share/elasticsearch/jdk/bin/jstack " + Integer.parseInt(pid)).stdout(); } } catch (Exception e) { logger.error("Failed to get thread dump", e); } return ""; } /** * Waits for the Elasticsearch container to exit. */ private static void waitForElasticsearchToExit() { boolean isElasticsearchRunning = true; int attempt = 0; do { try { // Give the container a chance to exit out Thread.sleep(2000); if (sh.run("docker ps --quiet --no-trunc").stdout().contains(containerId) == false) { isElasticsearchRunning = false; break; } } catch (Exception e) { logger.warn("Caught exception while waiting for ES to exit", e); } } while (attempt++ < 60); if (isElasticsearchRunning) { final Shell.Result dockerLogs = getContainerLogs(); fail(String.format(Locale.ROOT, """ Elasticsearch container didn't exit. stdout(): %s Stderr: %s\ """, dockerLogs.stdout(), dockerLogs.stderr())); } } /** * Removes the container with a given id */ public static void removeContainer(String containerId) { if (containerId != null) { // Remove the container, forcibly killing it if necessary logger.debug("Removing container " + containerId); final String command = "docker rm -f " + containerId; final Shell.Result result = sh.runIgnoreExitCode(command); if (result.isSuccess() == false) { boolean isErrorAcceptable = result.stderr().contains("removal of container " + containerId + " is already in progress") || result.stderr().contains("Error: No such container: " + containerId); // I'm not sure why we're already removing this container, but that's OK. if (isErrorAcceptable == false) { throw new RuntimeException("Command was not successful: [" + command + "] result: " + result); } } } } /** * Removes the currently running container. */ public static void removeContainer() { try { removeContainer(containerId); } finally { // Null out the containerId under all circumstances, so that even if the remove command fails // for some reason, the other tests will still proceed. Otherwise they can get stuck, continually // trying to remove a non-existent container ID. containerId = null; } } /** * Copies a file from the container into the local filesystem * @param from the file to copy in the container * @param to the location to place the copy */ public static void copyFromContainer(Path from, Path to) { final String script = "docker cp " + containerId + ":" + from + " " + to; logger.debug("Copying file from container with: " + script); sh.run(script); } /** * Checks whether a path exists in the Docker container. * @param path the path that ought to exist * @return whether the path exists */ public static boolean existsInContainer(Path path) { return existsInContainer(path.toString()); } /** * Checks whether a path exists in the Docker container. * @param path the path that ought to exist * @return whether the path exists */ public static boolean existsInContainer(String path) { logger.debug("Checking whether file " + path + " exists in container"); final Shell.Result result = dockerShell.runIgnoreExitCode("test -e " + path); return result.isSuccess(); } /** * Finds a file or dir in the container and returns its path ( in the container ). If there are multiple matches for the given * pattern, only the first is returned. * * @param base The base path in the container to start the search from * @param type The type we're looking for , d for directories or f for files. * @param pattern the pattern (case insensitive) that matches the file/dir name * @return a Path pointing to the file/directory in the container */ public static Path findInContainer(Path base, String type, String pattern) throws InvalidPathException { logger.debug("Trying to look for " + pattern + " ( " + type + ") in " + base + " in the container"); final String script = "docker exec " + containerId + " find " + base + " -type " + type + " -iname " + pattern; final Shell.Result result = sh.run(script); if (result.isSuccess() && Strings.isNullOrEmpty(result.stdout()) == false) { String path = result.stdout(); if (path.split(System.lineSeparator()).length > 1) { path = path.split(System.lineSeparator())[1]; } return Path.of(path); } return null; } /** * Run privilege escalated shell command on the local file system via a bind mount inside a Docker container. * @param shellCmd The shell command to execute on the localPath e.g. `mkdir /containerPath/dir`. * @param localPath The local path where shellCmd will be executed on (inside a container). * @param containerPath The path to mount localPath inside the container. */ private static void executePrivilegeEscalatedShellCmd(String shellCmd, Path localPath, Path containerPath) { final String image = "alpine:3.13"; ensureImageIsPulled(image); final List<String> args = new ArrayList<>(); args.add("docker run"); // Don't leave orphaned containers args.add("--rm"); // Mount localPath to a known location inside the container, so that we can execute shell commands on it later args.add("--volume \"" + localPath.getParent() + ":" + containerPath.getParent() + "\""); // Use a lightweight musl libc based small image args.add(image); // And run inline commands via the POSIX shell args.add("/bin/sh -c \"" + shellCmd + "\""); final String command = String.join(" ", args); logger.info("Running command: " + command); sh.run(command); } private static void ensureImageIsPulled(String image) { // Don't pull if the image already exists. This does also mean that we never refresh it, but that // isn't an issue in CI. if (sh.runIgnoreExitCode("docker image inspect -f '{{ .Id }}' " + image).isSuccess()) { return; } Shell.Result result = null; int i = 0; while (true) { result = sh.runIgnoreExitCode("docker pull " + image); if (result.isSuccess()) { return; } if (++i == 3) { throw new RuntimeException("Failed to pull Docker image [" + image + "]: " + result); } try { Thread.sleep(10_000L); } catch (InterruptedException e) { // ignore } } } /** * Create a directory with specified uid/gid using Docker backed privilege escalation. * @param localPath The path to the directory to create. * @param uid The numeric id for localPath * @param gid The numeric id for localPath */ public static void mkDirWithPrivilegeEscalation(Path localPath, int uid, int gid) { final Path containerBasePath = Paths.get("/mount"); final Path containerPath = containerBasePath.resolve(Paths.get("/").relativize(localPath)); final List<String> args = new ArrayList<>(); args.add("mkdir " + containerPath.toAbsolutePath()); args.add("&&"); args.add("chown " + uid + ":" + gid + " " + containerPath.toAbsolutePath()); args.add("&&"); args.add("chmod 0770 " + containerPath.toAbsolutePath()); final String command = String.join(" ", args); executePrivilegeEscalatedShellCmd(command, localPath, containerPath); final PosixFileAttributes dirAttributes = FileUtils.getPosixFileAttributes(localPath); final Map<String, Integer> numericPathOwnership = FileUtils.getNumericUnixPathOwnership(localPath); assertThat(localPath + " has wrong uid", numericPathOwnership.get("uid"), equalTo(uid)); assertThat(localPath + " has wrong gid", numericPathOwnership.get("gid"), equalTo(gid)); assertThat(localPath + " has wrong permissions", dirAttributes.permissions(), equalTo(p770)); } /** * Delete a directory using Docker backed privilege escalation. * @param localPath The path to the directory to delete. */ public static void rmDirWithPrivilegeEscalation(Path localPath) { final Path containerBasePath = Paths.get("/mount"); final Path containerPath = containerBasePath.resolve(localPath.getParent().getFileName()); final List<String> args = new ArrayList<>(); args.add("cd " + containerBasePath.toAbsolutePath()); args.add("&&"); args.add("rm -rf " + localPath.getFileName()); final String command = String.join(" ", args); executePrivilegeEscalatedShellCmd(command, localPath, containerPath); } /** * Change the ownership of a path using Docker backed privilege escalation. * @param localPath The path to the file or directory to change. * @param ownership the ownership to apply. Can either be just the user, or the user and group, separated by a colon (":"), * or just the group if prefixed with a colon. */ public static void chownWithPrivilegeEscalation(Path localPath, String ownership) { final Path containerBasePath = Paths.get("/mount"); final Path containerPath = containerBasePath.resolve(localPath.getParent().getFileName()); final List<String> args = new ArrayList<>(); args.add("cd " + containerBasePath.toAbsolutePath()); args.add("&&"); args.add("chown -R " + ownership + " " + localPath.getFileName()); final String command = String.join(" ", args); executePrivilegeEscalatedShellCmd(command, localPath, containerPath); } /** * Waits for up to 20 seconds for a path to exist in the container. * @param path the path to await */ public static void waitForPathToExist(Path path) throws InterruptedException { int attempt = 0; do { if (existsInContainer(path)) { return; } Thread.sleep(1000); } while (attempt++ < 20); fail(path + " failed to exist after 5000ms"); } /** * Perform a variety of checks on an installation. * @param es the installation to verify */ public static void verifyContainerInstallation(Installation es) { // Ensure the `elasticsearch` user and group exist. // These lines will both throw an exception if the command fails dockerShell.run("id elasticsearch"); dockerShell.run("grep -E '^elasticsearch:' /etc/group"); final Shell.Result passwdResult = dockerShell.run("grep -E '^elasticsearch:' /etc/passwd"); final String homeDir = passwdResult.stdout().trim().split(":")[5]; assertThat("elasticsearch user's home directory is incorrect", homeDir, equalTo("/usr/share/elasticsearch")); assertThat(es.home, file(Directory, "root", "root", p775)); Stream.of(es.bundledJdk, es.lib, es.modules).forEach(dir -> assertThat(dir, file(Directory, "root", "root", p555))); // You couldn't install plugins that include configuration when running as `elasticsearch` if the `config` // dir is owned by `root`, because the installed tries to manipulate the permissions on the plugin's // config directory. Stream.of(es.bin, es.config, es.logs, es.config.resolve("jvm.options.d"), es.data, es.plugins) .forEach(dir -> assertThat(dir, file(Directory, "elasticsearch", "root", p775))); final String arch = dockerShell.run("arch").stdout().trim(); Stream.of(es.bin, es.bundledJdk.resolve("bin"), es.modules.resolve("x-pack-ml/platform/linux-" + arch + "/bin")) .forEach( binariesPath -> listContents(binariesPath).forEach( binFile -> assertThat(binariesPath.resolve(binFile), file("root", "root", p555)) ) ); Stream.of("jvm.options", "log4j2.properties", "role_mapping.yml", "roles.yml", "users", "users_roles") .forEach(configFile -> assertThat(es.config(configFile), file("root", "root", p664))); // We write to the elasticsearch.yml and elasticsearch.keystore in AutoConfigureNode so it gets owned by elasticsearch. assertThat(es.config("elasticsearch.yml"), file("elasticsearch", "root", p664)); assertThat(es.config("elasticsearch.keystore"), file("elasticsearch", "root", p660)); Stream.of("LICENSE.txt", "NOTICE.txt", "README.asciidoc") .forEach(doc -> assertThat(es.home.resolve(doc), file("root", "root", p444))); assertThat(dockerShell.run(es.bin("elasticsearch-keystore") + " list").stdout(), containsString("keystore.seed")); // nc is useful for checking network issues // zip/unzip are installed to help users who are working with certificates. Stream.of("nc", "unzip", "zip") .forEach( cliBinary -> assertTrue( cliBinary + " ought to be available.", dockerShell.runIgnoreExitCode("bash -c 'hash " + cliBinary + "'").isSuccess() ) ); if (es.distribution.packaging == Packaging.DOCKER_CLOUD_ESS) { verifyCloudContainerInstallation(es); } } private static void verifyCloudContainerInstallation(Installation es) { final String pluginArchive = "/opt/plugins/archive"; final List<String> plugins = listContents(pluginArchive); if (es.distribution.packaging == Packaging.DOCKER_CLOUD_ESS) { assertThat("ESS image should come with plugins in " + pluginArchive, plugins, not(empty())); final List<String> repositoryPlugins = plugins.stream() .filter(p -> p.matches("^repository-(?:s3|gcs|azure)$")) .collect(Collectors.toList()); // Assert on equality to that the error reports the unexpected values. assertThat( "ESS image should not have repository plugins in " + pluginArchive, repositoryPlugins, equalTo(Collections.emptyList()) ); } else { assertThat("Cloud image should not have any plugins in " + pluginArchive, plugins, empty()); } // Cloud uses `wget` to install plugins / bundles. Stream.of("wget") .forEach( cliBinary -> assertTrue( cliBinary + " ought to be available.", dockerShell.runIgnoreExitCode("bash -c 'hash " + cliBinary + "'").isSuccess() ) ); } public static void waitForElasticsearch(Installation installation) throws Exception { withLogging(() -> ServerUtils.waitForElasticsearch(installation)); } public static void waitForElasticsearch(Installation installation, String username, String password) { waitForElasticsearch(installation, username, password, null); } /** * Waits for the Elasticsearch cluster status to turn green. * * @param installation the installation to check * @param username the username to authenticate with * @param password the password to authenticate with * @param caCert the CA cert to trust */ public static void waitForElasticsearch(Installation installation, String username, String password, Path caCert) { try { withLogging(() -> ServerUtils.waitForElasticsearch("green", null, installation, username, password, caCert)); } catch (Exception e) { throw new AssertionError( "Failed to check whether Elasticsearch had started. This could be because " + "authentication isn't working properly. Check the container logs", e ); } } /** * Runs the provided closure, and captures logging information if an exception is thrown. * @param r the closure to run * @throws Exception any exception encountered while running the closure are propagated. */ private static <E extends Exception> void withLogging(CheckedRunnable<E> r) throws Exception { try { r.run(); } catch (Exception e) { final Shell.Result logs = getContainerLogs(); logger.warn("Elasticsearch container failed to start.\n\nStdout:\n" + logs.stdout() + "\n\nStderr:\n" + logs.stderr()); throw e; } } /** * @return The ID of the container that this
Docker
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/MapTest.java
{ "start": 494, "end": 1988 }
class ____ extends TestCase { public void test_no_sort() throws Exception { JSONObject obj = new JSONObject(true); obj.put("name", "jobs"); obj.put("id", 33); String text = toJSONString(obj); Assert.assertEquals("{'name':'jobs','id':33}", text); } public void test_null() throws Exception { JSONObject obj = new JSONObject(true); obj.put("name", null); String text = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"name\":null}", text); } public static final String toJSONString(Object object) { SerializeWriter out = new SerializeWriter(); try { JSONSerializer serializer = new JSONSerializer(out); serializer.config(SerializerFeature.SortField, false); serializer.config(SerializerFeature.UseSingleQuotes, true); serializer.write(object); return out.toString(); } catch (StackOverflowError e) { throw new JSONException("maybe circular references", e); } finally { out.close(); } } public void test_onJSONField() { Map<String, String> map = new HashMap(); map.put("Ariston", null); MapNullValue mapNullValue = new MapNullValue(); mapNullValue.setMap( map ); String json = JSON.toJSONString( mapNullValue ); assertEquals("{\"map\":{\"Ariston\":null}}", json); }
MapTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/FixedLengthRecordSorter.java
{ "start": 18687, "end": 19309 }
class ____ extends AbstractPagedInputView { private final int limit; SingleSegmentInputView(int limit) { super(0); this.limit = limit; } protected void set(MemorySegment segment, int offset) { seekInput(segment, offset, this.limit); } @Override protected MemorySegment nextSegment(MemorySegment current) throws EOFException { throw new EOFException(); } @Override protected int getLimitForSegment(MemorySegment segment) { return this.limit; } } }
SingleSegmentInputView
java
grpc__grpc-java
alts/src/test/java/io/grpc/alts/InternalCheckGcpEnvironmentTest.java
{ "start": 898, "end": 2846 }
class ____ { @Test public void checkGcpLinuxPlatformData() throws Exception { BufferedReader reader; reader = new BufferedReader(new StringReader("HP Z440 Workstation")); assertFalse(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader)); reader = new BufferedReader(new StringReader("Google")); assertTrue(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader)); reader = new BufferedReader(new StringReader("Google Compute Engine")); assertTrue(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader)); reader = new BufferedReader(new StringReader("Google Compute Engine ")); assertTrue(InternalCheckGcpEnvironment.checkProductNameOnLinux(reader)); } @Test public void checkGcpWindowsPlatformData() throws Exception { BufferedReader reader; reader = new BufferedReader(new StringReader("Product : Google")); assertFalse(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); reader = new BufferedReader(new StringReader("Manufacturer : LENOVO")); assertFalse(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); reader = new BufferedReader(new StringReader("Manufacturer : Google Compute Engine")); assertFalse(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); reader = new BufferedReader(new StringReader("Manufacturer : Google")); assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); reader = new BufferedReader(new StringReader("Manufacturer:Google")); assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); reader = new BufferedReader(new StringReader("Manufacturer : Google ")); assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); reader = new BufferedReader(new StringReader("BIOSVersion : 1.0\nManufacturer : Google\n")); assertTrue(InternalCheckGcpEnvironment.checkBiosDataOnWindows(reader)); } }
InternalCheckGcpEnvironmentTest
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskMultipleInputSelectiveReadingTest.java
{ "start": 13600, "end": 14729 }
class ____ extends AbstractStreamOperatorFactory<String> { private final int input1Records; private final int input2Records; private final int maxContinuousReadingRecords; public SpecialRuleReadingStreamOperatorFactory( int input1Records, int input2Records, int maxContinuousReadingRecords) { this.input1Records = input1Records; this.input2Records = input2Records; this.maxContinuousReadingRecords = maxContinuousReadingRecords; } @Override public <T extends StreamOperator<String>> T createStreamOperator( StreamOperatorParameters<String> parameters) { return (T) new SpecialRuleReadingStreamOperator( parameters, input1Records, input2Records, maxContinuousReadingRecords); } @Override public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return SpecialRuleReadingStreamOperator.class; } } private static
SpecialRuleReadingStreamOperatorFactory
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/methodgenerics/targettype/PlainTargetTypeMapper.java
{ "start": 395, "end": 798 }
interface ____ { PlainTargetTypeMapper INSTANCE = Mappers.getMapper( PlainTargetTypeMapper.class ); Target sourceToTarget(Source source); @SuppressWarnings("unchecked") default <T> T map(String string, @TargetType Class<T> clazz) { if ( clazz == BigDecimal.class ) { return (T) new BigDecimal( string ); } return null; }
PlainTargetTypeMapper
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/domain/blog/PostLiteId.java
{ "start": 697, "end": 1218 }
class ____ { private int id; public PostLiteId() { } public void setId(int id) { this.id = id; } public PostLiteId(int aId) { id = aId; } public int getId() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final PostLiteId that = (PostLiteId) o; return id == that.id; } @Override public int hashCode() { return id; } }
PostLiteId
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/state/rocksdb/RocksDBNativeMetricMonitor.java
{ "start": 1574, "end": 5028 }
class ____ implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(RocksDBNativeMetricMonitor.class); private final RocksDBNativeMetricOptions options; private final MetricGroup metricGroup; private final Object lock; static final String COLUMN_FAMILY_KEY = "column_family"; @GuardedBy("lock") private RocksDB rocksDB; @Nullable @GuardedBy("lock") private Statistics statistics; public RocksDBNativeMetricMonitor( @Nonnull RocksDBNativeMetricOptions options, @Nonnull MetricGroup metricGroup, @Nonnull RocksDB rocksDB, @Nullable Statistics statistics) { this.options = options; this.metricGroup = metricGroup; this.rocksDB = rocksDB; this.statistics = statistics; this.lock = new Object(); registerStatistics(); } /** Register gauges to pull native metrics for the database. */ private void registerStatistics() { if (statistics != null) { for (TickerType tickerType : options.getMonitorTickerTypes()) { metricGroup.gauge( String.format("rocksdb.%s", tickerType.name().toLowerCase()), new RocksDBNativeStatisticsMetricView(tickerType)); } } } /** * Register gauges to pull native metrics for the column family. * * @param columnFamilyName group name for the new gauges * @param handle native handle to the column family */ void registerColumnFamily(String columnFamilyName, ColumnFamilyHandle handle) { boolean columnFamilyAsVariable = options.isColumnFamilyAsVariable(); MetricGroup group = columnFamilyAsVariable ? metricGroup.addGroup(COLUMN_FAMILY_KEY, columnFamilyName) : metricGroup.addGroup(columnFamilyName); for (RocksDBProperty property : options.getProperties()) { RocksDBNativePropertyMetricView gauge = new RocksDBNativePropertyMetricView(handle, property); group.gauge(property.getRocksDBProperty(), gauge); } } /** Updates the value of metricView if the reference is still valid. */ private void setProperty(RocksDBNativePropertyMetricView metricView) { if (metricView.isClosed()) { return; } try { synchronized (lock) { if (rocksDB != null) { long value = metricView.property.getNumericalPropertyValue( rocksDB, metricView.handle); metricView.setValue(value); } } } catch (Exception e) { metricView.close(); LOG.warn("Failed to read native metric {} from RocksDB.", metricView.property, e); } } private void setStatistics(RocksDBNativeStatisticsMetricView metricView) { if (metricView.isClosed()) { return; } if (statistics != null) { synchronized (lock) { metricView.setValue(statistics.getTickerCount(metricView.tickerType)); } } } @Override public void close() { synchronized (lock) { rocksDB = null; statistics = null; } } abstract static
RocksDBNativeMetricMonitor
java
elastic__elasticsearch
modules/legacy-geo/src/test/java/org/elasticsearch/legacygeo/GeometryIOTests.java
{ "start": 1234, "end": 4374 }
class ____ extends ESTestCase { public void testRandomSerialization() throws Exception { for (int i = 0; i < randomIntBetween(1, 20); i++) { boolean hasAlt = randomBoolean(); Geometry geometry = randomGeometry(hasAlt); if (shapeSupported(geometry) && randomBoolean()) { // Shape builder conversion doesn't support altitude ShapeBuilder<?, ?, ?> shapeBuilder = geometryToShapeBuilder(geometry); if (randomBoolean()) { Geometry actual = shapeBuilder.buildGeometry(); assertEquals(geometry, actual); } if (randomBoolean()) { // Test ShapeBuilder -> Geometry Serialization try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeNamedWriteable(shapeBuilder); try (StreamInput in = out.bytes().streamInput()) { Geometry actual = GeometryIO.readGeometry(in); assertEquals(geometry, actual); assertEquals(0, in.available()); } } } else { // Test Geometry -> ShapeBuilder Serialization try (BytesStreamOutput out = new BytesStreamOutput()) { GeometryIO.writeGeometry(out, geometry); try (StreamInput in = out.bytes().streamInput()) { try (StreamInput nin = new NamedWriteableAwareStreamInput(in, this.writableRegistry())) { ShapeBuilder<?, ?, ?> actual = nin.readNamedWriteable(ShapeBuilder.class); assertEquals(shapeBuilder, actual); assertEquals(0, in.available()); } } } } // Test Geometry -> Geometry try (BytesStreamOutput out = new BytesStreamOutput()) { GeometryIO.writeGeometry(out, geometry); ; try (StreamInput in = out.bytes().streamInput()) { Geometry actual = GeometryIO.readGeometry(in); assertEquals(geometry, actual); assertEquals(0, in.available()); } } } } } private boolean shapeSupported(Geometry geometry) { if (geometry.hasZ()) { return false; } if (geometry.type() == ShapeType.GEOMETRYCOLLECTION) { GeometryCollection<?> collection = (GeometryCollection<?>) geometry; for (Geometry g : collection) { if (shapeSupported(g) == false) { return false; } } } return true; } @Override protected NamedWriteableRegistry writableRegistry() { return new NamedWriteableRegistry(GeoShapeType.getShapeWriteables()); } }
GeometryIOTests
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractJacksonView.java
{ "start": 2088, "end": 7892 }
class ____ extends AbstractView { protected static final String JSON_VIEW_HINT = JsonView.class.getName(); protected static final String FILTER_PROVIDER_HINT = FilterProvider.class.getName(); private static volatile @Nullable List<JacksonModule> modules; private final ObjectMapper mapper; private JsonEncoding encoding = JsonEncoding.UTF8; private boolean disableCaching = true; protected boolean updateContentLength = false; protected AbstractJacksonView(MapperBuilder<?, ?> builder, String contentType) { this.mapper = builder.addModules(initModules()).build(); setContentType(contentType); setExposePathVariables(false); } protected AbstractJacksonView(ObjectMapper mapper, String contentType) { this.mapper = mapper; setContentType(contentType); setExposePathVariables(false); } private List<JacksonModule> initModules() { if (modules == null) { modules = MapperBuilder.findModules(AbstractJacksonHttpMessageConverter.class.getClassLoader()); } return Objects.requireNonNull(modules); } /** * Set the {@code JsonEncoding} for this view. * <p>Default is {@linkplain JsonEncoding#UTF8 UTF-8}. */ public void setEncoding(JsonEncoding encoding) { Assert.notNull(encoding, "'encoding' must not be null"); this.encoding = encoding; } /** * Return the {@code JsonEncoding} for this view. */ public final JsonEncoding getEncoding() { return this.encoding; } /** * Disables caching of the generated JSON. * <p>Default is {@code true}, which will prevent the client from caching the * generated JSON. */ public void setDisableCaching(boolean disableCaching) { this.disableCaching = disableCaching; } /** * Whether to update the 'Content-Length' header of the response. When set to * {@code true}, the response is buffered in order to determine the content * length and set the 'Content-Length' header of the response. * <p>The default setting is {@code false}. */ public void setUpdateContentLength(boolean updateContentLength) { this.updateContentLength = updateContentLength; } @Override protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) { setResponseContentType(request, response); response.setCharacterEncoding(this.encoding.getJavaName()); if (this.disableCaching) { response.addHeader("Cache-Control", "no-store"); } } @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { ByteArrayOutputStream temporaryStream = null; OutputStream stream; if (this.updateContentLength) { temporaryStream = createTemporaryOutputStream(); stream = temporaryStream; } else { stream = response.getOutputStream(); } Object value = filterModel(model, request); Map<String, Object> hints = null; boolean containsFilterProviderHint = model.containsKey(FILTER_PROVIDER_HINT); if (model.containsKey(JSON_VIEW_HINT)) { if (containsFilterProviderHint) { hints = new HashMap<>(2); hints.put(JSON_VIEW_HINT, model.get(JSON_VIEW_HINT)); hints.put(FILTER_PROVIDER_HINT, model.get(FILTER_PROVIDER_HINT)); } else { hints = Collections.singletonMap(JSON_VIEW_HINT, model.get(JSON_VIEW_HINT)); } } else if (containsFilterProviderHint) { hints = Collections.singletonMap(FILTER_PROVIDER_HINT, model.get(FILTER_PROVIDER_HINT)); } writeContent(stream, value, hints); if (temporaryStream != null) { writeToResponse(response, temporaryStream); } } /** * Write the actual JSON content to the stream. * @param stream the output stream to use * @param object the value to be rendered, as returned from {@link #filterModel} * @param hints additional information about how to serialize the data * @throws IOException if writing failed */ protected void writeContent(OutputStream stream, Object object, @Nullable Map<String, Object> hints) throws IOException { try (JsonGenerator generator = this.mapper.createGenerator(stream, this.encoding)) { writePrefix(generator, object); Class<?> serializationView = null; FilterProvider filters = null; if (hints != null) { serializationView = (Class<?>) hints.get(JSON_VIEW_HINT); filters = (FilterProvider) hints.get(FILTER_PROVIDER_HINT); } ObjectWriter objectWriter = (serializationView != null ? this.mapper.writerWithView(serializationView) : this.mapper.writer()); if (filters != null) { objectWriter = objectWriter.with(filters); } objectWriter.writeValue(generator, object); writeSuffix(generator, object); generator.flush(); } } /** * Set the attribute in the model that should be rendered by this view. * <p>When set, all other model attributes will be ignored. */ public abstract void setModelKey(String modelKey); /** * Filter out undesired attributes from the given model. * <p>The return value can be either another {@link Map} or a single value object. * @param model the model, as passed on to {@link #renderMergedOutputModel} * @param request current HTTP request * @return the value to be rendered */ protected abstract Object filterModel(Map<String, Object> model, HttpServletRequest request); /** * Write a prefix before the main content. * @param generator the generator to use for writing content * @param object the object to write to the output message */ protected void writePrefix(JsonGenerator generator, Object object) throws IOException { } /** * Write a suffix after the main content. * @param generator the generator to use for writing content * @param object the object to write to the output message */ protected void writeSuffix(JsonGenerator generator, Object object) throws IOException { } }
AbstractJacksonView
java
quarkusio__quarkus
integration-tests/grpc-interceptors/src/main/java/io/quarkus/grpc/examples/interceptors/ClientInterceptors.java
{ "start": 520, "end": 696 }
class ____ { @GlobalInterceptor @Produces MethodTarget methodTarget() { return new MethodTarget(); } } abstract static
Producer
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/DeletedEntities.java
{ "start": 868, "end": 2929 }
class ____ { private Integer id1; private Integer id2; private Integer id3; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { // Revision 1 scope.inEntityManager( em -> { em.getTransaction().begin(); StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 ); StrIntTestEntity site2 = new StrIntTestEntity( "b", 11 ); em.persist( site1 ); em.persist( site2 ); id2 = site2.getId(); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); site2 = em.find( StrIntTestEntity.class, id2 ); em.remove( site2 ); em.getTransaction().commit(); } ); } @Test public void testProjectionsInEntitiesAtRevision(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( 2, auditReader.createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 1 ).getResultList().size() ); assertEquals( 1, auditReader.createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 2 ).getResultList().size() ); assertEquals( 2L, auditReader.createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 1 ) .addProjection( AuditEntity.id().count() ).getResultList().get( 0 ) ); assertEquals( 1L, auditReader.createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 2 ) .addProjection( AuditEntity.id().count() ).getResultList().get( 0 ) ); } ); } @Test public void testRevisionsOfEntityWithoutDelete(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var result = AuditReaderFactory.get( em ).createQuery() .forRevisionsOfEntity( StrIntTestEntity.class, false, false ) .add( AuditEntity.id().eq( id2 ) ) .getResultList(); assertEquals( 1, result.size() ); assertEquals( new StrIntTestEntity( "b", 11, id2 ), ((Object[]) result.get( 0 ))[0] ); assertEquals( 1, ((SequenceIdRevisionEntity) ((Object[]) result.get( 0 ))[1]).getId() ); assertEquals( RevisionType.ADD, ((Object[]) result.get( 0 ))[2] ); } ); } }
DeletedEntities
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/PositionedReadable.java
{ "start": 1951, "end": 6589 }
interface ____ { /** * Read up to the specified number of bytes, from a given * position within a file, and return the number of bytes read. This does not * change the current offset of a file, and is thread-safe. * * <i>Warning: Not all filesystems satisfy the thread-safety requirement.</i> * @param position position within file * @param buffer destination buffer * @param offset offset in the buffer * @param length number of bytes to read * @return actual number of bytes read; -1 means "none" * @throws IOException IO problems. */ int read(long position, byte[] buffer, int offset, int length) throws IOException; /** * Read the specified number of bytes, from a given * position within a file. This does not * change the current offset of a file, and is thread-safe. * * <i>Warning: Not all filesystems satisfy the thread-safety requirement.</i> * @param position position within file * @param buffer destination buffer * @param offset offset in the buffer * @param length number of bytes to read * @throws IOException IO problems. * @throws EOFException the end of the data was reached before * the read operation completed */ void readFully(long position, byte[] buffer, int offset, int length) throws IOException; /** * Read number of bytes equal to the length of the buffer, from a given * position within a file. This does not * change the current offset of a file, and is thread-safe. * * <i>Warning: Not all filesystems satisfy the thread-safety requirement.</i> * @param position position within file * @param buffer destination buffer * @throws IOException IO problems. * @throws EOFException the end of the data was reached before * the read operation completed */ void readFully(long position, byte[] buffer) throws IOException; /** * What is the smallest reasonable seek? * @return the minimum number of bytes */ default int minSeekForVectorReads() { return S_16K; } /** * What is the largest size that we should group ranges together as? * @return the number of bytes to read at once */ default int maxReadSizeForVectorReads() { return S_1M; } /** * Read fully a list of file ranges asynchronously from this file. * The default iterates through the ranges to read each synchronously, but * the intent is that FSDataInputStream subclasses can make more efficient * readers. * As a result of the call, each range will have FileRange.setData(CompletableFuture) * called with a future that when complete will have a ByteBuffer with the * data from the file's range. * <p> * The position returned by getPos() after readVectored() is undefined. * </p> * <p> * If a file is changed while the readVectored() operation is in progress, the output is * undefined. Some ranges may have old data, some may have new and some may have both. * </p> * <p> * While a readVectored() operation is in progress, normal read api calls may block. * </p> * @param ranges the byte ranges to read * @param allocate the function to allocate ByteBuffer * @throws IOException any IOE. * @throws IllegalArgumentException if the any of ranges are invalid, or they overlap. */ default void readVectored(List<? extends FileRange> ranges, IntFunction<ByteBuffer> allocate) throws IOException { VectoredReadUtils.readVectored(this, ranges, allocate); } /** * Extension of {@link #readVectored(List, IntFunction)} where a {@code release(buffer)} * operation may be invoked if problems surface during reads. * <p> * The {@code release} operation is invoked after an IOException * to return the actively buffer to a pool before reporting a failure * in the future. * <p> * The default implementation calls {@link #readVectored(List, IntFunction)}.p * <p> * Implementations SHOULD override this method if they can release buffers as * part of their error handling. * @param ranges the byte ranges to read * @param allocate function to allocate ByteBuffer * @param release callable to release a ByteBuffer. * @throws IOException any IOE. * @throws IllegalArgumentException if any of ranges are invalid, or they overlap. * @throws NullPointerException null arguments. */ default void readVectored(List<? extends FileRange> ranges, IntFunction<ByteBuffer> allocate, Consumer<ByteBuffer> release) throws IOException { requireNonNull(release); readVectored(ranges, allocate); } }
PositionedReadable
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
{ "start": 5946, "end": 6362 }
class ____ { SubClass<String> generate() { return null; } } @Test public void can_handle_deep_stubs_with_generics_at_end_of_deep_invocation() { UserOfSubClass mock = mock(UserOfSubClass.class, RETURNS_DEEP_STUBS); when(mock.generate().execute()).thenReturn("sub"); assertThat(mock.generate().execute()).isEqualTo("sub"); } public
UserOfSubClass
java
google__dagger
javatests/dagger/internal/codegen/kotlin/KspComponentProcessorTest.java
{ "start": 7291, "end": 8261 }
class ____ implements MyComponent {", " private final MyComponentImpl myComponentImpl = this;", "", " MyComponentImpl() {", "", "", " }", "", " @Override", " public Foo foo() {", " return new Foo(new Bar());", " }", " }", "}")); }); } @Test public void injectBindingWithProvidersComponentTest() throws Exception { Source componentSrc = CompilerTests.kotlinSource( "MyComponent.kt", "package test", "", "import dagger.Component", "import javax.inject.Inject", "import javax.inject.Provider", "", "@Component", "
MyComponentImpl
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builder/ignore/BuilderIgnoringMappingConfig.java
{ "start": 320, "end": 442 }
interface ____ { @BeanMapping(ignoreByDefault = true) BaseEntity mapBase(BaseDto dto); }
BuilderIgnoringMappingConfig
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointStreamFactory.java
{ "start": 1324, "end": 4206 }
interface ____ { /** * Creates an new {@link CheckpointStateOutputStream}. When the stream is closed, it returns a * state handle that can retrieve the state back. * * @param scope The state's scope, whether it is exclusive or shared. * @return An output stream that writes state for the given checkpoint. * @throws IOException Exceptions may occur while creating the stream and should be forwarded. */ CheckpointStateOutputStream createCheckpointStateOutputStream(CheckpointedStateScope scope) throws IOException; /** * Tells if we can duplicate the given {@link StreamStateHandle} into the path corresponding to * the given {@link CheckpointedStateScope}. * * <p>This should be a rather cheap operation, preferably not involving any remote accesses. * * @param stateHandle The handle to duplicate * @param scope Scope determining the location to duplicate into * @return true, if we can perform the duplication */ boolean canFastDuplicate(StreamStateHandle stateHandle, CheckpointedStateScope scope) throws IOException; /** * Duplicates {@link StreamStateHandle} into the path corresponding to * the given {@link * CheckpointedStateScope}. * * <p>You should first check if you can duplicate with {@link * #canFastDuplicate(StreamStateHandle, CheckpointedStateScope)}. * * @param stateHandles The handles to duplicate * @param scope Scope determining the location to duplicate into * @return The duplicated handle */ List<StreamStateHandle> duplicate( List<StreamStateHandle> stateHandles, CheckpointedStateScope scope) throws IOException; /** * A callback method when some previous handle is reused. It is needed by the file merging * mechanism (FLIP-306) which will manage the life cycle of underlying files by file-reusing * information. * * @param previousHandle the previous handles that will be reused. */ default void reusePreviousStateHandle(Collection<? extends StreamStateHandle> previousHandle) { // Does nothing for normal stream factory } /** * A pre-check hook before the checkpoint writer want to reuse a state handle, if this returns * false, it is not recommended for the writer to rewrite the state file considering the space * amplification. * * @param stateHandle the handle to be reused. * @return true if it can be reused. */ default boolean couldReuseStateHandle(StreamStateHandle stateHandle) { // By default, the CheckpointStreamFactory doesn't support snapshot-file-merging, so the // SegmentFileStateHandle type of stateHandle can not be reused. return !FileMergingSnapshotManager.isFileMergingHandle(stateHandle); } }
CheckpointStreamFactory
java
square__retrofit
retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/ObservableThrowingTest.java
{ "start": 1667, "end": 10344 }
interface ____ { @GET("/") Observable<String> body(); @GET("/") Observable<Response<String>> response(); @GET("/") Observable<Result<String>> result(); } private Service service; @Before public void setUp() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new StringConverterFactory()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); service = retrofit.create(Service.class); } @Test public void bodyThrowingInOnNextDeliveredToError() { server.enqueue(new MockResponse()); RecordingObserver<String> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .body() .subscribe( new ForwardingObserver<String>(observer) { @Override public void onNext(String value) { throw e; } }); observer.assertError(e); } @Test public void bodyThrowingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler( throwable -> { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } }); RecordingObserver<String> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .body() .subscribe( new ForwardingObserver<String>(observer) { @Override public void onComplete() { throw e; } }); observer.assertAnyValue(); Throwable throwable = throwableRef.get(); assertThat(throwable).isInstanceOf(UndeliverableException.class); assertThat(throwable).hasCauseThat().isSameInstanceAs(e); } @Test public void bodyThrowingInOnErrorDeliveredToPlugin() { server.enqueue(new MockResponse().setResponseCode(404)); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler( throwable -> { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } }); RecordingObserver<String> observer = subscriberRule.create(); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final RuntimeException e = new RuntimeException(); service .body() .subscribe( new ForwardingObserver<String>(observer) { @Override public void onError(Throwable throwable) { if (!errorRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } throw e; } }); //noinspection ThrowableResultOfMethodCallIgnored CompositeException composite = (CompositeException) throwableRef.get(); assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e); } @Test public void responseThrowingInOnNextDeliveredToError() { server.enqueue(new MockResponse()); RecordingObserver<Response<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .response() .subscribe( new ForwardingObserver<Response<String>>(observer) { @Override public void onNext(Response<String> value) { throw e; } }); observer.assertError(e); } @Test public void responseThrowingInOnCompleteDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler( throwable -> { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } }); RecordingObserver<Response<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .response() .subscribe( new ForwardingObserver<Response<String>>(observer) { @Override public void onComplete() { throw e; } }); observer.assertAnyValue(); Throwable throwable = throwableRef.get(); assertThat(throwable).isInstanceOf(UndeliverableException.class); assertThat(throwable).hasCauseThat().isSameInstanceAs(e); } @Test public void responseThrowingInOnErrorDeliveredToPlugin() { server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST)); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler( throwable -> { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } }); RecordingObserver<Response<String>> observer = subscriberRule.create(); final AtomicReference<Throwable> errorRef = new AtomicReference<>(); final RuntimeException e = new RuntimeException(); service .response() .subscribe( new ForwardingObserver<Response<String>>(observer) { @Override public void onError(Throwable throwable) { if (!errorRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } throw e; } }); //noinspection ThrowableResultOfMethodCallIgnored CompositeException composite = (CompositeException) throwableRef.get(); assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e); } @Test public void resultThrowingInOnNextDeliveredToError() { server.enqueue(new MockResponse()); RecordingObserver<Result<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .result() .subscribe( new ForwardingObserver<Result<String>>(observer) { @Override public void onNext(Result<String> value) { throw e; } }); observer.assertError(e); } @Test public void resultThrowingInOnCompletedDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler( throwable -> { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } }); RecordingObserver<Result<String>> observer = subscriberRule.create(); final RuntimeException e = new RuntimeException(); service .result() .subscribe( new ForwardingObserver<Result<String>>(observer) { @Override public void onComplete() { throw e; } }); observer.assertAnyValue(); Throwable throwable = throwableRef.get(); assertThat(throwable).isInstanceOf(UndeliverableException.class); assertThat(throwable).hasCauseThat().isSameInstanceAs(e); } @Test public void resultThrowingInOnErrorDeliveredToPlugin() { server.enqueue(new MockResponse()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler( throwable -> { if (!throwableRef.compareAndSet(null, throwable)) { throw Exceptions.propagate(throwable); } }); RecordingObserver<Result<String>> observer = subscriberRule.create(); final RuntimeException first = new RuntimeException(); final RuntimeException second = new RuntimeException(); service .result() .subscribe( new ForwardingObserver<Result<String>>(observer) { @Override public void onNext(Result<String> value) { // The only way to trigger onError for a result is if onNext throws. throw first; } @Override public void onError(Throwable throwable) { throw second; } }); //noinspection ThrowableResultOfMethodCallIgnored CompositeException composite = (CompositeException) throwableRef.get(); assertThat(composite.getExceptions()).containsExactly(first, second); } private abstract static
Service
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleDoOnLifecycle.java
{ "start": 1178, "end": 1781 }
class ____<T> extends Single<T> { final Single<T> source; final Consumer<? super Disposable> onSubscribe; final Action onDispose; public SingleDoOnLifecycle(Single<T> upstream, Consumer<? super Disposable> onSubscribe, Action onDispose) { this.source = upstream; this.onSubscribe = onSubscribe; this.onDispose = onDispose; } @Override protected void subscribeActual(SingleObserver<? super T> observer) { source.subscribe(new SingleLifecycleObserver<>(observer, onSubscribe, onDispose)); } static final
SingleDoOnLifecycle
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java
{ "start": 34573, "end": 34632 }
class ____ extends GenericBaseClass { } private static
BRaw
java
spring-projects__spring-framework
spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceUnitPostProcessor.java
{ "start": 696, "end": 1251 }
interface ____ post-processing a {@link MutablePersistenceUnitInfo} * configuration that Spring prepares for JPA persistence unit bootstrapping. * * <p>Implementations can be registered with a {@link DefaultPersistenceUnitManager} * or via a {@link org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean}. * * @author Juergen Hoeller * @since 2.0 * @see DefaultPersistenceUnitManager#setPersistenceUnitPostProcessors * @see org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#setPersistenceUnitPostProcessors */ public
for
java
spring-projects__spring-security
test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java
{ "start": 16371, "end": 16848 }
class ____ implements WebFilter { private final Supplier<Mono<SecurityContext>> context; private SetupMutatorFilter(Supplier<Mono<SecurityContext>> context) { this.context = context; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain webFilterChain) { exchange.getAttributes().computeIfAbsent(MutatorFilter.ATTRIBUTE_NAME, (key) -> this.context); return webFilterChain.filter(exchange); } } private static
SetupMutatorFilter
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ApplicationId.java
{ "start": 1608, "end": 5278 }
class ____ implements Comparable<ApplicationId> { @Private @Unstable public static final String appIdStrPrefix = "application"; private static final String APPLICATION_ID_PREFIX = appIdStrPrefix + '_'; @Public @Unstable public static ApplicationId newInstance(long clusterTimestamp, int id) { ApplicationId appId = Records.newRecord(ApplicationId.class); appId.setClusterTimestamp(clusterTimestamp); appId.setId(id); appId.build(); return appId; } /** * Get the short integer identifier of the <code>ApplicationId</code> * which is unique for all applications started by a particular instance * of the <code>ResourceManager</code>. * @return short integer identifier of the <code>ApplicationId</code> */ @Public @Stable public abstract int getId(); @Private @Unstable protected abstract void setId(int id); /** * Get the <em>start time</em> of the <code>ResourceManager</code> which is * used to generate globally unique <code>ApplicationId</code>. * @return <em>start time</em> of the <code>ResourceManager</code> */ @Public @Stable public abstract long getClusterTimestamp(); @Private @Unstable protected abstract void setClusterTimestamp(long clusterTimestamp); protected abstract void build(); private static final int APP_ID_MIN_DIGITS = 4; @Override public int compareTo(ApplicationId other) { if (this.getClusterTimestamp() - other.getClusterTimestamp() == 0) { return this.getId() - other.getId(); } else { return this.getClusterTimestamp() > other.getClusterTimestamp() ? 1 : this.getClusterTimestamp() < other.getClusterTimestamp() ? -1 : 0; } } @Override public String toString() { StringBuilder sb = new StringBuilder(64); sb.append(APPLICATION_ID_PREFIX) .append(getClusterTimestamp()) .append('_'); FastNumberFormat.format(sb, getId(), APP_ID_MIN_DIGITS); return sb.toString(); } @Public @Stable public static ApplicationId fromString(String appIdStr) { if (!appIdStr.startsWith(APPLICATION_ID_PREFIX)) { throw new IllegalArgumentException("Invalid ApplicationId prefix: " + appIdStr + ". The valid ApplicationId should start with prefix " + appIdStrPrefix); } try { int pos1 = APPLICATION_ID_PREFIX.length() - 1; int pos2 = appIdStr.indexOf('_', pos1 + 1); if (pos2 < 0) { throw new IllegalArgumentException("Invalid ApplicationId: " + appIdStr); } long rmId = Long.parseLong(appIdStr.substring(pos1 + 1, pos2)); int appId = Integer.parseInt(appIdStr.substring(pos2 + 1)); ApplicationId applicationId = ApplicationId.newInstance(rmId, appId); return applicationId; } catch (NumberFormatException n) { throw new IllegalArgumentException("Invalid ApplicationId: " + appIdStr, n); } } @Override public int hashCode() { // Generated by eclipse. final int prime = 371237; int result = 6521; long clusterTimestamp = getClusterTimestamp(); result = prime * result + (int) (clusterTimestamp ^ (clusterTimestamp >>> 32)); result = prime * result + getId(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ApplicationId other = (ApplicationId) obj; if (this.getClusterTimestamp() != other.getClusterTimestamp()) return false; if (this.getId() != other.getId()) return false; return true; } }
ApplicationId