method2testcases
stringlengths
118
6.63k
### Question: RemoteInputChannel extends InputChannel implements BufferRecycler, BufferListener { public void onFailedPartitionRequest() { inputGate.triggerPartitionStateCheck(partitionId); } RemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ConnectionID connectionId, ConnectionManager connectionManager, TaskIOMetricGroup metrics); RemoteInputChannel( SingleInputGate inputGate, int channelIndex, ResultPartitionID partitionId, ConnectionID connectionId, ConnectionManager connectionManager, int initialBackOff, int maxBackoff, TaskIOMetricGroup metrics); @VisibleForTesting @Override void requestSubpartition(int subpartitionIndex); @Override boolean isReleased(); @Override String toString(); @Override void recycle(MemorySegment segment); int getNumberOfAvailableBuffers(); int getNumberOfRequiredBuffers(); int getSenderBacklog(); @Override boolean notifyBufferAvailable(Buffer buffer); @Override void notifyBufferDestroyed(); int getUnannouncedCredit(); int getAndResetUnannouncedCredit(); int getNumberOfQueuedBuffers(); int unsynchronizedGetNumberOfQueuedBuffers(); InputChannelID getInputChannelId(); int getInitialCredit(); BufferProvider getBufferProvider(); @Nullable Buffer requestBuffer(); void onBuffer(Buffer buffer, int sequenceNumber, int backlog); void onEmptyBuffer(int sequenceNumber, int backlog); void onFailedPartitionRequest(); void onError(Throwable cause); }### Answer: @Test public void testOnFailedPartitionRequest() throws Exception { final ConnectionManager connectionManager = mock(ConnectionManager.class); when(connectionManager.createPartitionRequestClient(any(ConnectionID.class))) .thenReturn(mock(PartitionRequestClient.class)); final ResultPartitionID partitionId = new ResultPartitionID(); final SingleInputGate inputGate = mock(SingleInputGate.class); final RemoteInputChannel ch = new RemoteInputChannel( inputGate, 0, partitionId, mock(ConnectionID.class), connectionManager, UnregisteredMetricGroups.createUnregisteredTaskMetricGroup().getIOMetricGroup()); ch.onFailedPartitionRequest(); verify(inputGate).triggerPartitionStateCheck(eq(partitionId)); }
### Question: EventSerializer { private static boolean isEvent(ByteBuffer buffer, Class<?> eventClass) throws IOException { if (buffer.remaining() < 4) { throw new IOException("Incomplete event"); } final int bufferPos = buffer.position(); final ByteOrder bufferOrder = buffer.order(); buffer.order(ByteOrder.BIG_ENDIAN); try { int type = buffer.getInt(); if (eventClass.equals(EndOfPartitionEvent.class)) { return type == END_OF_PARTITION_EVENT; } else if (eventClass.equals(CheckpointBarrier.class)) { return type == CHECKPOINT_BARRIER_EVENT; } else if (eventClass.equals(EndOfSuperstepEvent.class)) { return type == END_OF_SUPERSTEP_EVENT; } else if (eventClass.equals(CancelCheckpointMarker.class)) { return type == CANCEL_CHECKPOINT_MARKER_EVENT; } else { throw new UnsupportedOperationException("Unsupported eventClass = " + eventClass); } } finally { buffer.order(bufferOrder); buffer.position(bufferPos); } } static ByteBuffer toSerializedEvent(AbstractEvent event); static AbstractEvent fromSerializedEvent(ByteBuffer buffer, ClassLoader classLoader); static Buffer toBuffer(AbstractEvent event); static BufferConsumer toBufferConsumer(AbstractEvent event); static AbstractEvent fromBuffer(Buffer buffer, ClassLoader classLoader); static boolean isEvent(Buffer buffer, Class<?> eventClass); }### Answer: @Test public void testIsEvent() throws Exception { AbstractEvent[] events = { EndOfPartitionEvent.INSTANCE, EndOfSuperstepEvent.INSTANCE, new CheckpointBarrier(1678L, 4623784L, CheckpointOptions.forCheckpointWithDefaultLocation()), new TestTaskEvent(Math.random(), 12361231273L), new CancelCheckpointMarker(287087987329842L) }; Class[] expectedClasses = Arrays.stream(events) .map(AbstractEvent::getClass) .toArray(Class[]::new); for (AbstractEvent evt : events) { for (Class<?> expectedClass: expectedClasses) { if (expectedClass.equals(TestTaskEvent.class)) { try { checkIsEvent(evt, expectedClass); fail("This should fail"); } catch (UnsupportedOperationException ex) { } } else if (evt.getClass().equals(expectedClass)) { assertTrue(checkIsEvent(evt, expectedClass)); } else { assertFalse(checkIsEvent(evt, expectedClass)); } } } }
### Question: SpanningRecordSerializer implements RecordSerializer<T> { @Override public boolean hasSerializedData() { return lengthBuffer.hasRemaining() || dataBuffer.hasRemaining(); } SpanningRecordSerializer(); @Override SerializationResult addRecord(T record); @Override SerializationResult continueWritingWithNextBufferBuilder(BufferBuilder buffer); @Override void clear(); @Override boolean hasSerializedData(); }### Answer: @Test public void testHasSerializedData() throws IOException { final int segmentSize = 16; final SpanningRecordSerializer<SerializationTestType> serializer = new SpanningRecordSerializer<>(); final SerializationTestType randomIntRecord = Util.randomRecord(SerializationTestTypeFactory.INT); Assert.assertFalse(serializer.hasSerializedData()); serializer.addRecord(randomIntRecord); Assert.assertTrue(serializer.hasSerializedData()); serializer.continueWritingWithNextBufferBuilder(createBufferBuilder(segmentSize)); Assert.assertFalse(serializer.hasSerializedData()); serializer.continueWritingWithNextBufferBuilder(createBufferBuilder(8)); serializer.addRecord(randomIntRecord); Assert.assertFalse(serializer.hasSerializedData()); serializer.addRecord(randomIntRecord); Assert.assertTrue(serializer.hasSerializedData()); }
### Question: RecordWriter { public void broadcastEvent(AbstractEvent event) throws IOException { try (BufferConsumer eventBufferConsumer = EventSerializer.toBufferConsumer(event)) { for (int targetChannel = 0; targetChannel < numChannels; targetChannel++) { RecordSerializer<T> serializer = serializers[targetChannel]; tryFinishCurrentBufferBuilder(targetChannel, serializer); targetPartition.addBufferConsumer(eventBufferConsumer.copy(), targetChannel); } if (flushAlways) { flushAll(); } } } RecordWriter(ResultPartitionWriter writer); @SuppressWarnings("unchecked") RecordWriter(ResultPartitionWriter writer, ChannelSelector<T> channelSelector); RecordWriter(ResultPartitionWriter writer, ChannelSelector<T> channelSelector, boolean flushAlways); void emit(T record); void broadcastEmit(T record); void randomEmit(T record); void broadcastEvent(AbstractEvent event); void flushAll(); void clearBuffers(); void setMetricGroup(TaskIOMetricGroup metrics); }### Answer: @Test public void testBroadcastEventNoRecords() throws Exception { int numChannels = 4; int bufferSize = 32; @SuppressWarnings("unchecked") Queue<BufferConsumer>[] queues = new Queue[numChannels]; for (int i = 0; i < numChannels; i++) { queues[i] = new ArrayDeque<>(); } TestPooledBufferProvider bufferProvider = new TestPooledBufferProvider(Integer.MAX_VALUE, bufferSize); ResultPartitionWriter partitionWriter = new CollectingPartitionWriter(queues, bufferProvider); RecordWriter<ByteArrayIO> writer = new RecordWriter<>(partitionWriter, new RoundRobin<ByteArrayIO>()); CheckpointBarrier barrier = new CheckpointBarrier(Integer.MAX_VALUE + 919192L, Integer.MAX_VALUE + 18828228L, CheckpointOptions.forCheckpointWithDefaultLocation()); writer.broadcastEvent(barrier); assertEquals(0, bufferProvider.getNumberOfCreatedBuffers()); for (int i = 0; i < numChannels; i++) { assertEquals(1, queues[i].size()); BufferOrEvent boe = parseBuffer(queues[i].remove(), i); assertTrue(boe.isEvent()); assertEquals(barrier, boe.getEvent()); assertEquals(0, queues[i].size()); } } @Test public void testBroadcastEventBufferReferenceCounting() throws Exception { @SuppressWarnings("unchecked") ArrayDeque<BufferConsumer>[] queues = new ArrayDeque[] { new ArrayDeque(), new ArrayDeque() }; ResultPartitionWriter partition = new CollectingPartitionWriter(queues, new TestPooledBufferProvider(Integer.MAX_VALUE)); RecordWriter<?> writer = new RecordWriter<>(partition); writer.broadcastEvent(EndOfPartitionEvent.INSTANCE); assertEquals(1, queues[0].size()); assertEquals(1, queues[1].size()); BufferConsumer bufferConsumer1 = queues[0].getFirst(); BufferConsumer bufferConsumer2 = queues[1].getFirst(); for (int i = 0; i < queues.length; i++) { assertTrue(parseBuffer(queues[i].remove(), i).isEvent()); } assertTrue(bufferConsumer1.isRecycled()); assertTrue(bufferConsumer2.isRecycled()); } @Test public void testBroadcastEventBufferIndependence() throws Exception { @SuppressWarnings("unchecked") ArrayDeque<BufferConsumer>[] queues = new ArrayDeque[]{new ArrayDeque(), new ArrayDeque()}; ResultPartitionWriter partition = new CollectingPartitionWriter(queues, new TestPooledBufferProvider(Integer.MAX_VALUE)); RecordWriter<?> writer = new RecordWriter<>(partition); writer.broadcastEvent(EndOfPartitionEvent.INSTANCE); assertEquals(1, queues[0].size()); assertEquals(1, queues[1].size()); Buffer buffer1 = buildSingleBuffer(queues[0].remove()); Buffer buffer2 = buildSingleBuffer(queues[1].remove()); assertEquals(0, buffer1.getReaderIndex()); assertEquals(0, buffer2.getReaderIndex()); buffer1.setReaderIndex(1); assertEquals("Buffer 2 shares the same reader index as buffer 1", 0, buffer2.getReaderIndex()); }
### Question: LocalBufferPool implements BufferPool { @Override public void setNumBuffers(int numBuffers) throws IOException { synchronized (availableMemorySegments) { checkArgument(numBuffers >= numberOfRequiredMemorySegments, "Buffer pool needs at least %s buffers, but tried to set to %s", numberOfRequiredMemorySegments, numBuffers); if (numBuffers > maxNumberOfMemorySegments) { currentPoolSize = maxNumberOfMemorySegments; } else { currentPoolSize = numBuffers; } returnExcessMemorySegments(); if (owner != null && numberOfRequestedMemorySegments > currentPoolSize) { owner.releaseMemory(numberOfRequestedMemorySegments - numBuffers); } } } LocalBufferPool(NetworkBufferPool networkBufferPool, int numberOfRequiredMemorySegments); LocalBufferPool(NetworkBufferPool networkBufferPool, int numberOfRequiredMemorySegments, int maxNumberOfMemorySegments); @Override boolean isDestroyed(); @Override int getMemorySegmentSize(); @Override int getNumberOfRequiredMemorySegments(); @Override int getMaxNumberOfMemorySegments(); @Override int getNumberOfAvailableMemorySegments(); @Override int getNumBuffers(); @Override int bestEffortGetNumOfUsedBuffers(); @Override void setBufferPoolOwner(BufferPoolOwner owner); @Override Buffer requestBuffer(); @Override Buffer requestBufferBlocking(); @Override BufferBuilder requestBufferBuilderBlocking(); @Override void recycle(MemorySegment segment); @Override void lazyDestroy(); @Override boolean addBufferListener(BufferListener listener); @Override void setNumBuffers(int numBuffers); @Override String toString(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testSetLessThanRequiredNumBuffers() throws IOException { localBufferPool.setNumBuffers(1); localBufferPool.setNumBuffers(0); } @Test @SuppressWarnings("unchecked") public void testConcurrentRequestRecycle() throws ExecutionException, InterruptedException, IOException { int numConcurrentTasks = 128; int numBuffersToRequestPerTask = 1024; localBufferPool.setNumBuffers(numConcurrentTasks); Future<Boolean>[] taskResults = new Future[numConcurrentTasks]; for (int i = 0; i < numConcurrentTasks; i++) { taskResults[i] = executor.submit(new BufferRequesterTask(localBufferPool, numBuffersToRequestPerTask)); } for (int i = 0; i < numConcurrentTasks; i++) { assertTrue(taskResults[i].get()); } }
### Question: Scheduler implements InstanceListener, SlotAvailabilityListener, SlotProvider { @Override public CompletableFuture<LogicalSlot> allocateSlot( SlotRequestId slotRequestId, ScheduledUnit task, boolean allowQueued, SlotProfile slotProfile, Time allocationTimeout) { try { final Object ret = scheduleTask(task, allowQueued, slotProfile.getPreferredLocations()); if (ret instanceof SimpleSlot) { return CompletableFuture.completedFuture((SimpleSlot) ret); } else if (ret instanceof CompletableFuture) { @SuppressWarnings("unchecked") CompletableFuture<LogicalSlot> typed = (CompletableFuture<LogicalSlot>) ret; return FutureUtils.orTimeout(typed, allocationTimeout.toMilliseconds(), TimeUnit.MILLISECONDS); } else { throw new RuntimeException(); } } catch (NoResourceAvailableException e) { return FutureUtils.completedExceptionally(e); } } Scheduler(Executor executor); void shutdown(); @Override CompletableFuture<LogicalSlot> allocateSlot( SlotRequestId slotRequestId, ScheduledUnit task, boolean allowQueued, SlotProfile slotProfile, Time allocationTimeout); @Override CompletableFuture<Acknowledge> cancelSlotRequest(SlotRequestId slotRequestId, @Nullable SlotSharingGroupId slotSharingGroupId, Throwable cause); @Override void newSlotAvailable(final Instance instance); @Override void newInstanceAvailable(Instance instance); @Override void instanceDied(Instance instance); int getNumberOfAvailableSlots(); int getTotalNumberOfSlots(); int getNumberOfAvailableInstances(); int getNumberOfInstancesWithAvailableSlots(); Map<String, List<Instance>> getInstancesByHost(); int getNumberOfUnconstrainedAssignments(); int getNumberOfLocalizedAssignments(); int getNumberOfNonLocalizedAssignments(); @VisibleForTesting @Nullable Instance getInstance(ResourceID resourceId); }### Answer: @Test public void testSlotAllocationTimeout() throws Exception { final Scheduler scheduler = new Scheduler(TestingUtils.defaultExecutor()); final ExecutionGraph executionGraph = ExecutionGraphTestUtils.createSimpleTestGraph(); final Map<ExecutionAttemptID, Execution> registeredExecutions = executionGraph.getRegisteredExecutions(); assertThat(registeredExecutions.values(), Matchers.not(Matchers.empty())); final Execution execution = registeredExecutions.values().iterator().next(); final CompletableFuture<LogicalSlot> slotFuture = scheduler.allocateSlot( new ScheduledUnit( execution), true, SlotProfile.noRequirements(), Time.milliseconds(1L)); try { slotFuture.get(); } catch (ExecutionException ee) { assertThat(ExceptionUtils.stripExecutionException(ee), Matchers.instanceOf(TimeoutException.class)); } }
### Question: CoLocationConstraint { public AbstractID getGroupId() { return this.group.getId(); } CoLocationConstraint(CoLocationGroup group); SharedSlot getSharedSlot(); AbstractID getGroupId(); boolean isAssigned(); boolean isAssignedAndAlive(); TaskManagerLocation getLocation(); void setSharedSlot(SharedSlot newSlot); void lockLocation(); void lockLocation(TaskManagerLocation taskManagerLocation); void setSlotRequestId(@Nullable SlotRequestId slotRequestId); @Nullable SlotRequestId getSlotRequestId(); @Override String toString(); }### Answer: @Test public void testCreateConstraints() { try { JobVertexID id1 = new JobVertexID(); JobVertexID id2 = new JobVertexID(); JobVertex vertex1 = new JobVertex("vertex1", id1); vertex1.setParallelism(2); JobVertex vertex2 = new JobVertex("vertex2", id2); vertex2.setParallelism(3); CoLocationGroup group = new CoLocationGroup(vertex1, vertex2); AbstractID groupId = group.getId(); assertNotNull(groupId); CoLocationConstraint constraint1 = group.getLocationConstraint(0); CoLocationConstraint constraint2 = group.getLocationConstraint(1); CoLocationConstraint constraint3 = group.getLocationConstraint(2); assertFalse(constraint1 == constraint2); assertFalse(constraint1 == constraint3); assertFalse(constraint2 == constraint3); assertEquals(groupId, constraint1.getGroupId()); assertEquals(groupId, constraint2.getGroupId()); assertEquals(groupId, constraint3.getGroupId()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
### Question: StandaloneHaServices extends AbstractNonHaServices { @Override public LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID) { synchronized (lock) { checkNotShutdown(); return new StandaloneLeaderRetrievalService(jobManagerAddress, DEFAULT_LEADER_ID); } } StandaloneHaServices( String resourceManagerAddress, String dispatcherAddress, String jobManagerAddress, String webMonitorAddress); @Override LeaderRetrievalService getResourceManagerLeaderRetriever(); @Override LeaderRetrievalService getDispatcherLeaderRetriever(); @Override LeaderElectionService getResourceManagerLeaderElectionService(); @Override LeaderElectionService getDispatcherLeaderElectionService(); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID, String defaultJobManagerAddress); @Override LeaderElectionService getJobManagerLeaderElectionService(JobID jobID); @Override LeaderRetrievalService getWebMonitorLeaderRetriever(); @Override LeaderElectionService getWebMonitorLeaderElectionService(); }### Answer: @Test public void testJobMasterLeaderRetrieval() throws Exception { JobID jobId1 = new JobID(); JobID jobId2 = new JobID(); final String jobManagerAddress1 = "foobar"; final String jobManagerAddress2 = "barfoo"; LeaderRetrievalListener jmListener1 = mock(LeaderRetrievalListener.class); LeaderRetrievalListener jmListener2 = mock(LeaderRetrievalListener.class); LeaderRetrievalService jmLeaderRetrievalService1 = standaloneHaServices.getJobManagerLeaderRetriever(jobId1, jobManagerAddress1); LeaderRetrievalService jmLeaderRetrievalService2 = standaloneHaServices.getJobManagerLeaderRetriever(jobId2, jobManagerAddress2); jmLeaderRetrievalService1.start(jmListener1); jmLeaderRetrievalService2.start(jmListener2); verify(jmListener1).notifyLeaderAddress(eq(jobManagerAddress1), eq(HighAvailabilityServices.DEFAULT_LEADER_ID)); verify(jmListener2).notifyLeaderAddress(eq(jobManagerAddress2), eq(HighAvailabilityServices.DEFAULT_LEADER_ID)); }
### Question: EmbeddedHaServices extends AbstractNonHaServices { @Override public LeaderElectionService getJobManagerLeaderElectionService(JobID jobID) { checkNotNull(jobID); synchronized (lock) { checkNotShutdown(); EmbeddedLeaderService service = getOrCreateJobManagerService(jobID); return service.createLeaderElectionService(); } } EmbeddedHaServices(Executor executor); @Override LeaderRetrievalService getResourceManagerLeaderRetriever(); @Override LeaderRetrievalService getDispatcherLeaderRetriever(); @Override LeaderElectionService getResourceManagerLeaderElectionService(); @Override LeaderElectionService getDispatcherLeaderElectionService(); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID, String defaultJobManagerAddress); @Override LeaderRetrievalService getWebMonitorLeaderRetriever(); @Override LeaderElectionService getJobManagerLeaderElectionService(JobID jobID); @Override LeaderElectionService getWebMonitorLeaderElectionService(); @Override void close(); }### Answer: @Test public void testJobManagerLeaderElection() throws Exception { JobID jobId1 = new JobID(); JobID jobId2 = new JobID(); LeaderContender leaderContender1 = mock(LeaderContender.class); LeaderContender leaderContender2 = mock(LeaderContender.class); LeaderContender leaderContenderDifferentJobId = mock(LeaderContender.class); LeaderElectionService leaderElectionService1 = embeddedHaServices.getJobManagerLeaderElectionService(jobId1); LeaderElectionService leaderElectionService2 = embeddedHaServices.getJobManagerLeaderElectionService(jobId1); LeaderElectionService leaderElectionServiceDifferentJobId = embeddedHaServices.getJobManagerLeaderElectionService(jobId2); leaderElectionService1.start(leaderContender1); leaderElectionService2.start(leaderContender2); leaderElectionServiceDifferentJobId.start(leaderContenderDifferentJobId); ArgumentCaptor<UUID> leaderIdArgumentCaptor1 = ArgumentCaptor.forClass(UUID.class); ArgumentCaptor<UUID> leaderIdArgumentCaptor2 = ArgumentCaptor.forClass(UUID.class); verify(leaderContender1, atLeast(0)).grantLeadership(leaderIdArgumentCaptor1.capture()); verify(leaderContender2, atLeast(0)).grantLeadership(leaderIdArgumentCaptor2.capture()); assertTrue(leaderIdArgumentCaptor1.getAllValues().isEmpty() ^ leaderIdArgumentCaptor2.getAllValues().isEmpty()); verify(leaderContenderDifferentJobId).grantLeadership(any(UUID.class)); }
### Question: EmbeddedHaServices extends AbstractNonHaServices { @Override public LeaderElectionService getResourceManagerLeaderElectionService() { return resourceManagerLeaderService.createLeaderElectionService(); } EmbeddedHaServices(Executor executor); @Override LeaderRetrievalService getResourceManagerLeaderRetriever(); @Override LeaderRetrievalService getDispatcherLeaderRetriever(); @Override LeaderElectionService getResourceManagerLeaderElectionService(); @Override LeaderElectionService getDispatcherLeaderElectionService(); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID); @Override LeaderRetrievalService getJobManagerLeaderRetriever(JobID jobID, String defaultJobManagerAddress); @Override LeaderRetrievalService getWebMonitorLeaderRetriever(); @Override LeaderElectionService getJobManagerLeaderElectionService(JobID jobID); @Override LeaderElectionService getWebMonitorLeaderElectionService(); @Override void close(); }### Answer: @Test public void testResourceManagerLeaderElection() throws Exception { LeaderContender leaderContender1 = mock(LeaderContender.class); LeaderContender leaderContender2 = mock(LeaderContender.class); LeaderElectionService leaderElectionService1 = embeddedHaServices.getResourceManagerLeaderElectionService(); LeaderElectionService leaderElectionService2 = embeddedHaServices.getResourceManagerLeaderElectionService(); leaderElectionService1.start(leaderContender1); leaderElectionService2.start(leaderContender2); ArgumentCaptor<UUID> leaderIdArgumentCaptor1 = ArgumentCaptor.forClass(UUID.class); ArgumentCaptor<UUID> leaderIdArgumentCaptor2 = ArgumentCaptor.forClass(UUID.class); verify(leaderContender1, atLeast(0)).grantLeadership(leaderIdArgumentCaptor1.capture()); verify(leaderContender2, atLeast(0)).grantLeadership(leaderIdArgumentCaptor2.capture()); assertTrue(leaderIdArgumentCaptor1.getAllValues().isEmpty() ^ leaderIdArgumentCaptor2.getAllValues().isEmpty()); }
### Question: ArchivedExecutionGraph implements AccessExecutionGraph, Serializable { public static ArchivedExecutionGraph createFrom(ExecutionGraph executionGraph) { final int numberVertices = executionGraph.getTotalNumberOfVertices(); Map<JobVertexID, ArchivedExecutionJobVertex> archivedTasks = new HashMap<>(numberVertices); List<ArchivedExecutionJobVertex> archivedVerticesInCreationOrder = new ArrayList<>(numberVertices); for (ExecutionJobVertex task : executionGraph.getVerticesTopologically()) { ArchivedExecutionJobVertex archivedTask = task.archive(); archivedVerticesInCreationOrder.add(archivedTask); archivedTasks.put(task.getJobVertexId(), archivedTask); } final Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators = executionGraph.getAccumulatorsSerialized(); final long[] timestamps = new long[JobStatus.values().length]; for (JobStatus jobStatus : JobStatus.values()) { final int ordinal = jobStatus.ordinal(); timestamps[ordinal] = executionGraph.getStatusTimestamp(jobStatus); } return new ArchivedExecutionGraph( executionGraph.getJobID(), executionGraph.getJobName(), archivedTasks, archivedVerticesInCreationOrder, timestamps, executionGraph.getState(), executionGraph.getFailureInfo(), executionGraph.getJsonPlan(), executionGraph.getAccumulatorResultsStringified(), serializedUserAccumulators, executionGraph.getArchivedExecutionConfig(), executionGraph.isStoppable(), executionGraph.getCheckpointCoordinatorConfiguration(), executionGraph.getCheckpointStatsSnapshot()); } ArchivedExecutionGraph( JobID jobID, String jobName, Map<JobVertexID, ArchivedExecutionJobVertex> tasks, List<ArchivedExecutionJobVertex> verticesInCreationOrder, long[] stateTimestamps, JobStatus state, @Nullable ErrorInfo failureCause, String jsonPlan, StringifiedAccumulatorResult[] archivedUserAccumulators, Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators, ArchivedExecutionConfig executionConfig, boolean isStoppable, @Nullable CheckpointCoordinatorConfiguration jobCheckpointingConfiguration, @Nullable CheckpointStatsSnapshot checkpointStatsSnapshot); @Override String getJsonPlan(); @Override JobID getJobID(); @Override String getJobName(); @Override JobStatus getState(); @Nullable @Override ErrorInfo getFailureInfo(); @Override ArchivedExecutionJobVertex getJobVertex(JobVertexID id); @Override Map<JobVertexID, AccessExecutionJobVertex> getAllVertices(); @Override Iterable<ArchivedExecutionJobVertex> getVerticesTopologically(); @Override Iterable<ArchivedExecutionVertex> getAllExecutionVertices(); @Override long getStatusTimestamp(JobStatus status); @Override CheckpointCoordinatorConfiguration getCheckpointCoordinatorConfiguration(); @Override CheckpointStatsSnapshot getCheckpointStatsSnapshot(); @Override boolean isArchived(); @Override ArchivedExecutionConfig getArchivedExecutionConfig(); @Override boolean isStoppable(); @Override StringifiedAccumulatorResult[] getAccumulatorResultsStringified(); @Override Map<String, SerializedValue<OptionalFailure<Object>>> getAccumulatorsSerialized(); static ArchivedExecutionGraph createFrom(ExecutionGraph executionGraph); }### Answer: @Test public void testArchive() throws IOException, ClassNotFoundException { ArchivedExecutionGraph archivedGraph = ArchivedExecutionGraph.createFrom(runtimeGraph); compareExecutionGraph(runtimeGraph, archivedGraph); } @Test public void testSerialization() throws IOException, ClassNotFoundException { ArchivedExecutionGraph archivedGraph = ArchivedExecutionGraph.createFrom(runtimeGraph); verifySerializability(archivedGraph); }
### Question: SnapshotDirectory { public boolean mkdirs() throws IOException { return fileSystem.mkdirs(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer: @Test public void mkdirs() throws Exception { File folderRoot = temporaryFolder.getRoot(); File newFolder = new File(folderRoot, String.valueOf(UUID.randomUUID())); File innerNewFolder = new File(newFolder, String.valueOf(UUID.randomUUID())); Path path = new Path(innerNewFolder.toURI()); Assert.assertFalse(newFolder.isDirectory()); Assert.assertFalse(innerNewFolder.isDirectory()); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path); Assert.assertFalse(snapshotDirectory.exists()); Assert.assertFalse(newFolder.isDirectory()); Assert.assertFalse(innerNewFolder.isDirectory()); Assert.assertTrue(snapshotDirectory.mkdirs()); Assert.assertTrue(newFolder.isDirectory()); Assert.assertTrue(innerNewFolder.isDirectory()); Assert.assertTrue(snapshotDirectory.exists()); }
### Question: SnapshotDirectory { public boolean exists() throws IOException { return fileSystem.exists(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer: @Test public void exists() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folderA = new File(folderRoot, String.valueOf(UUID.randomUUID())); Assert.assertFalse(folderA.isDirectory()); Path path = new Path(folderA.toURI()); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path); Assert.assertFalse(snapshotDirectory.exists()); Assert.assertTrue(folderA.mkdirs()); Assert.assertTrue(snapshotDirectory.exists()); Assert.assertTrue(folderA.delete()); Assert.assertFalse(snapshotDirectory.exists()); }
### Question: SnapshotDirectory { public FileStatus[] listStatus() throws IOException { return fileSystem.listStatus(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer: @Test public void listStatus() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folderA = new File(folderRoot, String.valueOf(UUID.randomUUID())); File folderB = new File(folderA, String.valueOf(UUID.randomUUID())); Assert.assertTrue(folderB.mkdirs()); File file = new File(folderA, "test.txt"); Assert.assertTrue(file.createNewFile()); Path path = new Path(folderA.toURI()); FileSystem fileSystem = path.getFileSystem(); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(path); Assert.assertTrue(snapshotDirectory.exists()); Assert.assertEquals( Arrays.toString(fileSystem.listStatus(path)), Arrays.toString(snapshotDirectory.listStatus())); }
### Question: SnapshotDirectory { @Nullable public abstract DirectoryStateHandle completeSnapshotAndGetHandle() throws IOException; private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer: @Test public void completeSnapshotAndGetHandle() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folderA = new File(folderRoot, String.valueOf(UUID.randomUUID())); Assert.assertTrue(folderA.mkdirs()); Path folderAPath = new Path(folderA.toURI()); SnapshotDirectory snapshotDirectory = SnapshotDirectory.permanent(folderAPath); DirectoryStateHandle handle = snapshotDirectory.completeSnapshotAndGetHandle(); Assert.assertNotNull(handle); Assert.assertTrue(snapshotDirectory.cleanup()); Assert.assertTrue(folderA.isDirectory()); Assert.assertEquals(folderAPath, handle.getDirectory()); handle.discardState(); Assert.assertFalse(folderA.isDirectory()); Assert.assertTrue(folderA.mkdirs()); snapshotDirectory = SnapshotDirectory.permanent(folderAPath); Assert.assertTrue(snapshotDirectory.cleanup()); try { snapshotDirectory.completeSnapshotAndGetHandle(); Assert.fail(); } catch (IOException ignore) { } }
### Question: SnapshotDirectory { public static SnapshotDirectory temporary(@Nonnull Path directory) throws IOException { return new TemporarySnapshotDirectory(directory); } private SnapshotDirectory(@Nonnull Path directory, @Nonnull FileSystem fileSystem); private SnapshotDirectory(@Nonnull Path directory); @Nonnull Path getDirectory(); boolean mkdirs(); @Nonnull FileSystem getFileSystem(); boolean exists(); FileStatus[] listStatus(); boolean cleanup(); boolean isSnapshotCompleted(); @Nullable abstract DirectoryStateHandle completeSnapshotAndGetHandle(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static SnapshotDirectory temporary(@Nonnull Path directory); static SnapshotDirectory permanent(@Nonnull Path directory); }### Answer: @Test public void temporary() throws Exception { File folderRoot = temporaryFolder.getRoot(); File folder = new File(folderRoot, String.valueOf(UUID.randomUUID())); Assert.assertTrue(folder.mkdirs()); Path folderPath = new Path(folder.toURI()); SnapshotDirectory tmpSnapshotDirectory = SnapshotDirectory.temporary(folderPath); Assert.assertNull(tmpSnapshotDirectory.completeSnapshotAndGetHandle()); Assert.assertTrue(tmpSnapshotDirectory.cleanup()); Assert.assertFalse(folder.exists()); }
### Question: FsCheckpointStorage extends AbstractFsCheckpointStorage { @Override public CheckpointStateOutputStream createTaskOwnedStateStream() throws IOException { return new FsCheckpointStateOutputStream( taskOwnedStateDirectory, fileSystem, FsCheckpointStreamFactory.DEFAULT_WRITE_BUFFER_SIZE, fileSizeThreshold); } FsCheckpointStorage( Path checkpointBaseDirectory, @Nullable Path defaultSavepointDirectory, JobID jobId, int fileSizeThreshold); Path getCheckpointsDirectory(); @Override boolean supportsHighlyAvailableStorage(); @Override CheckpointStorageLocation initializeLocationForCheckpoint(long checkpointId); @Override CheckpointStreamFactory resolveCheckpointStorageLocation( long checkpointId, CheckpointStorageLocationReference reference); @Override CheckpointStateOutputStream createTaskOwnedStateStream(); }### Answer: @Test public void testTaskOwnedStateStream() throws Exception { final List<String> state = Arrays.asList("Flopsy", "Mopsy", "Cotton Tail", "Peter"); final FsCheckpointStorage storage = new FsCheckpointStorage( Path.fromLocalFile(tmp.newFolder()), null, new JobID(), 10); final StreamStateHandle stateHandle; try (CheckpointStateOutputStream stream = storage.createTaskOwnedStateStream()) { assertTrue(stream instanceof FsCheckpointStateOutputStream); new ObjectOutputStream(stream).writeObject(state); stateHandle = stream.closeAndGetHandle(); } FileStateHandle fileStateHandle = (FileStateHandle) stateHandle; String parentDirName = fileStateHandle.getFilePath().getParent().getName(); assertEquals(FsCheckpointStorage.CHECKPOINT_TASK_OWNED_STATE_DIR, parentDirName); try (ObjectInputStream in = new ObjectInputStream(stateHandle.openInputStream())) { assertEquals(state, in.readObject()); } }
### Question: FileStateHandle implements StreamStateHandle { @Override public void discardState() throws Exception { FileSystem fs = getFileSystem(); fs.delete(filePath, false); } FileStateHandle(Path filePath, long stateSize); Path getFilePath(); @Override FSDataInputStream openInputStream(); @Override void discardState(); @Override long getStateSize(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testDisposeDeletesFile() throws Exception { File file = tempFolder.newFile(); writeTestData(file); assertTrue(file.exists()); FileStateHandle handle = new FileStateHandle(Path.fromLocalFile(file), file.length()); handle.discardState(); assertFalse(file.exists()); } @Test public void testDisposeDoesNotDeleteParentDirectory() throws Exception { File parentDir = tempFolder.newFolder(); assertTrue(parentDir.exists()); File file = new File(parentDir, "test"); writeTestData(file); assertTrue(file.exists()); FileStateHandle handle = new FileStateHandle(Path.fromLocalFile(file), file.length()); handle.discardState(); assertFalse(file.exists()); assertTrue(parentDir.exists()); }
### Question: TaskStateManagerImpl implements TaskStateManager { @Nonnull @Override public LocalRecoveryConfig createLocalRecoveryConfig() { return localStateStore.getLocalRecoveryConfig(); } TaskStateManagerImpl( @Nonnull JobID jobId, @Nonnull ExecutionAttemptID executionAttemptID, @Nonnull TaskLocalStateStore localStateStore, @Nullable JobManagerTaskRestore jobManagerTaskRestore, @Nonnull CheckpointResponder checkpointResponder); @Override void reportTaskStateSnapshots( @Nonnull CheckpointMetaData checkpointMetaData, @Nonnull CheckpointMetrics checkpointMetrics, @Nullable TaskStateSnapshot acknowledgedState, @Nullable TaskStateSnapshot localState); @Nonnull @Override PrioritizedOperatorSubtaskState prioritizedOperatorState(OperatorID operatorID); @Nonnull @Override LocalRecoveryConfig createLocalRecoveryConfig(); @Override void notifyCheckpointComplete(long checkpointId); }### Answer: @Test public void testForwardingSubtaskLocalStateBaseDirFromLocalStateStore() throws IOException { JobID jobID = new JobID(42L, 43L); AllocationID allocationID = new AllocationID(4711L, 23L); JobVertexID jobVertexID = new JobVertexID(12L, 34L); ExecutionAttemptID executionAttemptID = new ExecutionAttemptID(23L, 24L); TestCheckpointResponder checkpointResponderMock = new TestCheckpointResponder(); Executor directExecutor = Executors.directExecutor(); TemporaryFolder tmpFolder = new TemporaryFolder(); try { tmpFolder.create(); File[] allocBaseDirs = new File[]{tmpFolder.newFolder(), tmpFolder.newFolder(), tmpFolder.newFolder()}; LocalRecoveryDirectoryProviderImpl directoryProvider = new LocalRecoveryDirectoryProviderImpl(allocBaseDirs, jobID, jobVertexID, 0); LocalRecoveryConfig localRecoveryConfig = new LocalRecoveryConfig(true, directoryProvider); TaskLocalStateStore taskLocalStateStore = new TaskLocalStateStoreImpl(jobID, allocationID, jobVertexID, 13, localRecoveryConfig, directExecutor); TaskStateManager taskStateManager = taskStateManager( jobID, executionAttemptID, checkpointResponderMock, null, taskLocalStateStore); LocalRecoveryConfig localRecoveryConfFromTaskLocalStateStore = taskLocalStateStore.getLocalRecoveryConfig(); LocalRecoveryConfig localRecoveryConfFromTaskStateManager = taskStateManager.createLocalRecoveryConfig(); for (int i = 0; i < 10; ++i) { Assert.assertEquals(allocBaseDirs[i % allocBaseDirs.length], localRecoveryConfFromTaskLocalStateStore.getLocalStateDirectoryProvider().allocationBaseDirectory(i)); Assert.assertEquals(allocBaseDirs[i % allocBaseDirs.length], localRecoveryConfFromTaskStateManager.getLocalStateDirectoryProvider().allocationBaseDirectory(i)); } Assert.assertEquals( localRecoveryConfFromTaskLocalStateStore.isLocalRecoveryEnabled(), localRecoveryConfFromTaskStateManager.isLocalRecoveryEnabled()); } finally { tmpFolder.delete(); } }
### Question: ResourceProfile implements Serializable, Comparable<ResourceProfile> { public boolean isMatching(ResourceProfile required) { if (cpuCores >= required.getCpuCores() && heapMemoryInMB >= required.getHeapMemoryInMB() && directMemoryInMB >= required.getDirectMemoryInMB() && nativeMemoryInMB >= required.getNativeMemoryInMB() && networkMemoryInMB >= required.getNetworkMemoryInMB()) { for (Map.Entry<String, Resource> resource : required.extendedResources.entrySet()) { if (!extendedResources.containsKey(resource.getKey()) || !extendedResources.get(resource.getKey()).getResourceAggregateType().equals(resource.getValue().getResourceAggregateType()) || extendedResources.get(resource.getKey()).getValue() < resource.getValue().getValue()) { return false; } } return true; } return false; } ResourceProfile( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int networkMemoryInMB, Map<String, Resource> extendedResources); ResourceProfile(double cpuCores, int heapMemoryInMB); ResourceProfile(ResourceProfile other); double getCpuCores(); int getHeapMemoryInMB(); int getDirectMemoryInMB(); int getNativeMemoryInMB(); int getNetworkMemoryInMB(); int getMemoryInMB(); int getOperatorsMemoryInMB(); Map<String, Resource> getExtendedResources(); boolean isMatching(ResourceProfile required); @Override int compareTo(@Nonnull ResourceProfile other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourceProfile UNKNOWN; }### Answer: @Test public void testUnknownMatchesUnknown() { assertTrue(ResourceProfile.UNKNOWN.isMatching(ResourceProfile.UNKNOWN)); }
### Question: ResourceProfile implements Serializable, Comparable<ResourceProfile> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj != null && obj.getClass() == ResourceProfile.class) { ResourceProfile that = (ResourceProfile) obj; return this.cpuCores == that.cpuCores && this.heapMemoryInMB == that.heapMemoryInMB && this.directMemoryInMB == that.directMemoryInMB && this.networkMemoryInMB == that.networkMemoryInMB && Objects.equals(extendedResources, that.extendedResources); } return false; } ResourceProfile( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int networkMemoryInMB, Map<String, Resource> extendedResources); ResourceProfile(double cpuCores, int heapMemoryInMB); ResourceProfile(ResourceProfile other); double getCpuCores(); int getHeapMemoryInMB(); int getDirectMemoryInMB(); int getNativeMemoryInMB(); int getNetworkMemoryInMB(); int getMemoryInMB(); int getOperatorsMemoryInMB(); Map<String, Resource> getExtendedResources(); boolean isMatching(ResourceProfile required); @Override int compareTo(@Nonnull ResourceProfile other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourceProfile UNKNOWN; }### Answer: @Test public void testEquals() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertTrue(ResourceProfile.fromResourceSpec(rs1, 0).equals(ResourceProfile.fromResourceSpec(rs2, 0))); ResourceSpec rs3 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); ResourceSpec rs4 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); assertFalse(ResourceProfile.fromResourceSpec(rs3, 0).equals(ResourceProfile.fromResourceSpec(rs4, 0))); ResourceSpec rs5 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); assertTrue(ResourceProfile.fromResourceSpec(rs3, 100).equals(ResourceProfile.fromResourceSpec(rs5, 100))); }
### Question: ResourceProfile implements Serializable, Comparable<ResourceProfile> { @Override public int compareTo(@Nonnull ResourceProfile other) { int cmp = Integer.compare(this.getMemoryInMB(), other.getMemoryInMB()); if (cmp == 0) { cmp = Double.compare(this.cpuCores, other.cpuCores); } if (cmp == 0) { Iterator<Map.Entry<String, Resource>> thisIterator = extendedResources.entrySet().iterator(); Iterator<Map.Entry<String, Resource>> otherIterator = other.extendedResources.entrySet().iterator(); while (thisIterator.hasNext() && otherIterator.hasNext()) { Map.Entry<String, Resource> thisResource = thisIterator.next(); Map.Entry<String, Resource> otherResource = otherIterator.next(); if ((cmp = otherResource.getKey().compareTo(thisResource.getKey())) != 0) { return cmp; } if (!otherResource.getValue().getResourceAggregateType().equals(thisResource.getValue().getResourceAggregateType())) { return 1; } if ((cmp = Double.compare(thisResource.getValue().getValue(), otherResource.getValue().getValue())) != 0) { return cmp; } } if (thisIterator.hasNext()) { return 1; } if (otherIterator.hasNext()) { return -1; } } return cmp; } ResourceProfile( double cpuCores, int heapMemoryInMB, int directMemoryInMB, int nativeMemoryInMB, int networkMemoryInMB, Map<String, Resource> extendedResources); ResourceProfile(double cpuCores, int heapMemoryInMB); ResourceProfile(ResourceProfile other); double getCpuCores(); int getHeapMemoryInMB(); int getDirectMemoryInMB(); int getNativeMemoryInMB(); int getNetworkMemoryInMB(); int getMemoryInMB(); int getOperatorsMemoryInMB(); Map<String, Resource> getExtendedResources(); boolean isMatching(ResourceProfile required); @Override int compareTo(@Nonnull ResourceProfile other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourceProfile UNKNOWN; }### Answer: @Test public void testCompareTo() throws Exception { ResourceSpec rs1 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); ResourceSpec rs2 = ResourceSpec.newBuilder().setCpuCores(1.0).setHeapMemoryInMB(100).build(); assertEquals(0, ResourceProfile.fromResourceSpec(rs1, 0).compareTo(ResourceProfile.fromResourceSpec(rs2, 0))); ResourceSpec rs3 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); assertEquals(-1, ResourceProfile.fromResourceSpec(rs1, 0).compareTo(ResourceProfile.fromResourceSpec(rs3, 0))); assertEquals(1, ResourceProfile.fromResourceSpec(rs3, 0).compareTo(ResourceProfile.fromResourceSpec(rs1, 0))); ResourceSpec rs4 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(1.1). build(); assertEquals(1, ResourceProfile.fromResourceSpec(rs3, 0).compareTo(ResourceProfile.fromResourceSpec(rs4, 0))); assertEquals(-1, ResourceProfile.fromResourceSpec(rs4, 0).compareTo(ResourceProfile.fromResourceSpec(rs3, 0))); ResourceSpec rs5 = ResourceSpec.newBuilder(). setCpuCores(1.0). setHeapMemoryInMB(100). setGPUResource(2.2). build(); assertEquals(0, ResourceProfile.fromResourceSpec(rs3, 0).compareTo(ResourceProfile.fromResourceSpec(rs5, 0))); }
### Question: ContaineredTaskManagerParameters implements java.io.Serializable { public static long calculateCutoffMB(Configuration config, long containerMemoryMB) { Preconditions.checkArgument(containerMemoryMB > 0); final float memoryCutoffRatio = config.getFloat( ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_RATIO); if (memoryCutoffRatio >= 1 || memoryCutoffRatio <= 0) { throw new IllegalArgumentException("The configuration value '" + ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_RATIO.key() + "' must be between 0 and 1. Value given=" + memoryCutoffRatio); } final int minCutoff = config.getInteger( ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN); if (minCutoff >= containerMemoryMB) { throw new IllegalArgumentException("The configuration value '" + ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN.key() + "'='" + minCutoff + "' is larger than the total container memory " + containerMemoryMB); } long cutoff = (long) (containerMemoryMB * memoryCutoffRatio); if (cutoff < minCutoff) { cutoff = minCutoff; } return cutoff; } ContaineredTaskManagerParameters( long totalContainerMemoryMB, long taskManagerHeapSizeMB, long taskManagerDirectMemoryLimitMB, int numSlots, HashMap<String, String> taskManagerEnv); long taskManagerTotalMemoryMB(); long taskManagerHeapSizeMB(); long taskManagerDirectMemoryLimitMB(); int numSlots(); Map<String, String> taskManagerEnv(); @Override String toString(); static long calculateCutoffMB(Configuration config, long containerMemoryMB); static ContaineredTaskManagerParameters create( Configuration config, long containerMemoryMB, int numSlots); }### Answer: @Test public void testCalculateCutoffMB() { Configuration config = new Configuration(); long containerMemoryMB = 1000L; config.setFloat(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_RATIO, 0.1f); config.setInteger(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN, 128); assertEquals(128, ContaineredTaskManagerParameters.calculateCutoffMB(config, containerMemoryMB)); config.setFloat(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_RATIO, 0.2f); assertEquals(200, ContaineredTaskManagerParameters.calculateCutoffMB(config, containerMemoryMB)); config.setInteger(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN, 1000); try { ContaineredTaskManagerParameters.calculateCutoffMB(config, containerMemoryMB); fail("Expected to fail with an invalid argument exception."); } catch (IllegalArgumentException ignored) { } }
### Question: TaskManagerServices { public static long calculateHeapSizeMB(long totalJavaMemorySizeMB, Configuration config) { Preconditions.checkArgument(totalJavaMemorySizeMB > 0); final long networkBufMB = calculateNetworkBufferMemory( totalJavaMemorySizeMB << 20, config) >> 20; final long remainingJavaMemorySizeMB = totalJavaMemorySizeMB - networkBufMB; final boolean useOffHeap = config.getBoolean(TaskManagerOptions.MEMORY_OFF_HEAP); final long heapSizeMB; if (useOffHeap) { long offHeapSize = config.getLong(TaskManagerOptions.MANAGED_MEMORY_SIZE); if (offHeapSize <= 0) { double fraction = config.getFloat(TaskManagerOptions.MANAGED_MEMORY_FRACTION); offHeapSize = (long) (fraction * remainingJavaMemorySizeMB); } TaskManagerServicesConfiguration .checkConfigParameter(offHeapSize < remainingJavaMemorySizeMB, offHeapSize, TaskManagerOptions.MANAGED_MEMORY_SIZE.key(), "Managed memory size too large for " + networkBufMB + " MB network buffer memory and a total of " + totalJavaMemorySizeMB + " MB JVM memory"); heapSizeMB = remainingJavaMemorySizeMB - offHeapSize; } else { heapSizeMB = remainingJavaMemorySizeMB; } return heapSizeMB; } TaskManagerServices( TaskManagerLocation taskManagerLocation, MemoryManager memoryManager, IOManager ioManager, NetworkEnvironment networkEnvironment, BroadcastVariableManager broadcastVariableManager, FileCache fileCache, TaskSlotTable taskSlotTable, JobManagerTable jobManagerTable, JobLeaderService jobLeaderService, TaskExecutorLocalStateStoresManager taskManagerStateStore); MemoryManager getMemoryManager(); IOManager getIOManager(); NetworkEnvironment getNetworkEnvironment(); TaskManagerLocation getTaskManagerLocation(); BroadcastVariableManager getBroadcastVariableManager(); FileCache getFileCache(); TaskSlotTable getTaskSlotTable(); JobManagerTable getJobManagerTable(); JobLeaderService getJobLeaderService(); TaskExecutorLocalStateStoresManager getTaskManagerStateStore(); void shutDown(); static TaskManagerServices fromConfiguration( TaskManagerServicesConfiguration taskManagerServicesConfiguration, ResourceID resourceID, Executor taskIOExecutor, long freeHeapMemoryWithDefrag, long maxJvmHeapMemory); @SuppressWarnings("deprecation") static long calculateNetworkBufferMemory(long totalJavaMemorySize, Configuration config); static long calculateNetworkBufferMemory(TaskManagerServicesConfiguration tmConfig, long maxJvmHeapMemory); static long calculateHeapSizeMB(long totalJavaMemorySizeMB, Configuration config); @VisibleForTesting static final String LOCAL_STATE_SUB_DIRECTORY_ROOT; }### Answer: @Test public void calculateHeapSizeMB() throws Exception { Configuration config = new Configuration(); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.1f); config.setLong(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN, 64L << 20); config.setLong(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX, 1L << 30); config.setBoolean(TaskManagerOptions.MEMORY_OFF_HEAP, false); assertEquals(900, TaskManagerServices.calculateHeapSizeMB(1000, config)); config.setBoolean(TaskManagerOptions.MEMORY_OFF_HEAP, false); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.2f); assertEquals(800, TaskManagerServices.calculateHeapSizeMB(1000, config)); config.setBoolean(TaskManagerOptions.MEMORY_OFF_HEAP, true); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.1f); config.setLong(TaskManagerOptions.MANAGED_MEMORY_SIZE, 10); assertEquals(890, TaskManagerServices.calculateHeapSizeMB(1000, config)); config.setLong(TaskManagerOptions.MANAGED_MEMORY_SIZE, -1); config.setFloat(TaskManagerOptions.MANAGED_MEMORY_FRACTION, 0.1f); assertEquals(810, TaskManagerServices.calculateHeapSizeMB(1000, config)); }
### Question: SimpleSlot extends Slot implements LogicalSlot { @Override public CompletableFuture<?> releaseSlot(@Nullable Throwable cause) { if (!isCanceled()) { final CompletableFuture<?> terminationFuture; if (payload != null) { payload.fail(cause != null ? cause : new FlinkException("TaskManager was lost/killed: " + getTaskManagerLocation())); terminationFuture = payload.getTerminalStateFuture(); } else { terminationFuture = CompletableFuture.completedFuture(null); } terminationFuture.whenComplete( (Object ignored, Throwable throwable) -> { if (getParent() == null) { if (markCancelled()) { getOwner().returnAllocatedSlot(this).whenComplete( (value, t) -> { if (t != null) { releaseFuture.completeExceptionally(t); } else { releaseFuture.complete(null); } }); } } else { getParent().releaseChild(this); releaseFuture.complete(null); } }); } return releaseFuture; } SimpleSlot( SlotOwner owner, TaskManagerLocation location, int slotNumber, TaskManagerGateway taskManagerGateway); SimpleSlot( SlotOwner owner, TaskManagerLocation location, int slotNumber, TaskManagerGateway taskManagerGateway, @Nullable SharedSlot parent, @Nullable AbstractID groupID); SimpleSlot(SlotContext slotContext, SlotOwner owner, int slotNumber); SimpleSlot(SharedSlot parent, SlotOwner owner, int slotNumber, AbstractID groupID); private SimpleSlot( SlotContext slotContext, SlotOwner owner, int slotNumber, @Nullable SharedSlot parent, @Nullable AbstractID groupID); @Override int getNumberLeaves(); @Override boolean tryAssignPayload(Payload payload); @Nullable @Override Payload getPayload(); Locality getLocality(); void setLocality(Locality locality); @Override CompletableFuture<?> releaseSlot(@Nullable Throwable cause); @Override int getPhysicalSlotNumber(); @Override AllocationID getAllocationId(); @Override SlotRequestId getSlotRequestId(); @Nullable @Override SlotSharingGroupId getSlotSharingGroupId(); @Override String toString(); }### Answer: @Test public void testStateTransitions() { try { { SimpleSlot slot = getSlot(); assertTrue(slot.isAlive()); slot.releaseSlot(); assertFalse(slot.isAlive()); assertTrue(slot.isCanceled()); assertTrue(slot.isReleased()); } { SimpleSlot slot = getSlot(); assertTrue(slot.isAlive()); slot.markCancelled(); assertFalse(slot.isAlive()); assertTrue(slot.isCanceled()); assertFalse(slot.isReleased()); slot.markReleased(); assertFalse(slot.isAlive()); assertTrue(slot.isCanceled()); assertTrue(slot.isReleased()); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
### Question: SSLUtils { @Nullable public static SSLContext createSSLClientContext(Configuration sslConfig) throws Exception { Preconditions.checkNotNull(sslConfig); SSLContext clientSSLContext = null; if (getSSLEnabled(sslConfig)) { LOG.debug("Creating client SSL context from configuration"); String trustStoreFilePath = sslConfig.getString(SecurityOptions.SSL_TRUSTSTORE); String trustStorePassword = sslConfig.getString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD); String sslProtocolVersion = sslConfig.getString(SecurityOptions.SSL_PROTOCOL); Preconditions.checkNotNull(trustStoreFilePath, SecurityOptions.SSL_TRUSTSTORE.key() + " was not configured."); Preconditions.checkNotNull(trustStorePassword, SecurityOptions.SSL_TRUSTSTORE_PASSWORD.key() + " was not configured."); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream trustStoreFile = null; try { trustStoreFile = new FileInputStream(new File(trustStoreFilePath)); trustStore.load(trustStoreFile, trustStorePassword.toCharArray()); } finally { if (trustStoreFile != null) { trustStoreFile.close(); } } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); clientSSLContext = SSLContext.getInstance(sslProtocolVersion); clientSSLContext.init(null, trustManagerFactory.getTrustManagers(), null); } return clientSSLContext; } static boolean getSSLEnabled(Configuration sslConfig); static void setSSLVerAndCipherSuites(ServerSocket socket, Configuration config); static SSLEngineFactory createServerSSLEngineFactory(final Configuration config); static SSLEngineFactory createClientSSLEngineFactory(final Configuration config); @Deprecated static void setSSLVerAndCipherSuites(SSLEngine engine, Configuration config); static void setSSLVerifyHostname(Configuration sslConfig, SSLParameters sslParams); @Nullable static SSLContext createSSLClientContext(Configuration sslConfig); @Nullable static SSLContext createSSLServerContext(Configuration sslConfig); }### Answer: @Test public void testCreateSSLClientContext() throws Exception { Configuration clientConfig = new Configuration(); clientConfig.setBoolean(SecurityOptions.SSL_ENABLED, true); clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE, "src/test/resources/local127.truststore"); clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD, "password"); SSLContext clientContext = SSLUtils.createSSLClientContext(clientConfig); Assert.assertNotNull(clientContext); } @Test public void testCreateSSLClientContextWithSSLDisabled() throws Exception { Configuration clientConfig = new Configuration(); clientConfig.setBoolean(SecurityOptions.SSL_ENABLED, false); SSLContext clientContext = SSLUtils.createSSLClientContext(clientConfig); Assert.assertNull(clientContext); } @Test public void testCreateSSLClientContextMisconfiguration() { Configuration clientConfig = new Configuration(); clientConfig.setBoolean(SecurityOptions.SSL_ENABLED, true); clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE, "src/test/resources/local127.truststore"); clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD, "badpassword"); try { SSLContext clientContext = SSLUtils.createSSLClientContext(clientConfig); Assert.fail("SSL client context created even with bad SSL configuration "); } catch (Exception e) { } }
### Question: SSLUtils { private static SSLEngineFactory createSSLEngineFactory( final Configuration config, final boolean clientMode) throws Exception { final SSLContext sslContext = clientMode ? createSSLClientContext(config) : createSSLServerContext(config); checkState(sslContext != null, "%s it not enabled", SecurityOptions.SSL_ENABLED.key()); return new SSLEngineFactory( sslContext, getEnabledProtocols(config), getEnabledCipherSuites(config), clientMode); } static boolean getSSLEnabled(Configuration sslConfig); static void setSSLVerAndCipherSuites(ServerSocket socket, Configuration config); static SSLEngineFactory createServerSSLEngineFactory(final Configuration config); static SSLEngineFactory createClientSSLEngineFactory(final Configuration config); @Deprecated static void setSSLVerAndCipherSuites(SSLEngine engine, Configuration config); static void setSSLVerifyHostname(Configuration sslConfig, SSLParameters sslParams); @Nullable static SSLContext createSSLClientContext(Configuration sslConfig); @Nullable static SSLContext createSSLServerContext(Configuration sslConfig); }### Answer: @Test public void testCreateSSLEngineFactory() throws Exception { Configuration serverConfig = new Configuration(); serverConfig.setBoolean(SecurityOptions.SSL_ENABLED, true); serverConfig.setString(SecurityOptions.SSL_KEYSTORE, "src/test/resources/local127.keystore"); serverConfig.setString(SecurityOptions.SSL_KEYSTORE_PASSWORD, "password"); serverConfig.setString(SecurityOptions.SSL_KEY_PASSWORD, "password"); serverConfig.setString(SecurityOptions.SSL_PROTOCOL, "TLSv1"); serverConfig.setString(SecurityOptions.SSL_ALGORITHMS, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"); final SSLEngineFactory serverSSLEngineFactory = SSLUtils.createServerSSLEngineFactory(serverConfig); final SSLEngine sslEngine = serverSSLEngineFactory.createSSLEngine(); assertThat( Arrays.asList(sslEngine.getEnabledProtocols()), contains("TLSv1")); assertThat( Arrays.asList(sslEngine.getEnabledCipherSuites()), containsInAnyOrder("TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256")); }
### Question: FutureUtils { public static <T> CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor) { final CompletableFuture<T> resultFuture = new CompletableFuture<>(); retryOperationWithDelay( resultFuture, operation, retries, retryDelay, retryPredicate, scheduledExecutor); return resultFuture; } static CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retrySuccesfulWithDelay( final Supplier<CompletableFuture<T>> operation, final Time retryDelay, final Deadline deadline, final Predicate<T> acceptancePredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit); static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor); static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction); static ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures); static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures); static ConjunctFuture<Void> completeAll(Collection<? extends CompletableFuture<?>> futuresToComplete); static CompletableFuture<T> completedExceptionally(Throwable cause); static CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor); static FiniteDuration toFiniteDuration(Time time); static Time toTime(FiniteDuration finiteDuration); static CompletableFuture<T> toJava(Future<T> scalaFuture); }### Answer: @Test public void testRetryWithDelay() throws Exception { final int retries = 4; final Time delay = Time.milliseconds(5L); final AtomicInteger countDown = new AtomicInteger(retries); long start = System.currentTimeMillis(); CompletableFuture<Boolean> retryFuture = FutureUtils.retryWithDelay( () -> { if (countDown.getAndDecrement() == 0) { return CompletableFuture.completedFuture(true); } else { return FutureUtils.completedExceptionally(new FlinkException("Test exception.")); } }, retries, delay, TestingUtils.defaultScheduledExecutor()); Boolean result = retryFuture.get(); long completionTime = System.currentTimeMillis() - start; assertTrue(result); assertTrue("The completion time should be at least rertries times delay between retries.", completionTime >= retries * delay.toMilliseconds()); }
### Question: FutureUtils { public static <T> CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit) { if (!future.isDone()) { final ScheduledFuture<?> timeoutFuture = Delayer.delay(new Timeout(future), timeout, timeUnit); future.whenComplete((T value, Throwable throwable) -> { if (!timeoutFuture.isDone()) { timeoutFuture.cancel(false); } }); } return future; } static CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retrySuccesfulWithDelay( final Supplier<CompletableFuture<T>> operation, final Time retryDelay, final Deadline deadline, final Predicate<T> acceptancePredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit); static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor); static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction); static ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures); static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures); static ConjunctFuture<Void> completeAll(Collection<? extends CompletableFuture<?>> futuresToComplete); static CompletableFuture<T> completedExceptionally(Throwable cause); static CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor); static FiniteDuration toFiniteDuration(Time time); static Time toTime(FiniteDuration finiteDuration); static CompletableFuture<T> toJava(Future<T> scalaFuture); }### Answer: @Test public void testOrTimeout() throws Exception { final CompletableFuture<String> future = new CompletableFuture<>(); final long timeout = 10L; FutureUtils.orTimeout(future, timeout, TimeUnit.MILLISECONDS); try { future.get(); } catch (ExecutionException e) { assertTrue(ExceptionUtils.stripExecutionException(e) instanceof TimeoutException); } }
### Question: FutureUtils { public static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable) { return runAfterwardsAsync(future, runnable, Executors.directExecutor()); } static CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retrySuccesfulWithDelay( final Supplier<CompletableFuture<T>> operation, final Time retryDelay, final Deadline deadline, final Predicate<T> acceptancePredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit); static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor); static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction); static ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures); static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures); static ConjunctFuture<Void> completeAll(Collection<? extends CompletableFuture<?>> futuresToComplete); static CompletableFuture<T> completedExceptionally(Throwable cause); static CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor); static FiniteDuration toFiniteDuration(Time time); static Time toTime(FiniteDuration finiteDuration); static CompletableFuture<T> toJava(Future<T> scalaFuture); }### Answer: @Test public void testRunAfterwards() throws Exception { final CompletableFuture<Void> inputFuture = new CompletableFuture<>(); final OneShotLatch runnableLatch = new OneShotLatch(); final CompletableFuture<Void> runFuture = FutureUtils.runAfterwards( inputFuture, runnableLatch::trigger); assertThat(runnableLatch.isTriggered(), is(false)); assertThat(runFuture.isDone(), is(false)); inputFuture.complete(null); assertThat(runnableLatch.isTriggered(), is(true)); assertThat(runFuture.isDone(), is(true)); runFuture.get(); } @Test public void testRunAfterwardsExceptional() throws Exception { final CompletableFuture<Void> inputFuture = new CompletableFuture<>(); final OneShotLatch runnableLatch = new OneShotLatch(); final FlinkException testException = new FlinkException("Test exception"); final CompletableFuture<Void> runFuture = FutureUtils.runAfterwards( inputFuture, runnableLatch::trigger); assertThat(runnableLatch.isTriggered(), is(false)); assertThat(runFuture.isDone(), is(false)); inputFuture.completeExceptionally(testException); assertThat(runnableLatch.isTriggered(), is(true)); assertThat(runFuture.isDone(), is(true)); try { runFuture.get(); fail("Expected an exceptional completion"); } catch (ExecutionException ee) { assertThat(ExceptionUtils.stripExecutionException(ee), is(testException)); } }
### Question: FutureUtils { public static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures) { checkNotNull(futures, "futures"); return new WaitingConjunctFuture(futures); } static CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retrySuccesfulWithDelay( final Supplier<CompletableFuture<T>> operation, final Time retryDelay, final Deadline deadline, final Predicate<T> acceptancePredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit); static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor); static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction); static ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures); static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures); static ConjunctFuture<Void> completeAll(Collection<? extends CompletableFuture<?>> futuresToComplete); static CompletableFuture<T> completedExceptionally(Throwable cause); static CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor); static FiniteDuration toFiniteDuration(Time time); static Time toTime(FiniteDuration finiteDuration); static CompletableFuture<T> toJava(Future<T> scalaFuture); }### Answer: @Test public void testCancelWaitingConjunctFuture() { cancelConjunctFuture(inputFutures -> FutureUtils.waitForAll(inputFutures)); }
### Question: FutureUtils { public static <T> ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures) { checkNotNull(futures, "futures"); return new ResultConjunctFuture<>(futures); } static CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retrySuccesfulWithDelay( final Supplier<CompletableFuture<T>> operation, final Time retryDelay, final Deadline deadline, final Predicate<T> acceptancePredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit); static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor); static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction); static ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures); static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures); static ConjunctFuture<Void> completeAll(Collection<? extends CompletableFuture<?>> futuresToComplete); static CompletableFuture<T> completedExceptionally(Throwable cause); static CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor); static FiniteDuration toFiniteDuration(Time time); static Time toTime(FiniteDuration finiteDuration); static CompletableFuture<T> toJava(Future<T> scalaFuture); }### Answer: @Test public void testCancelResultConjunctFuture() { cancelConjunctFuture(inputFutures -> FutureUtils.combineAll(inputFutures)); }
### Question: FutureUtils { public static <T> CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor) { return CompletableFuture.supplyAsync( () -> { try { return supplier.get(); } catch (Throwable e) { throw new CompletionException(e); } }, executor); } static CompletableFuture<T> retry( final Supplier<CompletableFuture<T>> operation, final int retries, final Executor executor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final Predicate<Throwable> retryPredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retryWithDelay( final Supplier<CompletableFuture<T>> operation, final int retries, final Time retryDelay, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> retrySuccesfulWithDelay( final Supplier<CompletableFuture<T>> operation, final Time retryDelay, final Deadline deadline, final Predicate<T> acceptancePredicate, final ScheduledExecutor scheduledExecutor); static CompletableFuture<T> orTimeout(CompletableFuture<T> future, long timeout, TimeUnit timeUnit); static CompletableFuture<Void> runAfterwards(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync(CompletableFuture<?> future, RunnableWithException runnable); static CompletableFuture<Void> runAfterwardsAsync( CompletableFuture<?> future, RunnableWithException runnable, Executor executor); static CompletableFuture<Void> composeAfterwards( CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction); static ConjunctFuture<Collection<T>> combineAll(Collection<? extends CompletableFuture<? extends T>> futures); static ConjunctFuture<Void> waitForAll(Collection<? extends CompletableFuture<?>> futures); static ConjunctFuture<Void> completeAll(Collection<? extends CompletableFuture<?>> futuresToComplete); static CompletableFuture<T> completedExceptionally(Throwable cause); static CompletableFuture<T> supplyAsync(SupplierWithException<T, ?> supplier, Executor executor); static FiniteDuration toFiniteDuration(Time time); static Time toTime(FiniteDuration finiteDuration); static CompletableFuture<T> toJava(Future<T> scalaFuture); }### Answer: @Test public void testSupplyAsyncFailure() throws Exception { final String exceptionMessage = "Test exception"; final FlinkException testException = new FlinkException(exceptionMessage); final CompletableFuture<Object> future = FutureUtils.supplyAsync( () -> { throw testException; }, TestingUtils.defaultExecutor()); try { future.get(); fail("Expected an exception."); } catch (ExecutionException e) { assertThat(ExceptionUtils.findThrowableWithMessage(e, exceptionMessage).isPresent(), is(true)); } } @Test public void testSupplyAsync() throws Exception { final CompletableFuture<Acknowledge> future = FutureUtils.supplyAsync( Acknowledge::get, TestingUtils.defaultExecutor()); assertThat(future.get(), is(Acknowledge.get())); }
### Question: MiniDispatcher extends Dispatcher { public CompletableFuture<ApplicationStatus> getJobTerminationFuture() { return jobTerminationFuture; } MiniDispatcher( RpcService rpcService, String endpointId, Configuration configuration, HighAvailabilityServices highAvailabilityServices, ResourceManagerGateway resourceManagerGateway, BlobServer blobServer, HeartbeatServices heartbeatServices, JobManagerMetricGroup jobManagerMetricGroup, @Nullable String metricQueryServicePath, ArchivedExecutionGraphStore archivedExecutionGraphStore, JobManagerRunnerFactory jobManagerRunnerFactory, FatalErrorHandler fatalErrorHandler, @Nullable String restAddress, HistoryServerArchivist historyServerArchivist, JobGraph jobGraph, JobClusterEntrypoint.ExecutionMode executionMode); CompletableFuture<ApplicationStatus> getJobTerminationFuture(); @Override CompletableFuture<Acknowledge> submitJob(JobGraph jobGraph, Time timeout); @Override CompletableFuture<JobResult> requestJobResult(JobID jobId, Time timeout); }### Answer: @Test public void testTerminationAfterJobCompletion() throws Exception { final MiniDispatcher miniDispatcher = createMiniDispatcher(ClusterEntrypoint.ExecutionMode.DETACHED); miniDispatcher.start(); try { dispatcherLeaderElectionService.isLeader(UUID.randomUUID()).get(); jobGraphFuture.get(); resultFuture.complete(archivedExecutionGraph); miniDispatcher.getJobTerminationFuture().get(); } finally { RpcUtils.terminateRpcEndpoint(miniDispatcher, timeout); } }
### Question: MiniDispatcher extends Dispatcher { @Override public CompletableFuture<JobResult> requestJobResult(JobID jobId, Time timeout) { final CompletableFuture<JobResult> jobResultFuture = super.requestJobResult(jobId, timeout); if (executionMode == ClusterEntrypoint.ExecutionMode.NORMAL) { jobResultFuture.thenAccept((JobResult result) -> { ApplicationStatus status = result.getSerializedThrowable().isPresent() ? ApplicationStatus.FAILED : ApplicationStatus.SUCCEEDED; jobTerminationFuture.complete(status); }); } return jobResultFuture; } MiniDispatcher( RpcService rpcService, String endpointId, Configuration configuration, HighAvailabilityServices highAvailabilityServices, ResourceManagerGateway resourceManagerGateway, BlobServer blobServer, HeartbeatServices heartbeatServices, JobManagerMetricGroup jobManagerMetricGroup, @Nullable String metricQueryServicePath, ArchivedExecutionGraphStore archivedExecutionGraphStore, JobManagerRunnerFactory jobManagerRunnerFactory, FatalErrorHandler fatalErrorHandler, @Nullable String restAddress, HistoryServerArchivist historyServerArchivist, JobGraph jobGraph, JobClusterEntrypoint.ExecutionMode executionMode); CompletableFuture<ApplicationStatus> getJobTerminationFuture(); @Override CompletableFuture<Acknowledge> submitJob(JobGraph jobGraph, Time timeout); @Override CompletableFuture<JobResult> requestJobResult(JobID jobId, Time timeout); }### Answer: @Test public void testJobResultRetrieval() throws Exception { final MiniDispatcher miniDispatcher = createMiniDispatcher(ClusterEntrypoint.ExecutionMode.NORMAL); miniDispatcher.start(); try { dispatcherLeaderElectionService.isLeader(UUID.randomUUID()).get(); jobGraphFuture.get(); resultFuture.complete(archivedExecutionGraph); assertFalse(miniDispatcher.getTerminationFuture().isDone()); final DispatcherGateway dispatcherGateway = miniDispatcher.getSelfGateway(DispatcherGateway.class); final CompletableFuture<JobResult> jobResultFuture = dispatcherGateway.requestJobResult(jobGraph.getJobID(), timeout); final JobResult jobResult = jobResultFuture.get(); assertThat(jobResult.getJobId(), is(jobGraph.getJobID())); } finally { RpcUtils.terminateRpcEndpoint(miniDispatcher, timeout); } }
### Question: FileArchivedExecutionGraphStore implements ArchivedExecutionGraphStore { @Override public void put(ArchivedExecutionGraph archivedExecutionGraph) throws IOException { final JobStatus jobStatus = archivedExecutionGraph.getState(); final JobID jobId = archivedExecutionGraph.getJobID(); final String jobName = archivedExecutionGraph.getJobName(); Preconditions.checkArgument( jobStatus.isGloballyTerminalState(), "The job " + jobName + '(' + jobId + ") is not in a globally terminal state. Instead it is in state " + jobStatus + '.'); switch (jobStatus) { case FINISHED: numFinishedJobs++; break; case CANCELED: numCanceledJobs++; break; case FAILED: numFailedJobs++; break; default: throw new IllegalStateException("The job " + jobName + '(' + jobId + ") should have been in a globally terminal state. " + "Instead it was in state " + jobStatus + '.'); } storeArchivedExecutionGraph(archivedExecutionGraph); final JobDetails detailsForJob = WebMonitorUtils.createDetailsForJob(archivedExecutionGraph); jobDetailsCache.put(jobId, detailsForJob); archivedExecutionGraphCache.put(jobId, archivedExecutionGraph); } FileArchivedExecutionGraphStore( File rootDir, Time expirationTime, long maximumCacheSizeBytes, ScheduledExecutor scheduledExecutor, Ticker ticker); @Override int size(); @Override @Nullable ArchivedExecutionGraph get(JobID jobId); @Override void put(ArchivedExecutionGraph archivedExecutionGraph); @Override JobsOverview getStoredJobsOverview(); @Override Collection<JobDetails> getAvailableJobDetails(); @Nullable @Override JobDetails getAvailableJobDetails(JobID jobId); @Override void close(); }### Answer: @Test public void testPut() throws IOException { final ArchivedExecutionGraph dummyExecutionGraph = new ArchivedExecutionGraphBuilder().setState(JobStatus.FINISHED).build(); final File rootDir = temporaryFolder.newFolder(); try (final FileArchivedExecutionGraphStore executionGraphStore = createDefaultExecutionGraphStore(rootDir)) { final File storageDirectory = executionGraphStore.getStorageDir(); assertThat(storageDirectory.listFiles().length, Matchers.equalTo(0)); executionGraphStore.put(dummyExecutionGraph); assertThat(storageDirectory.listFiles().length, Matchers.equalTo(1)); assertThat(executionGraphStore.get(dummyExecutionGraph.getJobID()), new PartialArchivedExecutionGraphMatcher(dummyExecutionGraph)); } }
### Question: FileArchivedExecutionGraphStore implements ArchivedExecutionGraphStore { @Override @Nullable public ArchivedExecutionGraph get(JobID jobId) { try { return archivedExecutionGraphCache.get(jobId); } catch (ExecutionException e) { LOG.debug("Could not load archived execution graph for job id {}.", jobId, e); return null; } } FileArchivedExecutionGraphStore( File rootDir, Time expirationTime, long maximumCacheSizeBytes, ScheduledExecutor scheduledExecutor, Ticker ticker); @Override int size(); @Override @Nullable ArchivedExecutionGraph get(JobID jobId); @Override void put(ArchivedExecutionGraph archivedExecutionGraph); @Override JobsOverview getStoredJobsOverview(); @Override Collection<JobDetails> getAvailableJobDetails(); @Nullable @Override JobDetails getAvailableJobDetails(JobID jobId); @Override void close(); }### Answer: @Test public void testUnknownGet() throws IOException { final File rootDir = temporaryFolder.newFolder(); try (final FileArchivedExecutionGraphStore executionGraphStore = createDefaultExecutionGraphStore(rootDir)) { assertThat(executionGraphStore.get(new JobID()), Matchers.nullValue()); } }
### Question: SlotManager implements AutoCloseable { public boolean registerSlotRequest(SlotRequest slotRequest) throws SlotManagerException { checkInit(); if (checkDuplicateRequest(slotRequest.getAllocationId())) { LOG.debug("Ignoring a duplicate slot request with allocation id {}.", slotRequest.getAllocationId()); return false; } else { PendingSlotRequest pendingSlotRequest = new PendingSlotRequest(slotRequest); pendingSlotRequests.put(slotRequest.getAllocationId(), pendingSlotRequest); try { internalRequestSlot(pendingSlotRequest); } catch (ResourceManagerException e) { pendingSlotRequests.remove(slotRequest.getAllocationId()); throw new SlotManagerException("Could not fulfill slot request " + slotRequest.getAllocationId() + '.', e); } return true; } } SlotManager( ScheduledExecutor scheduledExecutor, Time taskManagerRequestTimeout, Time slotRequestTimeout, Time taskManagerTimeout); int getNumberRegisteredSlots(); int getNumberRegisteredSlotsOf(InstanceID instanceId); int getNumberFreeSlots(); int getNumberFreeSlotsOf(InstanceID instanceId); void start(ResourceManagerId newResourceManagerId, Executor newMainThreadExecutor, ResourceActions newResourceActions); void suspend(); @Override void close(); boolean registerSlotRequest(SlotRequest slotRequest); boolean unregisterSlotRequest(AllocationID allocationId); void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport); boolean unregisterTaskManager(InstanceID instanceId); boolean reportSlotStatus(InstanceID instanceId, SlotReport slotReport); void freeSlot(SlotID slotId, AllocationID allocationId); @VisibleForTesting void unregisterTaskManagersAndReleaseResources(); }### Answer: @Test public void testSlotRequestWithoutFreeSlots() throws Exception { final ResourceManagerId resourceManagerId = ResourceManagerId.generate(); final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337); final SlotRequest slotRequest = new SlotRequest( new JobID(), new AllocationID(), resourceProfile, "localhost"); ResourceActions resourceManagerActions = mock(ResourceActions.class); try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) { slotManager.registerSlotRequest(slotRequest); verify(resourceManagerActions).allocateResource(eq(resourceProfile)); } } @Test public void testSlotRequestWithResourceAllocationFailure() throws Exception { final ResourceManagerId resourceManagerId = ResourceManagerId.generate(); final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337); final SlotRequest slotRequest = new SlotRequest( new JobID(), new AllocationID(), resourceProfile, "localhost"); ResourceActions resourceManagerActions = mock(ResourceActions.class); doThrow(new ResourceManagerException("Test exception")).when(resourceManagerActions).allocateResource(any(ResourceProfile.class)); try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) { slotManager.registerSlotRequest(slotRequest); fail("The slot request should have failed with a ResourceManagerException."); } catch (ResourceManagerException e) { } } @Test public void testDuplicatePendingSlotRequest() throws Exception { final ResourceManagerId resourceManagerId = ResourceManagerId.generate(); final ResourceActions resourceManagerActions = mock(ResourceActions.class); final AllocationID allocationId = new AllocationID(); final ResourceProfile resourceProfile1 = new ResourceProfile(1.0, 2); final ResourceProfile resourceProfile2 = new ResourceProfile(2.0, 1); final SlotRequest slotRequest1 = new SlotRequest(new JobID(), allocationId, resourceProfile1, "foobar"); final SlotRequest slotRequest2 = new SlotRequest(new JobID(), allocationId, resourceProfile2, "barfoo"); try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) { assertTrue(slotManager.registerSlotRequest(slotRequest1)); assertFalse(slotManager.registerSlotRequest(slotRequest2)); } verify(resourceManagerActions, times(1)).allocateResource(any(ResourceProfile.class)); }
### Question: SlotManager implements AutoCloseable { public void freeSlot(SlotID slotId, AllocationID allocationId) { checkInit(); TaskManagerSlot slot = slots.get(slotId); if (null != slot) { if (slot.getState() == TaskManagerSlot.State.ALLOCATED) { if (Objects.equals(allocationId, slot.getAllocationId())) { TaskManagerRegistration taskManagerRegistration = taskManagerRegistrations.get(slot.getInstanceId()); if (taskManagerRegistration == null) { throw new IllegalStateException("Trying to free a slot from a TaskManager " + slot.getInstanceId() + " which has not been registered."); } updateSlotState(slot, taskManagerRegistration, null); } else { LOG.debug("Received request to free slot {} with expected allocation id {}, " + "but actual allocation id {} differs. Ignoring the request.", slotId, allocationId, slot.getAllocationId()); } } else { LOG.debug("Slot {} has not been allocated.", allocationId); } } else { LOG.debug("Trying to free a slot {} which has not been registered. Ignoring this message.", slotId); } } SlotManager( ScheduledExecutor scheduledExecutor, Time taskManagerRequestTimeout, Time slotRequestTimeout, Time taskManagerTimeout); int getNumberRegisteredSlots(); int getNumberRegisteredSlotsOf(InstanceID instanceId); int getNumberFreeSlots(); int getNumberFreeSlotsOf(InstanceID instanceId); void start(ResourceManagerId newResourceManagerId, Executor newMainThreadExecutor, ResourceActions newResourceActions); void suspend(); @Override void close(); boolean registerSlotRequest(SlotRequest slotRequest); boolean unregisterSlotRequest(AllocationID allocationId); void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport); boolean unregisterTaskManager(InstanceID instanceId); boolean reportSlotStatus(InstanceID instanceId, SlotReport slotReport); void freeSlot(SlotID slotId, AllocationID allocationId); @VisibleForTesting void unregisterTaskManagersAndReleaseResources(); }### Answer: @Test public void testFreeSlot() throws Exception { final ResourceManagerId resourceManagerId = ResourceManagerId.generate(); final ResourceID resourceID = ResourceID.generate(); final JobID jobId = new JobID(); final SlotID slotId = new SlotID(resourceID, 0); final AllocationID allocationId = new AllocationID(); final ResourceProfile resourceProfile = new ResourceProfile(42.0, 1337); ResourceActions resourceManagerActions = mock(ResourceActions.class); final TaskExecutorGateway taskExecutorGateway = mock(TaskExecutorGateway.class); final TaskExecutorConnection taskExecutorConnection = new TaskExecutorConnection(resourceID, taskExecutorGateway); final SlotStatus slotStatus = new SlotStatus(slotId, resourceProfile, jobId, allocationId); final SlotReport slotReport = new SlotReport(slotStatus); try (SlotManager slotManager = createSlotManager(resourceManagerId, resourceManagerActions)) { slotManager.registerTaskManager( taskExecutorConnection, slotReport); TaskManagerSlot slot = slotManager.getSlot(slotId); assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId()); slotManager.freeSlot(slotId, new AllocationID()); assertTrue(slot.getState() == TaskManagerSlot.State.ALLOCATED); assertEquals("The slot has not been allocated to the expected allocation id.", allocationId, slot.getAllocationId()); slotManager.freeSlot(slotId, allocationId); assertTrue(slot.getState() == TaskManagerSlot.State.FREE); assertNull(slot.getAllocationId()); } }
### Question: TaskStateSnapshot implements CompositeStateHandle { public boolean hasState() { for (OperatorSubtaskState operatorSubtaskState : subtaskStatesByOperatorID.values()) { if (operatorSubtaskState != null && operatorSubtaskState.hasState()) { return true; } } return false; } TaskStateSnapshot(); TaskStateSnapshot(int size); TaskStateSnapshot(Map<OperatorID, OperatorSubtaskState> subtaskStatesByOperatorID); @Nullable OperatorSubtaskState getSubtaskStateByOperatorID(OperatorID operatorID); OperatorSubtaskState putSubtaskStateByOperatorID( @Nonnull OperatorID operatorID, @Nonnull OperatorSubtaskState state); Set<Map.Entry<OperatorID, OperatorSubtaskState>> getSubtaskStateMappings(); boolean hasState(); @Override void discardState(); @Override long getStateSize(); @Override void registerSharedStates(SharedStateRegistry stateRegistry); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void hasState() { Random random = new Random(0x42); TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot(); Assert.assertFalse(taskStateSnapshot.hasState()); OperatorSubtaskState emptyOperatorSubtaskState = new OperatorSubtaskState(); Assert.assertFalse(emptyOperatorSubtaskState.hasState()); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), emptyOperatorSubtaskState); Assert.assertFalse(taskStateSnapshot.hasState()); OperatorStateHandle stateHandle = StateHandleDummyUtil.createNewOperatorStateHandle(2, random); OperatorSubtaskState nonEmptyOperatorSubtaskState = new OperatorSubtaskState( stateHandle, null, null, null ); Assert.assertTrue(nonEmptyOperatorSubtaskState.hasState()); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), nonEmptyOperatorSubtaskState); Assert.assertTrue(taskStateSnapshot.hasState()); } @Test public void hasState() { Random random = new Random(0x42); TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot(); Assert.assertFalse(taskStateSnapshot.hasState()); OperatorSubtaskState emptyOperatorSubtaskState = new OperatorSubtaskState(); Assert.assertFalse(emptyOperatorSubtaskState.hasState()); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), emptyOperatorSubtaskState); Assert.assertFalse(taskStateSnapshot.hasState()); OperatorStateHandle stateHandle = StateHandleDummyUtil.createNewOperatorStateHandle(2, random); OperatorSubtaskState nonEmptyOperatorSubtaskState = new OperatorSubtaskState( stateHandle, null, null, null, null, null ); Assert.assertTrue(nonEmptyOperatorSubtaskState.hasState()); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), nonEmptyOperatorSubtaskState); Assert.assertTrue(taskStateSnapshot.hasState()); }
### Question: TaskStateSnapshot implements CompositeStateHandle { @Override public long getStateSize() { long size = 0L; for (OperatorSubtaskState subtaskState : subtaskStatesByOperatorID.values()) { if (subtaskState != null) { size += subtaskState.getStateSize(); } } return size; } TaskStateSnapshot(); TaskStateSnapshot(int size); TaskStateSnapshot(Map<OperatorID, OperatorSubtaskState> subtaskStatesByOperatorID); @Nullable OperatorSubtaskState getSubtaskStateByOperatorID(OperatorID operatorID); OperatorSubtaskState putSubtaskStateByOperatorID( @Nonnull OperatorID operatorID, @Nonnull OperatorSubtaskState state); Set<Map.Entry<OperatorID, OperatorSubtaskState>> getSubtaskStateMappings(); boolean hasState(); @Override void discardState(); @Override long getStateSize(); @Override void registerSharedStates(SharedStateRegistry stateRegistry); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void getStateSize() { Random random = new Random(0x42); TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot(); Assert.assertEquals(0, taskStateSnapshot.getStateSize()); OperatorSubtaskState emptyOperatorSubtaskState = new OperatorSubtaskState(); Assert.assertFalse(emptyOperatorSubtaskState.hasState()); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), emptyOperatorSubtaskState); Assert.assertEquals(0, taskStateSnapshot.getStateSize()); OperatorStateHandle stateHandle_1 = StateHandleDummyUtil.createNewOperatorStateHandle(2, random); OperatorSubtaskState nonEmptyOperatorSubtaskState_1 = new OperatorSubtaskState( stateHandle_1, null, null, null ); OperatorStateHandle stateHandle_2 = StateHandleDummyUtil.createNewOperatorStateHandle(2, random); OperatorSubtaskState nonEmptyOperatorSubtaskState_2 = new OperatorSubtaskState( null, stateHandle_2, null, null ); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), nonEmptyOperatorSubtaskState_1); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), nonEmptyOperatorSubtaskState_2); long totalSize = stateHandle_1.getStateSize() + stateHandle_2.getStateSize(); Assert.assertEquals(totalSize, taskStateSnapshot.getStateSize()); } @Test public void getStateSize() { Random random = new Random(0x42); TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot(); Assert.assertEquals(0, taskStateSnapshot.getStateSize()); OperatorSubtaskState emptyOperatorSubtaskState = new OperatorSubtaskState(); Assert.assertFalse(emptyOperatorSubtaskState.hasState()); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), emptyOperatorSubtaskState); Assert.assertEquals(0, taskStateSnapshot.getStateSize()); OperatorStateHandle stateHandle_1 = StateHandleDummyUtil.createNewOperatorStateHandle(2, random); OperatorSubtaskState nonEmptyOperatorSubtaskState_1 = new OperatorSubtaskState( stateHandle_1, null, null, null, null, null ); OperatorStateHandle stateHandle_2 = StateHandleDummyUtil.createNewOperatorStateHandle(2, random); OperatorSubtaskState nonEmptyOperatorSubtaskState_2 = new OperatorSubtaskState( null, stateHandle_2, null, null, null, null ); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), nonEmptyOperatorSubtaskState_1); taskStateSnapshot.putSubtaskStateByOperatorID(new OperatorID(), nonEmptyOperatorSubtaskState_2); long totalSize = stateHandle_1.getStateSize() + stateHandle_2.getStateSize(); Assert.assertEquals(totalSize, taskStateSnapshot.getStateSize()); }
### Question: MasterHooks { public static <T> MasterTriggerRestoreHook<T> wrapHook( MasterTriggerRestoreHook<T> hook, ClassLoader userClassLoader) { return new WrappedMasterHook<>(hook, userClassLoader); } private MasterHooks(); static void reset( final Collection<MasterTriggerRestoreHook<?>> hooks, final Logger log); static void close( final Collection<MasterTriggerRestoreHook<?>> hooks, final Logger log); static List<MasterState> triggerMasterHooks( Collection<MasterTriggerRestoreHook<?>> hooks, long checkpointId, long timestamp, Executor executor, Time timeout); static void restoreMasterHooks( final Map<String, MasterTriggerRestoreHook<?>> masterHooks, final Collection<MasterState> states, final long checkpointId, final boolean allowUnmatchedState, final Logger log); static MasterTriggerRestoreHook<T> wrapHook( MasterTriggerRestoreHook<T> hook, ClassLoader userClassLoader); }### Answer: @Test public void wrapHook() throws Exception { final String id = "id"; Thread thread = Thread.currentThread(); final ClassLoader originalClassLoader = thread.getContextClassLoader(); final ClassLoader userClassLoader = new URLClassLoader(new URL[0]); final Runnable command = spy(new Runnable() { @Override public void run() { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); } }); MasterTriggerRestoreHook<String> hook = spy(new MasterTriggerRestoreHook<String>() { @Override public String getIdentifier() { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); return id; } @Override public void reset() throws Exception { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); } @Override public void close() throws Exception { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); } @Nullable @Override public CompletableFuture<String> triggerCheckpoint(long checkpointId, long timestamp, Executor executor) throws Exception { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); executor.execute(command); return null; } @Override public void restoreCheckpoint(long checkpointId, @Nullable String checkpointData) throws Exception { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); } @Nullable @Override public SimpleVersionedSerializer<String> createCheckpointDataSerializer() { assertEquals(userClassLoader, Thread.currentThread().getContextClassLoader()); return null; } }); MasterTriggerRestoreHook<String> wrapped = MasterHooks.wrapHook(hook, userClassLoader); wrapped.getIdentifier(); verify(hook, times(1)).getIdentifier(); assertEquals(originalClassLoader, thread.getContextClassLoader()); TestExecutor testExecutor = new TestExecutor(); wrapped.triggerCheckpoint(0L, 0, testExecutor); assertEquals(originalClassLoader, thread.getContextClassLoader()); assertNotNull(testExecutor.command); testExecutor.command.run(); verify(command, times(1)).run(); assertEquals(originalClassLoader, thread.getContextClassLoader()); wrapped.restoreCheckpoint(0L, ""); verify(hook, times(1)).restoreCheckpoint(eq(0L), eq("")); assertEquals(originalClassLoader, thread.getContextClassLoader()); wrapped.createCheckpointDataSerializer(); verify(hook, times(1)).createCheckpointDataSerializer(); assertEquals(originalClassLoader, thread.getContextClassLoader()); wrapped.close(); verify(hook, times(1)).close(); assertEquals(originalClassLoader, thread.getContextClassLoader()); }
### Question: PendingCheckpoint { public boolean canBeSubsumed() { return !props.forceCheckpoint(); } PendingCheckpoint( JobID jobId, long checkpointId, long checkpointTimestamp, Map<ExecutionAttemptID, ExecutionVertex> verticesToConfirm, CheckpointProperties props, CheckpointStorageLocation targetLocation, Executor executor); JobID getJobId(); long getCheckpointId(); long getCheckpointTimestamp(); int getNumberOfNonAcknowledgedTasks(); int getNumberOfAcknowledgedTasks(); Map<OperatorID, OperatorState> getOperatorStates(); boolean isFullyAcknowledged(); boolean isAcknowledgedBy(ExecutionAttemptID executionAttemptId); boolean isDiscarded(); boolean canBeSubsumed(); boolean setCancellerHandle(ScheduledFuture<?> cancellerHandle); CompletableFuture<CompletedCheckpoint> getCompletionFuture(); CompletedCheckpoint finalizeCheckpoint(); TaskAcknowledgeResult acknowledgeTask( ExecutionAttemptID executionAttemptId, TaskStateSnapshot operatorSubtaskStates, CheckpointMetrics metrics); void addMasterState(MasterState state); void abortExpired(); void abortSubsumed(); void abortDeclined(); void abortError(Throwable cause); @Override String toString(); }### Answer: @Test public void testCanBeSubsumed() throws Exception { CheckpointProperties forced = new CheckpointProperties(true, CheckpointType.SAVEPOINT, false, false, false, false, false); PendingCheckpoint pending = createPendingCheckpoint(forced); assertFalse(pending.canBeSubsumed()); try { pending.abortSubsumed(); fail("Did not throw expected Exception"); } catch (IllegalStateException ignored) { } CheckpointProperties subsumed = new CheckpointProperties(false, CheckpointType.SAVEPOINT, false, false, false, false, false); pending = createPendingCheckpoint(subsumed); assertTrue(pending.canBeSubsumed()); }
### Question: ValidationChain { public List<AttributeValidationResult> validate(UserProfileContext updateContext, UserProfile updatedProfile) { List<AttributeValidationResult> overallResults = new ArrayList<>(); for (AttributeValidator attribute : attributeValidators) { List<ValidationResult> validationResults = new ArrayList<>(); String attributeKey = attribute.attributeKey; String attributeValue = updatedProfile.getAttributes().getFirstAttribute(attributeKey); boolean attributeChanged = false; if (attributeValue != null) { attributeChanged = updateContext.getCurrentProfile() != null && !attributeValue.equals(updateContext.getCurrentProfile().getAttributes().getFirstAttribute(attributeKey)); for (Validator validator : attribute.validators) { validationResults.add(new ValidationResult(validator.function.apply(attributeValue, updateContext), validator.errorType)); } } overallResults.add(new AttributeValidationResult(attributeKey, attributeChanged, validationResults)); } return overallResults; } ValidationChain(List<AttributeValidator> attributeValidators); List<AttributeValidationResult> validate(UserProfileContext updateContext, UserProfile updatedProfile); }### Answer: @Test public void validate() { testchain = builder.build(); UserProfileValidationResult results = new UserProfileValidationResult(testchain.validate(updateContext, new UserRepresentationUserProfile(rep))); Assert.assertEquals(true, results.hasFailureOfErrorType("FAKE_FIELD_ERRORKEY")); Assert.assertEquals(false, results.hasFailureOfErrorType("FIRST_NAME_FIELD_ERRORKEY")); Assert.assertEquals(true, results.getValidationResults().stream().filter(o -> o.getField().equals("firstName")).collect(Collectors.toList()).get(0).isValid()); Assert.assertEquals(2, results.getValidationResults().size()); } @Test public void mergedConfig() { testchain = builder.addAttributeValidator().forAttribute("FAKE_FIELD") .addValidationFunction("FAKE_FIELD_ERRORKEY_1", (value, updateUserProfileContext) -> false).build() .addAttributeValidator().forAttribute("FAKE_FIELD") .addValidationFunction("FAKE_FIELD_ERRORKEY_2", (value, updateUserProfileContext) -> false).build().build(); UserProfileValidationResult results = new UserProfileValidationResult(testchain.validate(updateContext, new UserRepresentationUserProfile(rep))); Assert.assertEquals(true, results.hasFailureOfErrorType("FAKE_FIELD_ERRORKEY_1")); Assert.assertEquals(true, results.hasFailureOfErrorType("FAKE_FIELD_ERRORKEY_2")); Assert.assertEquals(true, results.getValidationResults().stream().filter(o -> o.getField().equals("firstName")).collect(Collectors.toList()).get(0).isValid()); Assert.assertEquals(false, results.hasAttributeChanged("firstName")); } @Test public void emptyChain() { UserProfileValidationResult results = new UserProfileValidationResult(ValidationChainBuilder.builder().build().validate(updateContext,new UserRepresentationUserProfile(rep) )); Assert.assertEquals(Collections.emptyList(), results.getValidationResults()); }
### Question: SimpleHttpFacade implements OIDCHttpFacade { @Override public KeycloakSecurityContext getSecurityContext() { SecurityContext context = SecurityContextHolder.getContext(); if (context != null && context.getAuthentication() != null) { KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) context.getAuthentication(); return authentication.getAccount().getKeycloakSecurityContext(); } return null; } SimpleHttpFacade(HttpServletRequest request, HttpServletResponse response); @Override KeycloakSecurityContext getSecurityContext(); @Override Request getRequest(); @Override Response getResponse(); @Override X509Certificate[] getCertificateChain(); }### Answer: @Test public void shouldRetrieveKeycloakSecurityContext() { SimpleHttpFacade facade = new SimpleHttpFacade(new MockHttpServletRequest(), new MockHttpServletResponse()); assertNotNull(facade.getSecurityContext()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getMethod() { return request.getMethod(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetMethod() throws Exception { assertNotNull(request.getMethod()); assertEquals(REQUEST_METHOD, request.getMethod()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getURI() { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) { buf.append('?').append(request.getQueryString()); } return buf.toString(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetURI() throws Exception { assertEquals("https: }
### Question: WrappedHttpServletRequest implements Request { @Override public boolean isSecure() { return request.isSecure(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testIsSecure() throws Exception { assertTrue(request.isSecure()); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getQueryParamValue(String param) { return request.getParameter(param); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetQueryParamValue() throws Exception { assertNotNull(request.getQueryParamValue(QUERY_PARM_1)); assertNotNull(request.getQueryParamValue(QUERY_PARM_2)); }
### Question: WrappedHttpServletRequest implements Request { @Override public Cookie getCookie(String cookieName) { javax.servlet.http.Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (javax.servlet.http.Cookie cookie : request.getCookies()) { if (cookie.getName().equals(cookieName)) { return new Cookie(cookie.getName(), cookie.getValue(), cookie.getVersion(), cookie.getDomain(), cookie.getPath()); } } return null; } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetCookie() throws Exception { assertNotNull(request.getCookie(COOKIE_NAME)); } @Test public void testGetCookieCookiesNull() throws Exception { mockHttpServletRequest.setCookies(null); request.getCookie(COOKIE_NAME); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getHeader(String name) { return request.getHeader(name); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetHeader() throws Exception { String header = request.getHeader(HEADER_SINGLE_VALUE); assertNotNull(header); assertEquals("baz", header); }
### Question: WrappedHttpServletRequest implements Request { @Override public List<String> getHeaders(String name) { Enumeration<String> values = request.getHeaders(name); List<String> array = new ArrayList<String>(); while (values.hasMoreElements()) { array.add(values.nextElement()); } return Collections.unmodifiableList(array); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetHeaders() throws Exception { List<String> headers = request.getHeaders(HEADER_MULTI_VALUE); assertNotNull(headers); assertEquals(2, headers.size()); assertTrue(headers.contains("foo")); assertTrue(headers.contains("bar")); }
### Question: WrappedHttpServletRequest implements Request { @Override public InputStream getInputStream() { return getInputStream(false); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetInputStream() throws Exception { assertNotNull(request.getInputStream()); }
### Question: ProxyMappings { public ProxyMapping getProxyFor(String hostname) { Objects.requireNonNull(hostname, "hostname"); if (hostnameToProxyCache.containsKey(hostname)) { return hostnameToProxyCache.get(hostname); } ProxyMapping proxyMapping = entries.stream() .filter(e -> e.matches(hostname)) .findFirst() .orElse(null); if (proxyMapping == null) { proxyMapping = new ProxyMapping(null, null, null); } hostnameToProxyCache.put(hostname, proxyMapping); return proxyMapping; } ProxyMappings(List<ProxyMapping> entries); static ProxyMappings valueOf(List<String> proxyMappings); static ProxyMappings valueOf(String... proxyMappings); boolean isEmpty(); ProxyMapping getProxyFor(String hostname); static void clearCache(); }### Answer: @Test public void shouldReturnProxy1ForConfiguredProxyMappingAlternative() { ProxyMapping proxy = proxyMappings.getProxyFor("www.googleapis.com"); assertThat(proxy.getProxyHost(), is(notNullValue())); assertThat(proxy.getProxyHost().getHostName(), is("proxy1")); } @Test public void shouldReturnProxy1ForConfiguredProxyMappingWithSubDomain() { ProxyMapping proxy = proxyMappings.getProxyFor("awesome.account.google.com"); assertThat(proxy.getProxyHost(), is(notNullValue())); assertThat(proxy.getProxyHost().getHostName(), is("proxy1")); } @Test public void shouldReturnProxy2ForConfiguredProxyMapping() { ProxyMapping proxy = proxyMappings.getProxyFor("login.facebook.com"); assertThat(proxy.getProxyHost(), is(notNullValue())); assertThat(proxy.getProxyHost().getHostName(), is("proxy2")); } @Test public void shouldReturnNoProxyForUnknownHost() { ProxyMapping proxy = proxyMappings.getProxyFor("login.microsoft.com"); assertThat(proxy.getProxyHost(), is(nullValue())); } @Test public void shouldRejectNull() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("hostname"); proxyMappings.getProxyFor(null); } @Test public void shouldReturnProxy1ForConfiguredProxyMapping() { ProxyMapping proxy = proxyMappings.getProxyFor("account.google.com"); assertThat(proxy.getProxyHost(), is(notNullValue())); assertThat(proxy.getProxyHost().getHostName(), is("proxy1")); }
### Question: WrappedHttpServletRequest implements Request { @Override public String getRemoteAddr() { return request.getRemoteAddr(); } WrappedHttpServletRequest(HttpServletRequest request); @Override String getFirstParam(String param); @Override String getMethod(); @Override String getURI(); @Override String getRelativePath(); @Override boolean isSecure(); @Override String getQueryParamValue(String param); @Override Cookie getCookie(String cookieName); @Override String getHeader(String name); @Override List<String> getHeaders(String name); @Override InputStream getInputStream(); @Override InputStream getInputStream(boolean buffered); @Override String getRemoteAddr(); @Override void setError(AuthenticationError error); @Override void setError(LogoutError error); }### Answer: @Test public void testGetRemoteAddr() throws Exception { assertNotNull(request.getRemoteAddr()); }
### Question: KeycloakClientRequestFactory extends HttpComponentsClientHttpRequestFactory implements ClientHttpRequestFactory { @Override protected void postProcessHttpRequest(HttpUriRequest request) { KeycloakSecurityContext context = this.getKeycloakSecurityContext(); request.setHeader(AUTHORIZATION_HEADER, "Bearer " + context.getTokenString()); } KeycloakClientRequestFactory(); static final String AUTHORIZATION_HEADER; }### Answer: @Test public void testPostProcessHttpRequest() throws Exception { factory.postProcessHttpRequest(request); verify(factory).getKeycloakSecurityContext(); verify(request).setHeader(eq(KeycloakClientRequestFactory.AUTHORIZATION_HEADER), eq("Bearer " + bearerTokenString)); }
### Question: KeycloakClientRequestFactory extends HttpComponentsClientHttpRequestFactory implements ClientHttpRequestFactory { protected KeycloakSecurityContext getKeycloakSecurityContext() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); KeycloakAuthenticationToken token; KeycloakSecurityContext context; if (authentication == null) { throw new IllegalStateException("Cannot set authorization header because there is no authenticated principal"); } if (!KeycloakAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { throw new IllegalStateException( String.format( "Cannot set authorization header because Authentication is of type %s but %s is required", authentication.getClass(), KeycloakAuthenticationToken.class) ); } token = (KeycloakAuthenticationToken) authentication; context = token.getAccount().getKeycloakSecurityContext(); return context; } KeycloakClientRequestFactory(); static final String AUTHORIZATION_HEADER; }### Answer: @Test public void testGetKeycloakSecurityContext() throws Exception { KeycloakSecurityContext context = factory.getKeycloakSecurityContext(); assertNotNull(context); assertEquals(keycloakSecurityContext, context); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextInvalidAuthentication() throws Exception { SecurityContextHolder.getContext().setAuthentication( new PreAuthenticatedAuthenticationToken("foo", "bar", Collections.singleton(new KeycloakRole("baz")))); factory.getKeycloakSecurityContext(); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextNullAuthentication() throws Exception { SecurityContextHolder.clearContext(); factory.getKeycloakSecurityContext(); }
### Question: JBossWebPrincipalFactory extends GenericPrincipalFactory { static Constructor findJBossGenericPrincipalConstructor() { for (Constructor<?> c : JBossGenericPrincipal.class.getConstructors()) { if (c.getParameterTypes().length == 9 && c.getParameterTypes()[0].equals(Realm.class) && c.getParameterTypes()[1].equals(String.class) && c.getParameterTypes()[3].equals(List.class) && c.getParameterTypes()[4].equals(Principal.class) && c.getParameterTypes()[6].equals(Object.class) && c.getParameterTypes()[8].equals(Subject.class)) { return c; } } return null; } @Override GenericPrincipal createPrincipal(Realm realm, final Principal identity, final Set<String> roleSet); }### Answer: @Test public void test() { Constructor constructor = JBossWebPrincipalFactory.findJBossGenericPrincipalConstructor(); Assert.assertNotNull(constructor); Assert.assertEquals(Realm.class, constructor.getParameterTypes()[0]); Assert.assertEquals(String.class, constructor.getParameterTypes()[1]); Assert.assertEquals(List.class, constructor.getParameterTypes()[3]); Assert.assertEquals(Principal.class, constructor.getParameterTypes()[4]); Assert.assertEquals(Object.class, constructor.getParameterTypes()[6]); Assert.assertEquals(Subject.class, constructor.getParameterTypes()[8]); }
### Question: KeycloakSecurityContextClientRequestInterceptor implements ClientHttpRequestInterceptor { protected KeycloakSecurityContext getKeycloakSecurityContext() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); Principal principal = attributes.getRequest().getUserPrincipal(); if (principal == null) { throw new IllegalStateException("Cannot set authorization header because there is no authenticated principal"); } if (!(principal instanceof KeycloakPrincipal)) { throw new IllegalStateException( String.format( "Cannot set authorization header because the principal type %s does not provide the KeycloakSecurityContext", principal.getClass())); } return ((KeycloakPrincipal) principal).getKeycloakSecurityContext(); } @Override ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution); }### Answer: @Test public void testGetKeycloakSecurityContext() throws Exception { KeycloakSecurityContext context = factory.getKeycloakSecurityContext(); assertNotNull(context); assertEquals(keycloakSecurityContext, context); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextInvalidPrincipal() throws Exception { servletRequest.setUserPrincipal(new MarkerPrincipal()); factory.getKeycloakSecurityContext(); } @Test(expected = IllegalStateException.class) public void testGetKeycloakSecurityContextNullAuthentication() throws Exception { servletRequest.setUserPrincipal(null); factory.getKeycloakSecurityContext(); }
### Question: KeycloakRestTemplateCustomizer implements RestTemplateCustomizer { @Override public void customize(RestTemplate restTemplate) { restTemplate.getInterceptors().add(keycloakInterceptor); } KeycloakRestTemplateCustomizer(); protected KeycloakRestTemplateCustomizer( KeycloakSecurityContextClientRequestInterceptor keycloakInterceptor ); @Override void customize(RestTemplate restTemplate); }### Answer: @Test public void interceptorIsAddedToRequest() { RestTemplate restTemplate = new RestTemplate(); customizer.customize(restTemplate); assertTrue(restTemplate.getInterceptors().contains(interceptor)); }
### Question: HierarchicalPathBasedKeycloakConfigResolver extends PathBasedKeycloakConfigResolver { @Override public KeycloakDeployment resolve(OIDCHttpFacade.Request request) { URI uri = URI.create(request.getURI()); String path = uri.getPath(); if (path != null) { while (path.startsWith("/")) { path = path.substring(1); } String[] segments = path.split("/"); List<String> paths = collectPaths(segments); for (String pathFragment: paths) { KeycloakDeployment cachedDeployment = super.getCachedDeployment(pathFragment); if (cachedDeployment != null) { return cachedDeployment; } } } throw new IllegalStateException("Can't find Keycloak configuration related to URI path " + uri); } HierarchicalPathBasedKeycloakConfigResolver(); @Override KeycloakDeployment resolve(OIDCHttpFacade.Request request); }### Answer: @Test public void genericAndSpecificConfigurations() throws Exception { HierarchicalPathBasedKeycloakConfigResolver resolver = new HierarchicalPathBasedKeycloakConfigResolver(); populate(resolver, true); assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: assertThat(resolver.resolve(new MockRequest("http: populate(resolver, false); try { resolver.resolve(new MockRequest("http: fail("Expected java.lang.IllegalStateException: Can't find Keycloak configuration ..."); } catch (IllegalStateException expected) { } }
### Question: PathBasedKeycloakConfigResolver implements KeycloakConfigResolver { @Override public KeycloakDeployment resolve(OIDCHttpFacade.Request request) { String webContext = getDeploymentKeyForURI(request); return getOrCreateDeployment(webContext); } PathBasedKeycloakConfigResolver(); @Override KeycloakDeployment resolve(OIDCHttpFacade.Request request); }### Answer: @Test public void relativeURIsAndContexts() throws Exception { PathBasedKeycloakConfigResolver resolver = new PathBasedKeycloakConfigResolver(); assertNotNull(populate(resolver, "test") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "test") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "test") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "test/a") .resolve(new MockRequest("http: assertNotNull(populate(resolver, "") .resolve(new MockRequest("http: }
### Question: RefreshableKeycloakSecurityContext extends KeycloakSecurityContext { public boolean isActive() { return token != null && this.token.isActive() && deployment!=null && this.token.getIssuedAt() >= deployment.getNotBefore(); } RefreshableKeycloakSecurityContext(); RefreshableKeycloakSecurityContext(KeycloakDeployment deployment, AdapterTokenStore tokenStore, String tokenString, AccessToken token, String idTokenString, IDToken idToken, String refreshToken); @Override AccessToken getToken(); @Override String getTokenString(); @Override IDToken getIdToken(); @Override String getIdTokenString(); String getRefreshToken(); void logout(KeycloakDeployment deployment); boolean isActive(); boolean isTokenTimeToLiveSufficient(AccessToken token); KeycloakDeployment getDeployment(); void setCurrentRequestInfo(KeycloakDeployment deployment, AdapterTokenStore tokenStore); boolean refreshExpiredToken(boolean checkActive); void setAuthorizationContext(AuthorizationContext authorizationContext); }### Answer: @Test public void isActive() { TokenMetadataRepresentation token = new TokenMetadataRepresentation(); token.setActive(true); token.issuedNow(); RefreshableKeycloakSecurityContext sut = new RefreshableKeycloakSecurityContext(null,null,null,token,null, null, null); assertFalse(sut.isActive()); } @Test public void sameIssuedAtAsNotBeforeIsActiveKEYCLOAK10013() { KeycloakDeployment keycloakDeployment = new KeycloakDeployment(); keycloakDeployment.setNotBefore(5000); TokenMetadataRepresentation token = new TokenMetadataRepresentation(); token.setActive(true); token.issuedAt(4999); RefreshableKeycloakSecurityContext sut = new RefreshableKeycloakSecurityContext(keycloakDeployment,null,null,token,null, null, null); assertFalse(sut.isActive()); token.issuedAt(5000); assertTrue(sut.isActive()); }
### Question: KeycloakDeployment { public boolean isOAuthQueryParameterEnabled() { return !this.ignoreOAuthQueryParameter; } KeycloakDeployment(); boolean isConfigured(); String getResourceName(); String getRealm(); void setRealm(String realm); PublicKeyLocator getPublicKeyLocator(); void setPublicKeyLocator(PublicKeyLocator publicKeyLocator); String getAuthServerBaseUrl(); void setAuthServerBaseUrl(AdapterConfig config); RelativeUrlsUsed getRelativeUrls(); String getRealmInfoUrl(); KeycloakUriBuilder getAuthUrl(); String getTokenUrl(); KeycloakUriBuilder getLogoutUrl(); String getAccountUrl(); String getRegisterNodeUrl(); String getUnregisterNodeUrl(); String getJwksUrl(); void setResourceName(String resourceName); boolean isBearerOnly(); void setBearerOnly(boolean bearerOnly); boolean isAutodetectBearerOnly(); void setAutodetectBearerOnly(boolean autodetectBearerOnly); boolean isEnableBasicAuth(); void setEnableBasicAuth(boolean enableBasicAuth); boolean isPublicClient(); void setPublicClient(boolean publicClient); Map<String, Object> getResourceCredentials(); void setResourceCredentials(Map<String, Object> resourceCredentials); ClientCredentialsProvider getClientAuthenticator(); void setClientAuthenticator(ClientCredentialsProvider clientAuthenticator); HttpClient getClient(); void setClient(final HttpClient client); String getScope(); void setScope(String scope); SslRequired getSslRequired(); void setSslRequired(SslRequired sslRequired); boolean isSSLEnabled(); int getConfidentialPort(); void setConfidentialPort(int confidentialPort); TokenStore getTokenStore(); void setTokenStore(TokenStore tokenStore); String getAdapterStateCookiePath(); void setAdapterStateCookiePath(String adapterStateCookiePath); String getStateCookieName(); void setStateCookieName(String stateCookieName); boolean isUseResourceRoleMappings(); void setUseResourceRoleMappings(boolean useResourceRoleMappings); boolean isCors(); void setCors(boolean cors); int getCorsMaxAge(); void setCorsMaxAge(int corsMaxAge); String getCorsAllowedHeaders(); void setCorsAllowedHeaders(String corsAllowedHeaders); String getCorsAllowedMethods(); void setCorsAllowedMethods(String corsAllowedMethods); String getCorsExposedHeaders(); void setCorsExposedHeaders(String corsExposedHeaders); boolean isExposeToken(); void setExposeToken(boolean exposeToken); int getNotBefore(); void setNotBefore(int notBefore); void updateNotBefore(int notBefore); boolean isAlwaysRefreshToken(); void setAlwaysRefreshToken(boolean alwaysRefreshToken); boolean isRegisterNodeAtStartup(); void setRegisterNodeAtStartup(boolean registerNodeAtStartup); int getRegisterNodePeriod(); void setRegisterNodePeriod(int registerNodePeriod); String getPrincipalAttribute(); void setPrincipalAttribute(String principalAttribute); boolean isTurnOffChangeSessionIdOnLogin(); void setTurnOffChangeSessionIdOnLogin(boolean turnOffChangeSessionIdOnLogin); int getTokenMinimumTimeToLive(); void setTokenMinimumTimeToLive(final int tokenMinimumTimeToLive); int getMinTimeBetweenJwksRequests(); void setMinTimeBetweenJwksRequests(int minTimeBetweenJwksRequests); int getPublicKeyCacheTtl(); void setPublicKeyCacheTtl(int publicKeyCacheTtl); void setPolicyEnforcer(Callable<PolicyEnforcer> policyEnforcer); PolicyEnforcer getPolicyEnforcer(); boolean isPkce(); void setPkce(boolean pkce); void setIgnoreOAuthQueryParameter(boolean ignoreOAuthQueryParameter); boolean isOAuthQueryParameterEnabled(); Map<String, String> getRedirectRewriteRules(); void setRewriteRedirectRules(Map<String, String> redirectRewriteRules); boolean isDelegateBearerErrorResponseSending(); void setDelegateBearerErrorResponseSending(boolean delegateBearerErrorResponseSending); boolean isVerifyTokenAudience(); void setVerifyTokenAudience(boolean verifyTokenAudience); void setClient(Callable<HttpClient> callable); }### Answer: @Test public void shouldEnableOAuthQueryParamWhenIgnoreNotSet() { KeycloakDeployment keycloakDeployment = new KeycloakDeploymentMock(); assertTrue(keycloakDeployment.isOAuthQueryParameterEnabled()); }
### Question: IDFedLSInputResolver implements LSResourceResolver { public IDFedLSInput resolveResource(String type, String namespaceURI, final String publicId, final String systemId, final String baseURI) { if (systemId == null) { throw new IllegalArgumentException("Expected systemId"); } final String loc = schemaLocationMap.get(systemId); if (loc == null) { return null; } return new IDFedLSInput(baseURI, loc, publicId, systemId); } static Collection<String> schemas(); IDFedLSInput resolveResource(String type, String namespaceURI, final String publicId, final String systemId, final String baseURI); }### Answer: @Test public void testSchemaConstruction() throws Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final IDFedLSInputResolver idFedLSInputResolver = new IDFedLSInputResolver(); schemaFactory.setResourceResolver(new LSResourceResolver() { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { LSInput input = idFedLSInputResolver.resolveResource(type, namespaceURI, publicId, systemId, baseURI); if(input == null) { throw new IllegalArgumentException("Unable to resolve " + systemId); } InputStream is = input.getByteStream(); if(is == null) { throw new IllegalArgumentException("Unable to resolve stream for " + systemId); } try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } return input; } }); for(String schema : SchemaManagerUtil.getSchemas()) { if(schema.contains("saml")) { URL schemaFile = SecurityActions.loadResource(getClass(), schema); schemaFactory.newSchema(schemaFile); } } JAXPValidationUtil.validator(); }
### Question: SecurityActions { public static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName) { SecurityManager sm = System.getSecurityManager(); if (fullQualifiedName == null) { return null; } if (sm != null) { sm.checkPackageDefinition(extractPackageNameFromClassName(fullQualifiedName)); return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() { @Override public Class<?> run() { ClassLoader classLoader = theClass.getClassLoader(); Class<?> clazz = loadClass(classLoader, fullQualifiedName); if (clazz == null) { classLoader = Thread.currentThread().getContextClassLoader(); clazz = loadClass(classLoader, fullQualifiedName); } return clazz; } }); } else { ClassLoader classLoader = theClass.getClassLoader(); Class<?> clazz = loadClass(classLoader, fullQualifiedName); if (clazz == null) { classLoader = Thread.currentThread().getContextClassLoader(); clazz = loadClass(classLoader, fullQualifiedName); } return clazz; } } static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName); static Class<?> loadClass(final ClassLoader classLoader, final String fullQualifiedName); static URL loadResource(final Class<?> clazz, final String resourceName); static void setSystemProperty(final String key, final String value); static String getSystemProperty(final String key, final String defaultValue); static ClassLoader getTCCL(); static void setTCCL(final ClassLoader paramCl); }### Answer: @Test public void testLoadClass() { SecurityActions.loadClass(SecurityActionsTest.class, "java.lang.String"); if (RESTRICTED) { expectedException.expect(SecurityException.class); } SecurityActions.loadClass(SecurityActions.class, "sun.misc.Unsafe"); }
### Question: SecurityActions { public static ClassLoader getTCCL() { if (System.getSecurityManager() != null) { System.getSecurityManager().checkPermission(new RuntimePermission("getClassLoader")); return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); } else { return Thread.currentThread().getContextClassLoader(); } } static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName); static Class<?> loadClass(final ClassLoader classLoader, final String fullQualifiedName); static URL loadResource(final Class<?> clazz, final String resourceName); static void setSystemProperty(final String key, final String value); static String getSystemProperty(final String key, final String defaultValue); static ClassLoader getTCCL(); static void setTCCL(final ClassLoader paramCl); }### Answer: @Test public void testGetTCCL() { if (RESTRICTED) { expectedException.expect(AccessControlException.class); } SecurityActions.getTCCL(); }
### Question: SecurityActions { public static void setTCCL(final ClassLoader paramCl) { if (System.getSecurityManager() != null) { System.getSecurityManager().checkPermission(new RuntimePermission("setContextClassLoader")); AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { Thread.currentThread().setContextClassLoader(paramCl); return null; } }); } else { Thread.currentThread().setContextClassLoader(paramCl); } } static Class<?> loadClass(final Class<?> theClass, final String fullQualifiedName); static Class<?> loadClass(final ClassLoader classLoader, final String fullQualifiedName); static URL loadResource(final Class<?> clazz, final String resourceName); static void setSystemProperty(final String key, final String value); static String getSystemProperty(final String key, final String defaultValue); static ClassLoader getTCCL(); static void setTCCL(final ClassLoader paramCl); }### Answer: @Test public void testSetTCCL() { if (RESTRICTED) { expectedException.expect(AccessControlException.class); } SecurityActions.setTCCL(ClassLoader.getSystemClassLoader()); }
### Question: ReturnFields implements Iterable<String> { @Override public String toString() { return "[ReturnFieldsImpl: fields=" + this.fields + "]"; } ReturnFields(); ReturnFields(String spec); ReturnFields child(String field); boolean included(String... pathSegments); boolean excluded(String field); Iterator<String> iterator(); boolean isEmpty(); boolean isAll(); @Override String toString(); static ReturnFields ALL; static ReturnFields NONE; static ReturnFields ALL_RECURSIVELY; }### Answer: @Test public void testBasic() { String spec = "field1,field2,field3"; ReturnFields fspec = new ReturnFields(spec); StringBuilder val = new StringBuilder(); for (String field : fspec) { if (val.length() > 0) val.append(','); val.append(field); } Assert.assertEquals(spec, val.toString()); String[] specs = { "", null, ",", "field1,", ",field2" }; for (String filter : specs) { try { fspec = new ReturnFields(filter); Assert.fail("Parsing of fields spec should have failed! : " + filter); } catch (Exception e) { } } } @Test public void testNested() { String spec = "field1,field2(sub1,sub2(subsub1)),field3"; ReturnFields fspec = new ReturnFields(spec); String val = traverse(fspec); Assert.assertEquals(spec, val.toString()); String[] specs = { "(", ")", "field1,(", "field1,)", "field1,field2(", "field1,field2)", "field1,field2()", "field1,field2(sub1)(", "field1,field2(sub1))", "field1,field2(sub1)," }; for (String filter : specs) { try { fspec = new ReturnFields(filter); Assert.fail("Parsing of fields spec should have failed! : " + filter); } catch (Exception e) { } } }
### Question: StringPropertyReplacer { public static String replaceProperties(final String string) { return replaceProperties(string, (Properties) null); } static String replaceProperties(final String string); static String replaceProperties(final String string, final Properties props); static String replaceProperties(final String string, PropertyResolver resolver); static final String NEWLINE; }### Answer: @Test public void testSystemProperties() throws NoSuchAlgorithmException { System.setProperty("prop1", "val1"); Assert.assertEquals("foo-val1", StringPropertyReplacer.replaceProperties("foo-${prop1}")); Assert.assertEquals("foo-def", StringPropertyReplacer.replaceProperties("foo-${prop2:def}")); System.setProperty("prop2", "val2"); Assert.assertEquals("foo-val2", StringPropertyReplacer.replaceProperties("foo-${prop2:def}")); Assert.assertEquals("foo-def", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); System.setProperty("prop5", "val5"); Assert.assertEquals("foo-val5", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); System.setProperty("prop4", "val4"); Assert.assertEquals("foo-val4", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); System.setProperty("prop3", "val3"); Assert.assertEquals("foo-val3", StringPropertyReplacer.replaceProperties("foo-${prop3:${prop4:${prop5:def}}}")); Assert.assertEquals("foo-def", StringPropertyReplacer.replaceProperties("foo-${prop6,prop7:def}")); System.setProperty("prop7", "val7"); Assert.assertEquals("foo-val7", StringPropertyReplacer.replaceProperties("foo-${prop6,prop7:def}")); System.setProperty("prop6", "val6"); Assert.assertEquals("foo-val6", StringPropertyReplacer.replaceProperties("foo-${prop6,prop7:def}")); }
### Question: HtmlUtils { public static String escapeAttribute(String value) { StringBuilder escaped = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char chr = value.charAt(i); if (chr == '<') { escaped.append("&lt;"); } else if (chr == '>') { escaped.append("&gt;"); } else if (chr == '"') { escaped.append("&quot;"); } else if (chr == '\'') { escaped.append("&apos;"); } else if (chr == '&') { escaped.append("&amp;"); } else { escaped.append(chr); } } return escaped.toString(); } static String escapeAttribute(String value); }### Answer: @Test public void escapeAttribute() { Assert.assertEquals("1&lt;2", HtmlUtils.escapeAttribute("1<2")); Assert.assertEquals("2&lt;3&amp;&amp;3&gt;2", HtmlUtils.escapeAttribute("2<3&&3>2") ); Assert.assertEquals("test", HtmlUtils.escapeAttribute("test")); Assert.assertEquals("&apos;test&apos;", HtmlUtils.escapeAttribute("\'test\'")); Assert.assertEquals("&quot;test&quot;", HtmlUtils.escapeAttribute("\"test\"")); }
### Question: CollectionUtil { public static String join(Collection<String> strings) { return join(strings, ", "); } static String join(Collection<String> strings); static String join(Collection<String> strings, String separator); static boolean collectionEquals(Collection<T> col1, Collection<T> col2); }### Answer: @Test public void joinInputNoneOutputEmpty() { final ArrayList<String> strings = new ArrayList<>(); final String retval = CollectionUtil.join(strings, ","); Assert.assertEquals("", retval); } @Test public void joinInput2SeparatorNull() { final ArrayList<String> strings = new ArrayList<>(); strings.add("foo"); strings.add("bar"); final String retval = CollectionUtil.join(strings, null); Assert.assertEquals("foonullbar", retval); } @Test public void joinInput1SeparatorNotNull() { final ArrayList<String> strings = new ArrayList<>(); strings.add("foo"); final String retval = CollectionUtil.join(strings, ","); Assert.assertEquals("foo", retval); } @Test public void joinInput2SeparatorNotNull() { final ArrayList<String> strings = new ArrayList<>(); strings.add("foo"); strings.add("bar"); final String retval = CollectionUtil.join(strings, ","); Assert.assertEquals("foo,bar", retval); }
### Question: KeyUtils { public static SecretKey loadSecretKey(byte[] secret, String javaAlgorithmName) { return new SecretKeySpec(secret, javaAlgorithmName); } private KeyUtils(); static SecretKey loadSecretKey(byte[] secret, String javaAlgorithmName); static KeyPair generateRsaKeyPair(int keysize); static PublicKey extractPublicKey(PrivateKey key); static String createKeyId(Key key); }### Answer: @Test public void loadSecretKey() { byte[] secretBytes = new byte[32]; ThreadLocalRandom.current().nextBytes(secretBytes); SecretKeySpec expected = new SecretKeySpec(secretBytes, "HmacSHA256"); SecretKey actual = KeyUtils.loadSecretKey(secretBytes, "HmacSHA256"); assertEquals(expected.getAlgorithm(), actual.getAlgorithm()); assertArrayEquals(expected.getEncoded(), actual.getEncoded()); }
### Question: PemUtils { static byte[] generateThumbprintBytes(String[] certChain, String encoding) throws NoSuchAlgorithmException { return MessageDigest.getInstance(encoding).digest(pemToDer(certChain[0])); } private PemUtils(); static X509Certificate decodeCertificate(String cert); static PublicKey decodePublicKey(String pem); static PrivateKey decodePrivateKey(String pem); static String encodeKey(Key key); static String encodeCertificate(Certificate certificate); static byte[] pemToDer(String pem); static String removeBeginEnd(String pem); static String generateThumbprint(String[] certChain, String encoding); }### Answer: @Test public void testGenerateThumbprintBytesSha1() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; byte[] digest = PemUtils.generateThumbprintBytes(test, "SHA-1"); assertEquals(20, digest.length); } @Test public void testGenerateThumbprintBytesSha256() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; byte[] digest = PemUtils.generateThumbprintBytes(test, "SHA-256"); assertEquals(32, digest.length); }
### Question: PemUtils { public static String generateThumbprint(String[] certChain, String encoding) throws NoSuchAlgorithmException { return Base64Url.encode(generateThumbprintBytes(certChain, encoding)); } private PemUtils(); static X509Certificate decodeCertificate(String cert); static PublicKey decodePublicKey(String pem); static PrivateKey decodePrivateKey(String pem); static String encodeKey(Key key); static String encodeCertificate(Certificate certificate); static byte[] pemToDer(String pem); static String removeBeginEnd(String pem); static String generateThumbprint(String[] certChain, String encoding); }### Answer: @Test public void testGenerateThumbprintSha1() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; String encoded = PemUtils.generateThumbprint(test, "SHA-1"); assertEquals(27, encoded.length()); } @Test public void testGenerateThumbprintSha256() throws NoSuchAlgorithmException { String[] test = new String[] {"abcdefg"}; String encoded = PemUtils.generateThumbprint(test, "SHA-256"); assertEquals(43, encoded.length()); }
### Question: RegexUtils { public static boolean valueMatchesRegex(String regex, Object value) { if (value instanceof List) { List list = (List) value; for (Object val : list) { if (valueMatchesRegex(regex, val)) { return true; } } } else { if (value != null) { String stringValue = value.toString(); return stringValue != null && stringValue.matches(regex); } } return false; } static boolean valueMatchesRegex(String regex, Object value); }### Answer: @Test public void valueMatchesRegexTest() { assertThat(RegexUtils.valueMatchesRegex("AB.*", "AB_ADMIN"), is(true)); assertThat(RegexUtils.valueMatchesRegex("AB.*", "AA_ADMIN"), is(false)); assertThat(RegexUtils.valueMatchesRegex("99.*", 999), is(true)); assertThat(RegexUtils.valueMatchesRegex("98.*", 999), is(false)); assertThat(RegexUtils.valueMatchesRegex("99\\..*", 99.9), is(true)); assertThat(RegexUtils.valueMatchesRegex("AB.*", null), is(false)); assertThat(RegexUtils.valueMatchesRegex("AB.*", Arrays.asList("AB_ADMIN", "AA_ADMIN")), is(true)); }
### Question: JWK { public String getAlgorithm() { return algorithm; } String getKeyId(); void setKeyId(String keyId); String getKeyType(); void setKeyType(String keyType); String getAlgorithm(); void setAlgorithm(String algorithm); String getPublicKeyUse(); void setPublicKeyUse(String publicKeyUse); @JsonAnyGetter Map<String, Object> getOtherClaims(); @JsonAnySetter void setOtherClaims(String name, Object value); static final String KEY_ID; static final String KEY_TYPE; static final String ALGORITHM; static final String PUBLIC_KEY_USE; }### Answer: @Test public void parse() { String jwkJson = "{" + " \"kty\": \"RSA\"," + " \"alg\": \"RS256\"," + " \"use\": \"sig\"," + " \"kid\": \"3121adaa80ace09f89d80899d4a5dc4ce33d0747\"," + " \"n\": \"soFDjoZ5mQ8XAA7reQAFg90inKAHk0DXMTizo4JuOsgzUbhcplIeZ7ks83hsEjm8mP8lUVaHMPMAHEIp3gu6Xxsg-s73ofx1dtt_Fo7aj8j383MFQGl8-FvixTVobNeGeC0XBBQjN8lEl-lIwOa4ZoERNAShplTej0ntDp7TQm0=\"," + " \"e\": \"AQAB\"" + " }"; PublicKey key = JWKParser.create().parse(jwkJson).toPublicKey(); assertEquals("RSA", key.getAlgorithm()); assertEquals("X.509", key.getFormat()); }
### Question: StringListMapDeserializer extends JsonDeserializer<Object> { @Override public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { JsonNode jsonNode = jsonParser.readValueAsTree(); Iterator<Map.Entry<String, JsonNode>> itr = jsonNode.fields(); Map<String, List<String>> map = new HashMap<>(); while (itr.hasNext()) { Map.Entry<String, JsonNode> e = itr.next(); List<String> values = new LinkedList<>(); if (!e.getValue().isArray()) { values.add((e.getValue().isNull()) ? null : e.getValue().asText()); } else { ArrayNode a = (ArrayNode) e.getValue(); Iterator<JsonNode> vitr = a.elements(); while (vitr.hasNext()) { JsonNode node = vitr.next(); values.add((node.isNull() ? null : node.asText())); } } map.put(e.getKey(), values); } return map; } @Override Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext); }### Answer: @Test public void nonNullValue() throws IOException { Map<String, List<String>> attributes = deserialize("\"foo\": \"bar\""); assertTrue(attributes.containsKey("foo")); List<String> foo = attributes.get("foo"); assertEquals(1, foo.size()); assertEquals("bar", foo.get(0)); } @Test public void nonNullValueArray() throws IOException { Map<String, List<String>> attributes = deserialize("\"foo\": [ \"bar\", \"baz\" ]"); assertTrue(attributes.containsKey("foo")); List<String> foo = attributes.get("foo"); assertEquals(2, foo.size()); assertEquals("baz", foo.get(1)); } @Test public void nullValue() throws IOException { Map<String, List<String>> attributes = deserialize("\"foo\": null"); assertTrue(attributes.containsKey("foo")); List<String> foo = attributes.get("foo"); assertEquals(1, foo.size()); assertNull(foo.get(0)); } @Test public void nullValueArray() throws IOException { Map<String, List<String>> attributes = deserialize("\"foo\": [ null, \"something\", null ]"); assertTrue(attributes.containsKey("foo")); List<String> foo = attributes.get("foo"); assertEquals(3, foo.size()); assertEquals("something", foo.get(1)); assertNull(foo.get(2)); }
### Question: PropertiesUtil { public static Charset detectEncoding(InputStream in) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(in, DEFAULT_ENCODING))) { String firstLine = br.readLine(); if (firstLine != null) { Matcher matcher = DETECT_ENCODING_PATTERN.matcher(firstLine); if (matcher.find()) { String encoding = matcher.group(1); if (Charset.isSupported(encoding)) { return Charset.forName(encoding); } else { logger.warnv("Unsupported encoding: {0}", encoding); } } } } return DEFAULT_ENCODING; } static Charset detectEncoding(InputStream in); static final Pattern DETECT_ENCODING_PATTERN; static final Charset DEFAULT_ENCODING; }### Answer: @Test public void testDetectEncoding() throws Exception { Charset encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: utf-8\nkey=value".getBytes())); assertEquals(Charset.forName("utf-8"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: Shift_JIS\nkey=value".getBytes())); assertEquals(Charset.forName("Shift_JIS"), encoding); } @Test public void testDefaultEncoding() throws Exception { Charset encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("key=value".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("# encoding: unknown\nkey=value".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("\n# encoding: utf-8\nkey=value".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); encoding = PropertiesUtil.detectEncoding(new ByteArrayInputStream("".getBytes())); assertEquals(Charset.forName("ISO-8859-1"), encoding); }
### Question: KeyPairVerifier { public static void verify(String privateKeyPem, String publicKeyPem) throws VerificationException { PrivateKey privateKey; try { privateKey = PemUtils.decodePrivateKey(privateKeyPem); } catch (Exception e) { throw new VerificationException("Failed to decode private key"); } PublicKey publicKey; try { publicKey = PemUtils.decodePublicKey(publicKeyPem); } catch (Exception e) { throw new VerificationException("Failed to decode public key"); } try { String jws = new JWSBuilder().content("content".getBytes()).rsa256(privateKey); if (!RSAProvider.verify(new JWSInput(jws), publicKey)) { throw new VerificationException("Keys don't match"); } } catch (Exception e) { throw new VerificationException("Keys don't match"); } } static void verify(String privateKeyPem, String publicKeyPem); }### Answer: @Test public void verify() throws Exception { KeyPairVerifier.verify(privateKey1, publicKey1); KeyPairVerifier.verify(privateKey2048, publicKey2048); try { KeyPairVerifier.verify(privateKey1, publicKey2048); Assert.fail("Expected VerificationException"); } catch (VerificationException e) { } try { KeyPairVerifier.verify(privateKey2048, publicKey1); Assert.fail("Expected VerificationException"); } catch (VerificationException e) { } }
### Question: MessageFormatterMethod implements TemplateMethodModelEx { @Override public Object exec(List list) throws TemplateModelException { if (list.size() >= 1) { List<Object> resolved = resolve(list.subList(1, list.size())); String key = list.get(0).toString(); return new MessageFormat(messages.getProperty(key,key),locale).format(resolved.toArray()); } else { return null; } } MessageFormatterMethod(Locale locale, Properties messages); @Override Object exec(List list); }### Answer: @Test public void test() throws TemplateModelException { Locale locale = Locale.US; Properties properties = new Properties(); properties.setProperty("backToApplication", "Back to application"); properties.setProperty("backToClient", "Back to {0}"); properties.setProperty("client_admin-console", "Admin Console"); properties.setProperty("realm_example-realm", "Example Realm"); MessageFormatterMethod fmt = new MessageFormatterMethod(locale, properties); String msg = (String) fmt.exec(Arrays.asList("backToClient", "${client_admin-console}")); Assert.assertEquals("Back to Admin Console", msg); msg = (String) fmt.exec(Arrays.asList("backToClient", "client_admin-console")); Assert.assertEquals("Back to client_admin-console", msg); msg = (String) fmt.exec(Arrays.asList("backToClient", "client '${client_admin-console}' from '${realm_example-realm}'.")); Assert.assertEquals("Back to client 'Admin Console' from 'Example Realm'.", msg); }
### Question: LinkExpirationFormatterMethod implements TemplateMethodModelEx { @SuppressWarnings("rawtypes") @Override public Object exec(List arguments) throws TemplateModelException { Object val = arguments.isEmpty() ? null : arguments.get(0); if (val == null) return ""; try { return format(Long.parseLong(val.toString().trim()) * 60); } catch (NumberFormatException e) { return val.toString(); } } LinkExpirationFormatterMethod(Properties messages, Locale locale); @SuppressWarnings("rawtypes") @Override Object exec(List arguments); }### Answer: @Test public void inputtypes_null() throws TemplateModelException{ LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("", tested.exec(Collections.emptyList())); } @Test public void inputtypes_string_empty() throws TemplateModelException{ LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("", tested.exec(toList(""))); Assert.assertEquals(" ", tested.exec(toList(" "))); } @Test public void inputtypes_string_number() throws TemplateModelException{ LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("2 minutes", tested.exec(toList("2"))); Assert.assertEquals("2 minutes", tested.exec(toList(" 2 "))); } @Test public void inputtypes_string_notanumber() throws TemplateModelException{ LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("ahoj", tested.exec(toList("ahoj"))); } @Test public void inputtypes_number() throws TemplateModelException{ LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("5 minutes", tested.exec(toList(new Integer(5)))); Assert.assertEquals("5 minutes", tested.exec(toList(new Long(5)))); } @Test public void format_second_zero() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("0 seconds", tested.exec(toList(0))); } @Test public void format_minute_one() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("1 minute", tested.exec(toList(1))); } @Test public void format_minute_more() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("2 minutes", tested.exec(toList(2))); Assert.assertEquals("3 minutes-3", tested.exec(toList(3))); Assert.assertEquals("5 minutes", tested.exec(toList(5))); Assert.assertEquals("24 minutes", tested.exec(toList(24))); Assert.assertEquals("59 minutes", tested.exec(toList(59))); Assert.assertEquals("61 minutes", tested.exec(toList(61))); } @Test public void format_hour_one() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("1 hour", tested.exec(toList(60))); } @Test public void format_hour_more() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("2 hours", tested.exec(toList(2 * 60))); Assert.assertEquals("5 hours", tested.exec(toList(5 * 60))); Assert.assertEquals("23 hours", tested.exec(toList(23 * 60))); Assert.assertEquals("25 hours", tested.exec(toList(25 * 60))); } @Test public void format_day_one() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("1 day", tested.exec(toList(60 * 24))); } @Test public void format_day_more() throws TemplateModelException { LinkExpirationFormatterMethod tested = new LinkExpirationFormatterMethod(messages, locale); Assert.assertEquals("2 days", tested.exec(toList(2 * 24 * 60))); Assert.assertEquals("5 days", tested.exec(toList(5 * 24 * 60))); }
### Question: InitializerState extends SessionEntity { public int getSegmentsCount() { return segmentsCount; } InitializerState(int segmentsCount); private InitializerState(String realmId, int segmentsCount, BitSet segments); int getSegmentsCount(); boolean isFinished(); List<Integer> getSegmentsToLoad(int segmentToLoad, int maxSegmentCount); void markSegmentFinished(int index); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testOfflineLoaderContext() { OfflinePersistentLoaderContext ctx = new OfflinePersistentLoaderContext(28, 5); Assert.assertEquals(ctx.getSegmentsCount(), 6); ctx = new OfflinePersistentLoaderContext(19, 5); Assert.assertEquals(ctx.getSegmentsCount(), 4); ctx = new OfflinePersistentLoaderContext(20, 5); Assert.assertEquals(ctx.getSegmentsCount(), 4); ctx = new OfflinePersistentLoaderContext(21, 5); Assert.assertEquals(ctx.getSegmentsCount(), 5); }
### Question: JpaUtils { public static String getCustomChangelogTableName(String jpaEntityProviderFactoryId) { String upperCased = jpaEntityProviderFactoryId.toUpperCase(); upperCased = upperCased.replaceAll("-", "_"); upperCased = upperCased.replaceAll("[^A-Z_]", ""); return "DATABASECHANGELOG_" + upperCased.substring(0, Math.min(10, upperCased.length())); } static String getTableNameForNativeQuery(String tableName, EntityManager em); static EntityManagerFactory createEntityManagerFactory(KeycloakSession session, String unitName, Map<String, Object> properties, boolean jta); static List<Class<?>> getProvidedEntities(KeycloakSession session); static String getCustomChangelogTableName(String jpaEntityProviderFactoryId); static final String HIBERNATE_DEFAULT_SCHEMA; }### Answer: @Test public void testConvertTableName() { Assert.assertEquals("DATABASECHANGELOG_FOO", JpaUtils.getCustomChangelogTableName("foo")); Assert.assertEquals("DATABASECHANGELOG_FOOBAR", JpaUtils.getCustomChangelogTableName("foo123bar")); Assert.assertEquals("DATABASECHANGELOG_FOO_BAR", JpaUtils.getCustomChangelogTableName("foo_bar568")); Assert.assertEquals("DATABASECHANGELOG_FOO_BAR_C", JpaUtils.getCustomChangelogTableName("foo-bar-c568")); Assert.assertEquals("DATABASECHANGELOG_EXAMPLE_EN", JpaUtils.getCustomChangelogTableName("example-entity-provider")); }
### Question: KeyUtils { public static boolean isValidKey(String key) { return key == null || EXPECTED_KEY_PATTERN.matcher(key).matches(); } static boolean isValidKey(String key); static void assertValidKey(String key); static final Pattern UUID_PATTERN; static final Pattern EXPECTED_KEY_PATTERN; }### Answer: @Test public void testValidKeys() { assertTrue(KeyUtils.isValidKey(UUID.randomUUID().toString())); assertTrue(KeyUtils.isValidKey("01234567-1234-1234-aAAa-123456789012")); assertTrue(KeyUtils.isValidKey("01234567-1234-1234-aAAf-123456789012")); assertTrue(KeyUtils.isValidKey("f:" + UUID.randomUUID() + ":dsadsada")); assertTrue(KeyUtils.isValidKey("f:01234567-1234-1234-aAAa-123456789012:dsadsada")); assertTrue(KeyUtils.isValidKey("f:a1234567-1234-1234-aAAa-123456789012:dsadsada")); } @Test public void testInvalidKeys() { assertFalse(KeyUtils.isValidKey("any string")); assertFalse(KeyUtils.isValidKey("0")); assertFalse(KeyUtils.isValidKey("01234567-1234-1234-aAAg-123456789012a")); assertFalse(KeyUtils.isValidKey("z1234567-1234-1234-aAAa-123456789012")); assertFalse(KeyUtils.isValidKey("f:g1234567-1234-1234-aAAa-123456789012:dsadsada")); assertFalse(KeyUtils.isValidKey("g:a1234567-1234-1234-aAAa-123456789012:dsadsada")); assertFalse(KeyUtils.isValidKey("f:a1234567-1234-1234-aAAa-123456789012")); }
### Question: HttpAdapterUtils { public static MultivaluedHashMap<String, KeyInfo> extractKeysFromSamlDescriptor(InputStream xmlStream) throws ParsingException { Object res = new SamlDescriptorIDPKeysExtractor().parse(xmlStream); return (MultivaluedHashMap<String, KeyInfo>) res; } static MultivaluedHashMap<String, KeyInfo> downloadKeysFromSamlDescriptor(HttpClient client, String descriptorUrl); static MultivaluedHashMap<String, KeyInfo> extractKeysFromSamlDescriptor(InputStream xmlStream); }### Answer: @Test public void testExtractKeysFromSamlDescriptor() throws ParsingException { InputStream xmlStream = HttpAdapterUtilsTest.class.getResourceAsStream("saml-descriptor-valid.xml"); MultivaluedHashMap<String, KeyInfo> res = HttpAdapterUtils.extractKeysFromSamlDescriptor(xmlStream); assertThat(res, notNullValue()); assertThat(res.keySet(), hasItems(KeyTypes.SIGNING.value())); assertThat(res.get(KeycloakSamlAdapterV1QNames.ATTR_SIGNING.getQName().getLocalPart()), notNullValue()); assertThat(res.get(KeycloakSamlAdapterV1QNames.ATTR_SIGNING.getQName().getLocalPart()).size(), equalTo(2)); KeyInfo ki; KeyName keyName; X509Data x509data; X509Certificate x509certificate; Matcher<Iterable<? super XMLStructure>> x509DataMatcher = hasItem(instanceOf(X509Data.class)); Matcher<Iterable<? super XMLStructure>> keyNameMatcher = hasItem(instanceOf(KeyName.class)); ki = res.get(KeycloakSamlAdapterV1QNames.ATTR_SIGNING.getQName().getLocalPart()).get(0); assertThat(ki.getContent().size(), equalTo(2)); assertThat((Iterable<? super XMLStructure>) ki.getContent(), x509DataMatcher); assertThat((Iterable<? super XMLStructure>) ki.getContent(), keyNameMatcher); keyName = getContent(ki.getContent(), KeyName.class); assertThat(keyName.getName(), equalTo("rJkJlvowmv1Id74GznieaAC5jU5QQp_ILzuG-GsweTI")); x509data = getContent(ki.getContent(), X509Data.class); assertThat(x509data, notNullValue()); x509certificate = getContent(x509data.getContent(), X509Certificate.class); assertThat(x509certificate, notNullValue()); assertThat(x509certificate.getSigAlgName(), equalTo("SHA256withRSA")); ki = res.get(KeycloakSamlAdapterV1QNames.ATTR_SIGNING.getQName().getLocalPart()).get(1); assertThat(ki.getContent().size(), equalTo(2)); assertThat((Iterable<? super XMLStructure>) ki.getContent(), x509DataMatcher); assertThat((Iterable<? super XMLStructure>) ki.getContent(), keyNameMatcher); keyName = getContent(ki.getContent(), KeyName.class); assertThat(keyName.getName(), equalTo("BzYc4GwL8HVrAhNyNdp-lTah2DvU9jU03kby9Ynohr4")); x509data = getContent(ki.getContent(), X509Data.class); assertThat(x509data, notNullValue()); x509certificate = getContent(x509data.getContent(), X509Certificate.class); assertThat(x509certificate, notNullValue()); assertThat(x509certificate.getSigAlgName(), equalTo("SHA256withRSA")); }
### Question: PropertiesBasedRoleMapper implements RoleMappingsProvider { @Override public Set<String> map(final String principalName, final Set<String> roles) { if (this.roleMappings == null || this.roleMappings.isEmpty()) return roles; Set<String> resolvedRoles = new HashSet<>(); for (String role : roles) { if (this.roleMappings.containsKey(role)) { this.extractRolesIntoSet(role, resolvedRoles); } else { resolvedRoles.add(role); } } if (this.roleMappings.containsKey(principalName)) { this.extractRolesIntoSet(principalName, resolvedRoles); } return resolvedRoles; } @Override String getId(); @Override void init(final SamlDeployment deployment, final ResourceLoader loader, final Properties config); @Override Set<String> map(final String principalName, final Set<String> roles); static final String PROVIDER_ID; }### Answer: @Test public void testPropertiesBasedRoleMapper() throws Exception { InputStream is = getClass().getResourceAsStream("config/parsers/keycloak-saml-with-role-mappings-provider.xml"); SamlDeployment deployment = new DeploymentBuilder().build(is, new ResourceLoader() { @Override public InputStream getResourceAsStream(String resource) { return this.getClass().getClassLoader().getResourceAsStream(resource); } }); RoleMappingsProvider provider = deployment.getRoleMappingsProvider(); final Set<String> samlRoles = new HashSet<>(Arrays.asList(new String[]{"samlRoleA", "samlRoleB", "samlRoleC"})); final Set<String> mappedRoles = provider.map("kc-user", samlRoles); assertNotNull(mappedRoles); assertEquals(4, mappedRoles.size()); Set<String> expectedRoles = new HashSet<>(Arrays.asList(new String[]{"samlRoleC", "jeeRoleX", "jeeRoleY", "jeeRoleZ"})); assertEquals(expectedRoles, mappedRoles); }
### Question: HttpHeaderInspectingApiRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return X_REQUESTED_WITH_HEADER_AJAX_VALUE.equals(request.getHeader(X_REQUESTED_WITH_HEADER)); } @Override boolean matches(HttpServletRequest request); }### Answer: @Test public void testMatchesBrowserRequest() throws Exception { request.addHeader(HttpHeaders.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); assertFalse(apiRequestMatcher.matches(request)); } @Test public void testMatchesRequestedWith() throws Exception { request.addHeader( HttpHeaderInspectingApiRequestMatcher.X_REQUESTED_WITH_HEADER, HttpHeaderInspectingApiRequestMatcher.X_REQUESTED_WITH_HEADER_AJAX_VALUE); assertTrue(apiRequestMatcher.matches(request)); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected OAuthRequestAuthenticator createOAuthAuthenticator() { return new OAuthRequestAuthenticator(this, facade, deployment, sslRedirectPort, tokenStore); } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testCreateOAuthAuthenticator() throws Exception { OAuthRequestAuthenticator oathAuthenticator = authenticator.createOAuthAuthenticator(); assertNotNull(oathAuthenticator); }
### Question: OIDCAttributeMapperHelper { public static List<String> splitClaimPath(String claimPath) { final LinkedList<String> claimComponents = new LinkedList<>(); Matcher m = CLAIM_COMPONENT.matcher(claimPath); int start = 0; while (m.find()) { claimComponents.add(BACKSLASHED_CHARACTER.matcher(m.group(1)).replaceAll("$1")); start = m.end(); m.region(start, claimPath.length()); } if (claimPath.length() > start) { claimComponents.add(BACKSLASHED_CHARACTER.matcher(claimPath.substring(start)).replaceAll("$1")); } return claimComponents; } static Object mapAttributeValue(ProtocolMapperModel mappingModel, Object attributeValue); static List<String> splitClaimPath(String claimPath); static void mapClaim(IDToken token, ProtocolMapperModel mappingModel, Object attributeValue); static ProtocolMapperModel createClaimMapper(String name, String userAttribute, String tokenClaimName, String claimType, boolean accessToken, boolean idToken, String mapperId); static ProtocolMapperModel createClaimMapper(String name, String userAttribute, String tokenClaimName, String claimType, boolean accessToken, boolean idToken, boolean userinfo, String mapperId); static boolean includeInIDToken(ProtocolMapperModel mappingModel); static boolean includeInAccessToken(ProtocolMapperModel mappingModel); static boolean isMultivalued(ProtocolMapperModel mappingModel); static boolean includeInUserInfo(ProtocolMapperModel mappingModel); static void addAttributeConfig(List<ProviderConfigProperty> configProperties, Class<? extends ProtocolMapper> protocolMapperClass); static void addTokenClaimNameConfig(List<ProviderConfigProperty> configProperties); static void addJsonTypeConfig(List<ProviderConfigProperty> configProperties); static void addIncludeInTokensConfig(List<ProviderConfigProperty> configProperties, Class<? extends ProtocolMapper> protocolMapperClass); static final String TOKEN_CLAIM_NAME; static final String TOKEN_CLAIM_NAME_LABEL; static final String TOKEN_CLAIM_NAME_TOOLTIP; static final String JSON_TYPE; static final String JSON_TYPE_TOOLTIP; static final String INCLUDE_IN_ACCESS_TOKEN; static final String INCLUDE_IN_ACCESS_TOKEN_LABEL; static final String INCLUDE_IN_ACCESS_TOKEN_HELP_TEXT; static final String INCLUDE_IN_ID_TOKEN; static final String INCLUDE_IN_ID_TOKEN_LABEL; static final String INCLUDE_IN_ID_TOKEN_HELP_TEXT; static final String INCLUDE_IN_USERINFO; static final String INCLUDE_IN_USERINFO_LABEL; static final String INCLUDE_IN_USERINFO_HELP_TEXT; }### Answer: @Test public void testSplitClaimPath() { assertThat(OIDCAttributeMapperHelper.splitClaimPath(""), Matchers.empty()); assertThat(OIDCAttributeMapperHelper.splitClaimPath("a"), Matchers.contains("a")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("a.b"), Matchers.contains("a", "b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("a\\.b"), Matchers.contains("a.b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("a\\\\.b"), Matchers.contains("a\\", "b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("a\\\\\\.b"), Matchers.contains("a\\.b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("c.a\\\\.b"), Matchers.contains("c", "a\\", "b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("c.a\\\\\\.b"), Matchers.contains("c", "a\\.b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("c\\\\\\.b.a\\\\\\.b"), Matchers.contains("c\\.b", "a\\.b")); assertThat(OIDCAttributeMapperHelper.splitClaimPath("c\\h\\.b.a\\\\\\.b"), Matchers.contains("ch.b", "a\\.b")); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected void completeOAuthAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) { final RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext(); final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); final OidcKeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); this.tokenStore.saveAccountInfo(account); } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testCompleteOAuthAuthentication() throws Exception { authenticator.completeOAuthAuthentication(principal); verify(request).setAttribute(eq(KeycloakSecurityContext.class.getName()), eq(refreshableKeycloakSecurityContext)); verify(tokenStore).saveAccountInfo(any(OidcKeycloakAccount.class)); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) { RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext(); Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext); final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); logger.debug("Completing bearer authentication. Bearer roles: {} ",roles); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new KeycloakAuthenticationToken(account, false)); SecurityContextHolder.setContext(context); request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext); } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testCompleteBearerAuthentication() throws Exception { authenticator.completeBearerAuthentication(principal, "foo"); verify(request).setAttribute(eq(KeycloakSecurityContext.class.getName()), eq(refreshableKeycloakSecurityContext)); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); assertTrue(KeycloakAuthenticationToken.class.isAssignableFrom(SecurityContextHolder.getContext().getAuthentication().getClass())); }
### Question: SpringSecurityRequestAuthenticator extends RequestAuthenticator { @Override protected String changeHttpSessionId(boolean create) { HttpSession session = request.getSession(create); return session != null ? session.getId() : null; } SpringSecurityRequestAuthenticator( HttpFacade facade, HttpServletRequest request, KeycloakDeployment deployment, AdapterTokenStore tokenStore, int sslRedirectPort); }### Answer: @Test public void testGetHttpSessionIdTrue() throws Exception { String sessionId = authenticator.changeHttpSessionId(true); assertNotNull(sessionId); } @Test public void testGetHttpSessionIdFalse() throws Exception { String sessionId = authenticator.changeHttpSessionId(false); assertNull(sessionId); }
### Question: KeycloakAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) authentication; List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (String role : token.getAccount().getRoles()) { grantedAuthorities.add(new KeycloakRole(role)); } return new KeycloakAuthenticationToken(token.getAccount(), token.isInteractive(), mapAuthorities(grantedAuthorities)); } void setGrantedAuthoritiesMapper(GrantedAuthoritiesMapper grantedAuthoritiesMapper); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> aClass); }### Answer: @Test public void testAuthenticate() throws Exception { assertAuthenticationResult(provider.authenticate(token)); } @Test public void testAuthenticateInteractive() throws Exception { assertAuthenticationResult(provider.authenticate(interactiveToken)); }
### Question: KeycloakAuthenticationProvider implements AuthenticationProvider { @Override public boolean supports(Class<?> aClass) { return KeycloakAuthenticationToken.class.isAssignableFrom(aClass); } void setGrantedAuthoritiesMapper(GrantedAuthoritiesMapper grantedAuthoritiesMapper); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> aClass); }### Answer: @Test public void testSupports() throws Exception { assertTrue(provider.supports(KeycloakAuthenticationToken.class)); assertFalse(provider.supports(PreAuthenticatedAuthenticationToken.class)); }
### Question: KeycloakLogoutHandler implements LogoutHandler { @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (authentication == null) { log.warn("Cannot log out without authentication"); return; } else if (!KeycloakAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { log.warn("Cannot log out a non-Keycloak authentication: {}", authentication); return; } handleSingleSignOut(request, response, (KeycloakAuthenticationToken) authentication); } KeycloakLogoutHandler(AdapterDeploymentContext adapterDeploymentContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); }### Answer: @Test public void testLogout() throws Exception { keycloakLogoutHandler.logout(request, response, keycloakAuthenticationToken); verify(session).logout(eq(keycloakDeployment)); } @Test public void testLogoutAnonymousAuthentication() throws Exception { Authentication authentication = new AnonymousAuthenticationToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), authorities); keycloakLogoutHandler.logout(request, response, authentication); verifyZeroInteractions(session); } @Test public void testLogoutUsernamePasswordAuthentication() throws Exception { Authentication authentication = new UsernamePasswordAuthenticationToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), authorities); keycloakLogoutHandler.logout(request, response, authentication); verifyZeroInteractions(session); } @Test public void testLogoutRememberMeAuthentication() throws Exception { Authentication authentication = new RememberMeAuthenticationToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), authorities); keycloakLogoutHandler.logout(request, response, authentication); verifyZeroInteractions(session); } @Test public void testLogoutNullAuthentication() throws Exception { keycloakLogoutHandler.logout(request, response, null); verifyZeroInteractions(session); }
### Question: X509AuthenticatorConfigModel extends AuthenticatorConfigModel { public boolean isCertValidationEnabled() { return Boolean.parseBoolean(getConfig().get(TIMESTAMP_VALIDATION)); } X509AuthenticatorConfigModel(AuthenticatorConfigModel model); X509AuthenticatorConfigModel(); boolean getCRLEnabled(); X509AuthenticatorConfigModel setCRLEnabled(boolean value); boolean getOCSPEnabled(); X509AuthenticatorConfigModel setOCSPEnabled(boolean value); boolean getCRLDistributionPointEnabled(); X509AuthenticatorConfigModel setCRLDistributionPointEnabled(boolean value); String getCRLRelativePath(); X509AuthenticatorConfigModel setCRLRelativePath(String path); String getOCSPResponder(); X509AuthenticatorConfigModel setOCSPResponder(String responderUri); String getOCSPResponderCertificate(); X509AuthenticatorConfigModel setOCSPResponderCertificate(String responderCert); MappingSourceType getMappingSourceType(); X509AuthenticatorConfigModel setMappingSourceType(MappingSourceType value); IdentityMapperType getUserIdentityMapperType(); X509AuthenticatorConfigModel setUserIdentityMapperType(IdentityMapperType value); String getRegularExpression(); X509AuthenticatorConfigModel setRegularExpression(String value); String getCustomAttributeName(); X509AuthenticatorConfigModel setCustomAttributeName(String value); String getKeyUsage(); X509AuthenticatorConfigModel setKeyUsage(String value); String getExtendedKeyUsage(); X509AuthenticatorConfigModel setExtendedKeyUsage(String value); boolean getConfirmationPageDisallowed(); boolean getConfirmationPageAllowed(); X509AuthenticatorConfigModel setConfirmationPageDisallowed(boolean value); X509AuthenticatorConfigModel setConfirmationPageAllowed(boolean value); boolean isCanonicalDnEnabled(); X509AuthenticatorConfigModel setCanonicalDnEnabled(boolean value); boolean isCertValidationEnabled(); X509AuthenticatorConfigModel setCertValidationEnabled(boolean value); boolean isSerialnumberHex(); X509AuthenticatorConfigModel setSerialnumberHex(boolean value); }### Answer: @Test public void testTimestampValidationAttributeReturnsNull() { X509AuthenticatorConfigModel configModel = new X509AuthenticatorConfigModel(); Assert.assertNull(configModel.getConfig().get(AbstractX509ClientCertificateAuthenticator.TIMESTAMP_VALIDATION)); Assert.assertFalse(configModel.isCertValidationEnabled()); }
### Question: KeycloakLogoutHandler implements LogoutHandler { protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response, KeycloakAuthenticationToken authenticationToken) { HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response).logout(); RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) authenticationToken.getAccount().getKeycloakSecurityContext(); session.logout(deployment); } KeycloakLogoutHandler(AdapterDeploymentContext adapterDeploymentContext); void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory); @Override void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); }### Answer: @Test public void testHandleSingleSignOut() throws Exception { keycloakLogoutHandler.handleSingleSignOut(request, response, keycloakAuthenticationToken); verify(session).logout(eq(keycloakDeployment)); }
### Question: KeycloakAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpFacade facade = new SimpleHttpFacade(request, response); if (apiRequestMatcher.matches(request) || adapterDeploymentContext.resolveDeployment(facade).isBearerOnly()) { commenceUnauthorizedResponse(request, response); } else { commenceLoginRedirect(request, response); } } KeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext); KeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext, RequestMatcher apiRequestMatcher); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); void setLoginUri(String loginUri); void setRealm(String realm); static final String DEFAULT_LOGIN_URI; }### Answer: @Test public void testCommenceWithRedirect() throws Exception { configureBrowserRequest(); authenticationEntryPoint.commence(request, response, null); assertEquals(HttpStatus.FOUND.value(), response.getStatus()); assertEquals(KeycloakAuthenticationEntryPoint.DEFAULT_LOGIN_URI, response.getHeader("Location")); } @Test public void testCommenceWithRedirectNotRootContext() throws Exception { configureBrowserRequest(); String contextPath = "/foo"; request.setContextPath(contextPath); authenticationEntryPoint.commence(request, response, null); assertEquals(HttpStatus.FOUND.value(), response.getStatus()); assertEquals(contextPath + KeycloakAuthenticationEntryPoint.DEFAULT_LOGIN_URI, response.getHeader("Location")); } @Test public void testCommenceWithUnauthorizedWithAccept() throws Exception { request.addHeader(HttpHeaders.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); authenticationEntryPoint.commence(request, response, null); assertEquals(HttpStatus.FOUND.value(), response.getStatus()); assertNull(response.getHeader(HttpHeaders.WWW_AUTHENTICATE)); } @Test public void testCommenceWithCustomRequestMatcher() throws Exception { new KeycloakAuthenticationEntryPoint(adapterDeploymentContext, requestMatcher) .commence(request, response, null); verify(requestMatcher).matches(request); }
### Question: KeycloakAuthenticationEntryPoint implements AuthenticationEntryPoint { public void setLoginUri(String loginUri) { Assert.notNull(loginUri, "loginUri cannot be null"); this.loginUri = loginUri; } KeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext); KeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext, RequestMatcher apiRequestMatcher); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); void setLoginUri(String loginUri); void setRealm(String realm); static final String DEFAULT_LOGIN_URI; }### Answer: @Test public void testSetLoginUri() throws Exception { configureBrowserRequest(); final String logoutUri = "/foo"; authenticationEntryPoint.setLoginUri(logoutUri); authenticationEntryPoint.commence(request, response, null); assertEquals(HttpStatus.FOUND.value(), response.getStatus()); assertEquals(logoutUri, response.getHeader("Location")); }