language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__dubbo
dubbo-compatible/src/test/java/org/apache/dubbo/rpc/cluster/NewRouter.java
{ "start": 1028, "end": 1514 }
class ____ implements Router { @Override public URL getUrl() { return null; } @Override public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { return null; } @Override public boolean isRuntime() { return false; } @Override public boolean isForce() { return false; } @Override public int getPriority() { return 0; } }
NewRouter
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/RepeatingSequenceInputTypeStrategy.java
{ "start": 1603, "end": 4846 }
class ____ implements InputTypeStrategy { private final List<ArgumentTypeStrategy> argumentStrategies; public RepeatingSequenceInputTypeStrategy(List<ArgumentTypeStrategy> argumentStrategies) { this.argumentStrategies = argumentStrategies; } @Override public ArgumentCount getArgumentCount() { return new ArgumentCount() { @Override public boolean isValidCount(int count) { return count % argumentStrategies.size() == 0; } @Override public Optional<Integer> getMinCount() { return Optional.empty(); } @Override public Optional<Integer> getMaxCount() { return Optional.empty(); } }; } @Override public Optional<List<DataType>> inferInputTypes( CallContext callContext, boolean throwOnFailure) { final List<DataType> dataTypes = callContext.getArgumentDataTypes(); final List<DataType> inferredDataTypes = new ArrayList<>(dataTypes.size()); for (int i = 0; i < callContext.getArgumentDataTypes().size(); i++) { final ArgumentTypeStrategy argumentStrategy = argumentStrategies.get(i % argumentStrategies.size()); final Optional<DataType> inferredDataType = argumentStrategy.inferArgumentType(callContext, i, throwOnFailure); if (!inferredDataType.isPresent()) { return Optional.empty(); } inferredDataTypes.add(inferredDataType.get()); } return Optional.of(inferredDataTypes); } @Override public List<Signature> getExpectedSignatures(FunctionDefinition definition) { final List<Signature.Argument> arguments = new ArrayList<>(); for (int i = 0; i < argumentStrategies.size(); i++) { final Signature.Argument argument = argumentStrategies.get(i).getExpectedArgument(definition, i); final Signature.Argument newArgument; if (i == 0) { newArgument = Signature.Argument.of(String.format("[%s", argument.getType())); } else if (i == argumentStrategies.size() - 1) { newArgument = Signature.Argument.of(String.format("%s]...", argument.getType())); } else { newArgument = argument; } arguments.add(newArgument); } final Signature signature = Signature.of(arguments); return Collections.singletonList(signature); } // --------------------------------------------------------------------------------------------- @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } final RepeatingSequenceInputTypeStrategy that = (RepeatingSequenceInputTypeStrategy) other; return Objects.equals(argumentStrategies, that.argumentStrategies); } @Override public int hashCode() { return Objects.hash(argumentStrategies); } }
RepeatingSequenceInputTypeStrategy
java
apache__hadoop
hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/StubContext.java
{ "start": 3567, "end": 4242 }
class ____ extends RecordWriter<Text, Text> { List<Text> keys = new ArrayList<Text>(); List<Text> values = new ArrayList<Text>(); @Override public void write(Text key, Text value) throws IOException, InterruptedException { keys.add(key); values.add(value); } @Override public void close(TaskAttemptContext context) throws IOException, InterruptedException { } public List<Text> keys() { return keys; } public List<Text> values() { return values; } } public static TaskAttemptID getTaskAttemptID(int taskId) { return new TaskAttemptID("", 0, TaskType.MAP, taskId, 0); } }
StubInMemoryWriter
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/dao/HistoryInfo.java
{ "start": 1175, "end": 1906 }
class ____ { protected long startedOn; protected String hadoopVersion; protected String hadoopBuildVersion; protected String hadoopVersionBuiltOn; public HistoryInfo() { this.startedOn = JobHistoryServer.historyServerTimeStamp; this.hadoopVersion = VersionInfo.getVersion(); this.hadoopBuildVersion = VersionInfo.getBuildVersion(); this.hadoopVersionBuiltOn = VersionInfo.getDate(); } public String getHadoopVersion() { return this.hadoopVersion; } public String getHadoopBuildVersion() { return this.hadoopBuildVersion; } public String getHadoopVersionBuiltOn() { return this.hadoopVersionBuiltOn; } public long getStartedOn() { return this.startedOn; } }
HistoryInfo
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 49297, "end": 49469 }
class ____ extends" + " LocalInjectMemberNoConstructor {", " }", "", " public static final
ParentInjectMemberNoConstructor
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/AbstractStateIterator.java
{ "start": 1819, "end": 2283 }
class ____ to carry some already loaded elements and provide iterating * right on the task thread, and load following ones if needed (determined by {@link * #hasNextLoading()}) by creating **ANOTHER** iterating request. Thus, later it returns another * iterator instance, and we continue to apply the user iteration on that instance. The whole * elements will be iterated by recursive call of {@code #onNext()}. */ @SuppressWarnings("rawtypes") public abstract
is
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/TestSequenceFileSerialization.java
{ "start": 1350, "end": 2466 }
class ____ { private Configuration conf; private FileSystem fs; @BeforeEach public void setUp() throws Exception { conf = new Configuration(); conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization"); fs = FileSystem.getLocal(conf); } @AfterEach public void tearDown() throws Exception { fs.close(); } @Test public void testJavaSerialization() throws Exception { Path file = new Path(GenericTestUtils.getTempPath("testseqser.seq")); fs.delete(file, true); Writer writer = SequenceFile.createWriter(fs, conf, file, Long.class, String.class); writer.append(1L, "one"); writer.append(2L, "two"); writer.close(); Reader reader = new Reader(fs, file, conf); assertEquals(1L, reader.next((Object) null)); assertEquals("one", reader.getCurrentValue((Object) null)); assertEquals(2L, reader.next((Object) null)); assertEquals("two", reader.getCurrentValue((Object) null)); assertNull(reader.next((Object) null)); reader.close(); } }
TestSequenceFileSerialization
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/TypeExtractorTest.java
{ "start": 49362, "end": 49990 }
class ____ extends Mapper { private static final long serialVersionUID = 1L; @Override public String map(String value) throws Exception { return null; } } @SuppressWarnings({"rawtypes", "unchecked"}) @Test void testFunctionWithNoGenericSuperclass() { RichMapFunction<?, ?> function = new Mapper2(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes(function, (TypeInformation) Types.STRING); assertThat(ti.isBasicType()).isTrue(); assertThat(ti).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } public
Mapper2
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/BadFencingConfigurationException.java
{ "start": 1151, "end": 1443 }
class ____ extends IOException { private static final long serialVersionUID = 1L; public BadFencingConfigurationException(String msg) { super(msg); } public BadFencingConfigurationException(String msg, Throwable cause) { super(msg, cause); } }
BadFencingConfigurationException
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/LocalPhysicalPlanOptimizerTests.java
{ "start": 121391, "end": 121596 }
class ____ random full text function test cases. * Each test case should implement the queryBuilder and query methods to return the expected QueryBuilder and query string. */ private abstract
for
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/recovery/NMNullStateStoreService.java
{ "start": 2016, "end": 8598 }
class ____ extends NMStateStoreService { public NMNullStateStoreService() { super(NMNullStateStoreService.class.getName()); } @Override public boolean canRecover() { return false; } @Override public RecoveredApplicationsState loadApplicationsState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeApplication(ApplicationId appId, ContainerManagerApplicationProto p) throws IOException { } @Override public void removeApplication(ApplicationId appId) throws IOException { } @Override public RecoveryIterator<RecoveredContainerState> getContainerStateIterator() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeContainer(ContainerId containerId, int version, long startTime, StartContainerRequest startRequest) { } @Override public void storeContainerQueued(ContainerId containerId) throws IOException { } @Override public void storeContainerPaused(ContainerId containerId) throws IOException { } @Override public void removeContainerPaused(ContainerId containerId) throws IOException { } @Override public void storeContainerDiagnostics(ContainerId containerId, StringBuilder diagnostics) throws IOException { } @Override public void storeContainerLaunched(ContainerId containerId) throws IOException { } @Override public void storeContainerUpdateToken(ContainerId containerId, ContainerTokenIdentifier containerTokenIdentifier) throws IOException { } @Override public void storeContainerKilled(ContainerId containerId) throws IOException { } @Override public void storeContainerCompleted(ContainerId containerId, int exitCode) throws IOException { } @Override public void storeContainerRemainingRetryAttempts(ContainerId containerId, int remainingRetryAttempts) throws IOException { } @Override public void storeContainerRestartTimes(ContainerId containerId, List<Long> restartTimes) throws IOException { } @Override public void storeContainerWorkDir(ContainerId containerId, String workDir) throws IOException { } @Override public void storeContainerLogDir(ContainerId containerId, String logDir) throws IOException { } @Override public void removeContainer(ContainerId containerId) throws IOException { } @Override public RecoveredLocalizationState loadLocalizationState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void startResourceLocalization(String user, ApplicationId appId, LocalResourceProto proto, Path localPath) throws IOException { } @Override public void finishResourceLocalization(String user, ApplicationId appId, LocalizedResourceProto proto) throws IOException { } @Override public void removeLocalizedResource(String user, ApplicationId appId, Path localPath) throws IOException { } @Override public RecoveredDeletionServiceState loadDeletionServiceState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeDeletionTask(int taskId, DeletionServiceDeleteTaskProto taskProto) throws IOException { } @Override public void removeDeletionTask(int taskId) throws IOException { } @Override public RecoveredNMTokensState loadNMTokensState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeNMTokenCurrentMasterKey(MasterKey key) throws IOException { } @Override public void storeNMTokenPreviousMasterKey(MasterKey key) throws IOException { } @Override public void storeNMTokenApplicationMasterKey(ApplicationAttemptId attempt, MasterKey key) throws IOException { } @Override public void removeNMTokenApplicationMasterKey(ApplicationAttemptId attempt) throws IOException { } @Override public RecoveredContainerTokensState loadContainerTokensState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeContainerTokenCurrentMasterKey(MasterKey key) throws IOException { } @Override public void storeContainerTokenPreviousMasterKey(MasterKey key) throws IOException { } @Override public void storeContainerToken(ContainerId containerId, Long expirationTime) throws IOException { } @Override public void removeContainerToken(ContainerId containerId) throws IOException { } @Override public RecoveredLogDeleterState loadLogDeleterState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeLogDeleter(ApplicationId appId, LogDeleterProto proto) throws IOException { } @Override public void removeLogDeleter(ApplicationId appId) throws IOException { } @Override public RecoveredAMRMProxyState loadAMRMProxyState() throws IOException { throw new UnsupportedOperationException( "Recovery not supported by this state store"); } @Override public void storeAMRMProxyCurrentMasterKey(MasterKey key) throws IOException { } @Override public void storeAMRMProxyNextMasterKey(MasterKey key) throws IOException { } @Override public void storeAMRMProxyAppContextEntry(ApplicationAttemptId attempt, String key, byte[] data) throws IOException { } @Override public void removeAMRMProxyAppContextEntry(ApplicationAttemptId attempt, String key) throws IOException { } @Override public void removeAMRMProxyAppContext(ApplicationAttemptId attempt) throws IOException { } @Override public void storeAssignedResources(Container container, String resourceType, List<Serializable> assignedResources) throws IOException { updateContainerResourceMapping(container, resourceType, assignedResources); } @Override protected void initStorage(Configuration conf) throws IOException { } @Override protected void startStorage() throws IOException { } @Override protected void closeStorage() throws IOException { } }
NMNullStateStoreService
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/BlockingHandler.java
{ "start": 354, "end": 973 }
class ____ implements ServerRestHandler { private volatile Executor executor; private final Supplier<Executor> supplier; public BlockingHandler(Supplier<Executor> supplier) { this.supplier = supplier; } @Override public void handle(ResteasyReactiveRequestContext requestContext) throws Exception { if (BlockingOperationSupport.isBlockingAllowed()) { return; //already dispatched } if (executor == null) { executor = supplier.get(); } requestContext.suspend(); requestContext.resume(executor); } }
BlockingHandler
java
elastic__elasticsearch
libs/entitlement/src/test/java/org/elasticsearch/entitlement/runtime/policy/agent/TestAgent.java
{ "start": 543, "end": 592 }
class ____ testing agent entitlements. */ public
for
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/service/User.java
{ "start": 4540, "end": 5777 }
class ____ { private int id; private String name; private User owner; private Group parent; private List<Group> children; private Map<String, String> features; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public Group getParent() { return parent; } public void setParent(Group parent) { this.parent = parent; } public List<Group> getChildren() { return children; } public void setChildren(List<Group> children) { this.children = children; } public Map<String, String> getFeatures() { return features; } public void setFeatures(Map<String, String> features) { this.features = features; } } public static
Group
java
elastic__elasticsearch
x-pack/plugin/otel-data/src/main/java/org/elasticsearch/xpack/oteldata/otlp/OTLPMetricsRestAction.java
{ "start": 1013, "end": 2830 }
class ____ extends BaseRestHandler { @Override public String getName() { return "otlp_metrics_action"; } @Override public List<Route> routes() { return List.of(new Route(POST, "/_otlp/v1/metrics")); } @Override public boolean mediaTypesValid(RestRequest request) { return request.getXContentType() == null && request.getParsedContentType().mediaTypeWithoutParameters().equals("application/x-protobuf"); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { if (request.hasContent()) { var transportRequest = new OTLPMetricsTransportAction.MetricsRequest(request.content().retain()); return channel -> client.execute( OTLPMetricsTransportAction.TYPE, transportRequest, ActionListener.releaseBefore(request.content(), new RestResponseListener<>(channel) { @Override public RestResponse buildResponse(OTLPMetricsTransportAction.MetricsResponse r) { return new RestResponse(r.getStatus(), "application/x-protobuf", r.getResponse()); } }) ); } // If the server receives an empty request // (a request that does not carry any telemetry data) // the server SHOULD respond with success. // https://opentelemetry.io/docs/specs/otlp/#full-success-1 return channel -> channel.sendResponse( new RestResponse( RestStatus.OK, "application/x-protobuf", new BytesArray(ExportMetricsServiceResponse.newBuilder().build().toByteArray()) ) ); } }
OTLPMetricsRestAction
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/MonitoringServiceTests.java
{ "start": 6906, "end": 7566 }
class ____ extends CountingExporter { private final CountDownLatch latch; BlockingExporter(CountDownLatch latch) { this.latch = latch; } @Override public void export(Collection<MonitoringDoc> docs, ActionListener<Void> listener) { super.export(docs, listener.delegateFailureAndWrap((l, r) -> { try { latch.await(); l.onResponse(null); } catch (InterruptedException e) { l.onFailure(new ExportException("BlockingExporter failed", e)); } })); } } }
BlockingExporter
java
apache__camel
components/camel-jira/src/generated/java/org/apache/camel/component/jira/JiraComponentConfigurer.java
{ "start": 731, "end": 6801 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private org.apache.camel.component.jira.JiraConfiguration getOrCreateConfiguration(JiraComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.jira.JiraConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { JiraComponent target = (JiraComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": getOrCreateConfiguration(target).setAccessToken(property(camelContext, java.lang.String.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.jira.JiraConfiguration.class, value)); return true; case "consumerkey": case "consumerKey": getOrCreateConfiguration(target).setConsumerKey(property(camelContext, java.lang.String.class, value)); return true; case "delay": getOrCreateConfiguration(target).setDelay(property(camelContext, java.lang.Integer.class, value)); return true; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": target.setHealthCheckConsumerEnabled(property(camelContext, boolean.class, value)); return true; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": target.setHealthCheckProducerEnabled(property(camelContext, boolean.class, value)); return true; case "jiraurl": case "jiraUrl": getOrCreateConfiguration(target).setJiraUrl(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true; case "privatekey": case "privateKey": getOrCreateConfiguration(target).setPrivateKey(property(camelContext, java.lang.String.class, value)); return true; case "username": getOrCreateConfiguration(target).setUsername(property(camelContext, java.lang.String.class, value)); return true; case "verificationcode": case "verificationCode": getOrCreateConfiguration(target).setVerificationCode(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return java.lang.String.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "configuration": return org.apache.camel.component.jira.JiraConfiguration.class; case "consumerkey": case "consumerKey": return java.lang.String.class; case "delay": return java.lang.Integer.class; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return boolean.class; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return boolean.class; case "jiraurl": case "jiraUrl": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "password": return java.lang.String.class; case "privatekey": case "privateKey": return java.lang.String.class; case "username": return java.lang.String.class; case "verificationcode": case "verificationCode": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { JiraComponent target = (JiraComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return getOrCreateConfiguration(target).getAccessToken(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "configuration": return target.getConfiguration(); case "consumerkey": case "consumerKey": return getOrCreateConfiguration(target).getConsumerKey(); case "delay": return getOrCreateConfiguration(target).getDelay(); case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return target.isHealthCheckConsumerEnabled(); case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return target.isHealthCheckProducerEnabled(); case "jiraurl": case "jiraUrl": return getOrCreateConfiguration(target).getJiraUrl(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "password": return getOrCreateConfiguration(target).getPassword(); case "privatekey": case "privateKey": return getOrCreateConfiguration(target).getPrivateKey(); case "username": return getOrCreateConfiguration(target).getUsername(); case "verificationcode": case "verificationCode": return getOrCreateConfiguration(target).getVerificationCode(); default: return null; } } }
JiraComponentConfigurer
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/junit/jupiter/SoftAssertionsExtension_InjectionSanityChecking_Test.java
{ "start": 1468, "end": 1523 }
class ____ { @Test void myTest() {} }
TestBase
java
quarkusio__quarkus
extensions/mongodb-client/deployment/src/test/java/io/quarkus/mongodb/MongoWithReplicasTestBase.java
{ "start": 1364, "end": 7944 }
class ____ { private static final Logger LOGGER = Logger.getLogger(MongoWithReplicasTestBase.class); private static List<TransitionWalker.ReachedState<RunningMongodProcess>> startedServers = Collections.emptyList(); @BeforeAll public static void startMongoDatabase() { String uri = getConfiguredConnectionString(); // This switch allow testing against a running mongo database. if (uri == null) { startedServers = startReplicaSet(Version.Main.V7_0, 27018, "test001"); } else { LOGGER.infof("Using existing Mongo %s", uri); } } private static Net net(String hostName, int port) { return Net.builder() .from(Net.defaults()) .bindIp(hostName) .port(port) .build(); } private static List<TransitionWalker.ReachedState<RunningMongodProcess>> startReplicaSet( IFeatureAwareVersion version, int basePort, String replicaSet) { TransitionWalker.ReachedState<RunningMongodProcess> firstStarted = mongodWithPort(basePort, replicaSet).start(version); try { TransitionWalker.ReachedState<RunningMongodProcess> secondStarted = mongodWithPort(basePort + 1, replicaSet) .start(version); try { ServerAddress firstAddress = firstStarted.current().getServerAddress(); ServerAddress secondAddress = secondStarted.current().getServerAddress(); initializeReplicaSet(Arrays.asList(firstAddress, secondAddress), replicaSet); LOGGER.infof("ReplicaSet initialized with servers - firstServer: %s , secondServer: %s", firstAddress, secondAddress); return Arrays.asList(firstStarted, secondStarted); } catch (Exception ex) { LOGGER.error("Shutting down second Mongo Server."); secondStarted.close(); LOGGER.errorv(ex, "Error while initializing replicaSet. Error Message %s", ex.getMessage()); throw new RuntimeException("Error starting second server and initializing replicaset.", ex); } } catch (RuntimeException rx) { LOGGER.error("Shutting down first Mongo Server."); firstStarted.close(); throw rx; } } private static Mongod mongodWithPort(int port, String replicaSet) { return Mongod.instance().withNet(Start.to(Net.class).initializedWith(net("localhost", port))) .withProcessOutput(Start.to(ProcessOutput.class).initializedWith(ProcessOutput.silent())) .withMongodArguments(Start.to(MongodArguments.class).initializedWith( MongodArguments.defaults().withArgs(Map.of("--replSet", replicaSet)).withSyncDelay(10) .withUseSmallFiles(true).withUseNoJournal(false))) .withProcessConfig( Start.to(ProcessConfig.class) .initializedWith(ProcessConfig.defaults().withStopTimeoutInMillis(15_000))); } @AfterAll public static void stopMongoDatabase() { for (TransitionWalker.ReachedState<RunningMongodProcess> startedServer : startedServers) { try { startedServer.close(); } catch (RuntimeException rx) { LOGGER.error("startedServer.close", rx); } } } private static void initializeReplicaSet(final List<ServerAddress> mongodConfigList, String replicaSet) throws UnknownHostException { String arbitrerAddress = "mongodb://" + mongodConfigList.get(0).getHost() + ":" + mongodConfigList.get(0).getPort(); MongoClientSettings mo = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(arbitrerAddress)).build(); try (MongoClient mongo = MongoClients.create(mo)) { MongoDatabase mongoAdminDB = mongo.getDatabase("admin"); Document cr = mongoAdminDB.runCommand(new Document("isMaster", 1)); LOGGER.infof("isMaster: %s", cr); // Build replica set configuration settings Document rsConfiguration = buildReplicaSetConfiguration(mongodConfigList, replicaSet); LOGGER.infof("replSetSettings: %s", rsConfiguration); // Initialize replica set cr = mongoAdminDB.runCommand(new Document("replSetInitiate", rsConfiguration)); LOGGER.infof("replSetInitiate: %s", cr); // Check replica set status before to proceed Awaitility.await().atMost(ONE_MINUTE).with().pollInterval(ONE_SECOND).until(() -> { Document result = mongoAdminDB.runCommand(new Document("replSetGetStatus", 1)); LOGGER.infof("replSetGetStatus: %s", result); boolean replicaSetStatus = isReplicaSetStarted(result); LOGGER.infof("replicaSet Readiness Status: %s", replicaSetStatus); return replicaSetStatus; }); LOGGER.info("ReplicaSet is now ready with 2 cluster node."); } } private static Document buildReplicaSetConfiguration(List<ServerAddress> configList, String replicaSet) throws UnknownHostException { Document replicaSetSetting = new Document(); replicaSetSetting.append("_id", replicaSet); List<Document> members = new ArrayList<>(); int i = 0; for (ServerAddress mongoConfig : configList) { members.add(new Document().append("_id", i++).append("host", mongoConfig.getHost() + ":" + mongoConfig.getPort())); } replicaSetSetting.append("members", members); LOGGER.infof("ReplicaSet Configuration settings: %s", replicaSetSetting); return replicaSetSetting; } private static boolean isReplicaSetStarted(Document setting) { if (!setting.containsKey("members")) { return false; } @SuppressWarnings("unchecked") List<Document> members = setting.get("members", List.class); for (Document member : members) { LOGGER.infof("replica set member %s", member); int state = member.getInteger("state"); LOGGER.infof("state: %s", state); // 1 - PRIMARY, 2 - SECONDARY, 7 - ARBITER if (state != 1 && state != 2 && state != 7) { return false; } } return true; } }
MongoWithReplicasTestBase
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/DynamicRouterWithInterceptorTest.java
{ "start": 1673, "end": 4969 }
class ____ implements InterceptStrategy { private static final Logger LOGGER = LoggerFactory.getLogger(MyInterceptStrategy.class); private static int doneCount; @Override public Processor wrapProcessorInInterceptors( final CamelContext context, final NamedNode definition, final Processor target, final Processor nextTarget) { if (definition instanceof DynamicRouterDefinition<?>) { final DelegateAsyncProcessor delegateAsyncProcessor = new DelegateAsyncProcessor() { @Override public boolean process(final Exchange exchange, final AsyncCallback callback) { LOGGER.info("I'm doing someting"); return super.process(exchange, new AsyncCallback() { public void done(final boolean doneSync) { LOGGER.info("I'm done"); doneCount++; callback.done(doneSync); } }); } }; delegateAsyncProcessor.setProcessor(target); return delegateAsyncProcessor; } return new DelegateAsyncProcessor(target); } public void reset() { doneCount = 0; } } @Test public void testDynamicRouterOne() throws Exception { interceptStrategy.reset(); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(0); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); assertEquals(1, MyInterceptStrategy.doneCount, "Done method shall be called only once"); } @Test public void testDynamicRouterTwo() throws Exception { interceptStrategy.reset(); getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Bye World"); assertMockEndpointsSatisfied(); assertEquals(1, MyInterceptStrategy.doneCount, "Done method shall be called only once"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.getCamelContextExtension().addInterceptStrategy(interceptStrategy); from("direct:start").dynamicRouter(method(DynamicRouterWithInterceptorTest.class, "slip")).to("mock:result"); from("direct:foo").to("log:foo").to("mock:foo"); from("direct:bar").to("log:bar").to("mock:bar"); } }; } public String slip(@Body String body, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { return "direct:foo"; } else if ("Bye World".equals(body) && "direct://foo".equals(previous)) { return "direct:bar"; } // no more so return null return null; } }
MyInterceptStrategy
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/ExceptionTest.java
{ "start": 1120, "end": 5337 }
class ____ extends ContextTestSupport { @Test public void testExceptionWithoutHandler() throws Exception { MockEndpoint errorEndpoint = getMockEndpoint("mock:error"); MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); MockEndpoint exceptionEndpoint = getMockEndpoint("mock:exception"); errorEndpoint.expectedBodiesReceived("<exception/>"); exceptionEndpoint.expectedMessageCount(0); resultEndpoint.expectedMessageCount(0); // we don't expect any thrown exception here as there's no onException // clause defined for this test // so that the general purpose dead letter channel will come into the // play and then when all the attempts // to redelivery fails the exchange will be moved to "mock:error" and // then from the client point of // view the exchange is completed. template.sendBody("direct:start", "<body/>"); assertMockEndpointsSatisfied(); } @Test public void testExceptionWithHandler() throws Exception { MockEndpoint errorEndpoint = getMockEndpoint("mock:error"); MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); MockEndpoint exceptionEndpoint = getMockEndpoint("mock:exception"); errorEndpoint.expectedMessageCount(0); exceptionEndpoint.expectedBodiesReceived("<exception/>"); resultEndpoint.expectedMessageCount(0); assertThrows(Exception.class, () -> template.sendBody("direct:start", "<body/>"), "Should have thrown exception"); assertMockEndpointsSatisfied(); } @Test public void testExceptionWithLongHandler() throws Exception { MockEndpoint errorEndpoint = getMockEndpoint("mock:error"); MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); MockEndpoint exceptionEndpoint = getMockEndpoint("mock:exception"); errorEndpoint.expectedMessageCount(0); exceptionEndpoint.expectedBodiesReceived("<not-handled/>"); resultEndpoint.expectedMessageCount(0); assertThrows(Exception.class, () -> template.sendBody("direct:start", "<body/>"), "Should have thrown exception"); assertMockEndpointsSatisfied(); } @Test public void testLongRouteWithHandler() throws Exception { MockEndpoint errorEndpoint = getMockEndpoint("mock:error"); MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); MockEndpoint exceptionEndpoint = getMockEndpoint("mock:exception"); errorEndpoint.expectedMessageCount(0); exceptionEndpoint.expectedBodiesReceived("<exception/>"); resultEndpoint.expectedMessageCount(0); assertThrows(Exception.class, () -> template.sendBody("direct:start2", "<body/>"), "Should have thrown exception"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { final Processor exceptionThrower = exchange -> { exchange.getIn().setBody("<exception/>"); throw new IllegalArgumentException("Exception thrown intentionally."); }; return new RouteBuilder() { public void configure() { errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).maximumRedeliveries(3)); if (getName().endsWith("WithLongHandler")) { log.debug("Using long exception handler"); onException(IllegalArgumentException.class).setBody(constant("<not-handled/>")).to("mock:exception"); } else if (getName().endsWith("WithHandler")) { log.debug("Using exception handler"); onException(IllegalArgumentException.class).to("mock:exception"); } from("direct:start").process(exceptionThrower).to("mock:result"); from("direct:start2").to("direct:intermediate").to("mock:result"); from("direct:intermediate").setBody(constant("<some-value/>")).process(exceptionThrower).to("mock:result"); } }; } }
ExceptionTest
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestHeaderMapMethodArgumentResolver.java
{ "start": 1789, "end": 2944 }
class ____ extends HandlerMethodArgumentResolverSupport implements SyncHandlerMethodArgumentResolver { public RequestHeaderMapMethodArgumentResolver(ReactiveAdapterRegistry adapterRegistry) { super(adapterRegistry); } @Override public boolean supportsParameter(MethodParameter param) { return checkAnnotatedParamNoReactiveWrapper(param, RequestHeader.class, this::allParams); } private boolean allParams(RequestHeader annotation, Class<?> type) { return Map.class.isAssignableFrom(type) || HttpHeaders.class.isAssignableFrom(type); } @SuppressWarnings("removal") @Override public Object resolveArgumentValue( MethodParameter methodParameter, BindingContext context, ServerWebExchange exchange) { boolean isMultiValueMap = MultiValueMap.class.isAssignableFrom(methodParameter.getParameterType()); HttpHeaders headers = exchange.getRequest().getHeaders(); if (isMultiValueMap) { return headers.asMultiValueMap(); } boolean isHttpHeaders = HttpHeaders.class.isAssignableFrom(methodParameter.getParameterType()); return (isHttpHeaders ? headers : headers.toSingleValueMap()); } }
RequestHeaderMapMethodArgumentResolver
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCorrelateSplitRuleTest.java
{ "start": 2085, "end": 5001 }
class ____ extends TableTestBase { private final TableTestUtil util = streamTestUtil(TableConfig.getDefault()); @BeforeEach public void setup() { FlinkChainedProgram<StreamOptimizeContext> programs = new FlinkChainedProgram<>(); programs.addLast( "logical_rewrite", FlinkHepRuleSetProgramBuilder.<StreamOptimizeContext>newBuilder() .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE()) .setHepMatchOrder(HepMatchOrder.BOTTOM_UP) .add(FlinkStreamRuleSets.LOGICAL_REWRITE()) .build()); TableEnvironment tEnv = util.getTableEnv(); tEnv.executeSql( "CREATE TABLE MyTable (\n" + " a int,\n" + " b bigint,\n" + " c string,\n" + " d ARRAY<INT NOT NULL>,\n" + " e ROW<f ROW<h int, i double>, g string>\n" + ") WITH (\n" + " 'connector' = 'test-simple-table-source'\n" + ") ;"); util.addTemporarySystemFunction("func1", new Func1()); util.addTemporarySystemFunction("tableFunc", new RandomTableFunction()); util.addTemporarySystemFunction("scalar", new ScalarFunc()); util.addTemporarySystemFunction("asyncTableFunc", new AsyncFunc()); } @Test public void testCorrelateImmediate() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(tableFunc(func1(a)))"; util.verifyRelPlan(sqlQuery); } @Test public void testCorrelateIndirect() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(tableFunc(ABS(func1(a))))"; util.verifyRelPlan(sqlQuery); } @Test public void testCorrelateIndirectOtherWay() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(tableFunc(func1(ABS(a))))"; util.verifyRelPlan(sqlQuery); } @Test public void testCorrelateWithSystem() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(asyncTableFunc(ABS(a)))"; util.verifyRelPlan(sqlQuery); } @Test public void testCorrelateWithScalar() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(asyncTableFunc(scalar(a)))"; util.verifyRelPlan(sqlQuery); } @Test public void testCorrelateWithCast() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(asyncTableFunc(cast(cast(a as int) as int)))"; util.verifyRelPlan(sqlQuery); } @Test public void testCorrelateWithCompositeFieldAsInput() { String sqlQuery = "select * FROM MyTable, LATERAL TABLE(asyncTableFunc(e.f.h))"; util.verifyRelPlan(sqlQuery); } /** Test function. */ public static
AsyncCorrelateSplitRuleTest
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/syncjob/action/CheckInConnectorSyncJobAction.java
{ "start": 1246, "end": 1560 }
class ____ { public static final String NAME = "cluster:admin/xpack/connector/sync_job/check_in"; public static final ActionType<ConnectorUpdateActionResponse> INSTANCE = new ActionType<>(NAME); private CheckInConnectorSyncJobAction() {/* no instances */} public static
CheckInConnectorSyncJobAction
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/DocValueFormat.java
{ "start": 21711, "end": 24089 }
class ____ implements DocValueFormat { public static final DocValueFormat INSTANCE = new UnsignedLongShiftedDocValueFormat(); private UnsignedLongShiftedDocValueFormat() {} @Override public String getWriteableName() { return "unsigned_long_shifted"; } @Override public void writeTo(StreamOutput out) {} @Override public String toString() { return "unsigned_long_shifted"; } /** * Formats the unsigned long to the shifted long format */ @Override public long parseLong(String value, boolean roundUp, LongSupplier now) { long parsedValue = Long.parseUnsignedLong(value); // subtract 2^63 or 10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 // equivalent to flipping the first bit return parsedValue ^ MASK_2_63; } /** * Formats a raw docValue that is stored in the shifted long format to the unsigned long representation. */ @Override public Object format(long value) { // add 2^63 or 10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000, // equivalent to flipping the first bit long formattedValue = value ^ MASK_2_63; if (formattedValue >= 0) { return formattedValue; } else { return BigInteger.valueOf(formattedValue).and(BIGINTEGER_2_64_MINUS_ONE); } } @Override public Object formatSortValue(Object value) { if (value instanceof Long) { return format((Long) value); } return value; } /** * Double docValues of the unsigned_long field type are already in the formatted representation, * so we don't need to do anything here */ @Override public Double format(double value) { return value; } @Override public double parseDouble(String value, boolean roundUp, LongSupplier now) { return Double.parseDouble(value); } }; DocValueFormat TIME_SERIES_ID = new TimeSeriesIdDocValueFormat(); /** * DocValues format for time series id. */
UnsignedLongShiftedDocValueFormat
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/env/PropertyPlaceholderResolver.java
{ "start": 2689, "end": 3297 }
class ____ the type * @param <T> The type the value should be converted to * @return The resolved value * @throws ConfigurationException If multiple placeholders are found or * if the placeholder could not be converted to the requested type */ default @NonNull <T> T resolveRequiredPlaceholder(String str, Class<T> type) throws ConfigurationException { throw new ConfigurationException("Unsupported operation"); } /** * Resolves the optional value of a single placeholder. * * @param str The string containing the placeholder * @param type The
of
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/StaticGuardedByInstanceTest.java
{ "start": 3710, "end": 4198 }
class ____ { final Object lock = new Object(); static boolean init = false; void m() { synchronized (lock) { synchronized (Test.class) { init = true; } new Test() { { init = true; } }; } } } """) .doTest(); } }
Test
java
apache__camel
components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusProducer.java
{ "start": 1637, "end": 10164 }
class ____ extends DefaultProducer { private final Map<ServiceBusProducerOperationDefinition, Consumer<Exchange>> operationsToExecute = new EnumMap<>(ServiceBusProducerOperationDefinition.class); private ServiceBusSenderClient client; private ServiceBusConfigurationOptionsProxy configurationOptionsProxy; private ServiceBusSenderOperations serviceBusSenderOperations; { bind(ServiceBusProducerOperationDefinition.sendMessages, sendMessages()); bind(ServiceBusProducerOperationDefinition.scheduleMessages, scheduleMessages()); } public ServiceBusProducer(final Endpoint endpoint) { super(endpoint); } @Override protected void doInit() throws Exception { super.doInit(); ServiceBusUtils.validateConfiguration(getConfiguration(), false); configurationOptionsProxy = new ServiceBusConfigurationOptionsProxy(getConfiguration()); } @Override protected void doStart() throws Exception { super.doStart(); // create the senderClient client = getConfiguration().getSenderClient() != null ? getConfiguration().getSenderClient() : getEndpoint().getServiceBusClientFactory().createServiceBusSenderClient(getConfiguration()); // create the operations serviceBusSenderOperations = new ServiceBusSenderOperations(client); } @Override public void process(Exchange exchange) { final ServiceBusProducerOperationDefinition operation = configurationOptionsProxy.getServiceBusProducerOperationDefinition(exchange); final ServiceBusProducerOperationDefinition operationsToInvoke; // we put sendMessage operation as default in case no operation has been selected if (ObjectHelper.isEmpty(operation)) { operationsToInvoke = ServiceBusProducerOperationDefinition.sendMessages; } else { operationsToInvoke = operation; } final Consumer<Exchange> fnToInvoke = operationsToExecute.get(operationsToInvoke); if (fnToInvoke != null) { fnToInvoke.accept(exchange); } else { throw new RuntimeCamelException("Operation not supported. Value: " + operationsToInvoke); } } @Override protected void doStop() throws Exception { if (client != null) { // shutdown client client.close(); } super.doStop(); } @Override public ServiceBusEndpoint getEndpoint() { return (ServiceBusEndpoint) super.getEndpoint(); } public ServiceBusConfiguration getConfiguration() { return getEndpoint().getConfiguration(); } private void bind(ServiceBusProducerOperationDefinition operation, Consumer<Exchange> fn) { operationsToExecute.put(operation, fn); } @SuppressWarnings("unchecked") private Consumer<Exchange> sendMessages() { return (exchange) -> { final Object inputBody = exchange.getMessage().getBody(); Map<String, Object> applicationProperties = exchange.getMessage().getHeader(ServiceBusConstants.APPLICATION_PROPERTIES, Map.class); if (applicationProperties == null) { applicationProperties = new HashMap<>(); } propagateHeaders(exchange, applicationProperties); final String correlationId = exchange.getMessage().getHeader(ServiceBusConstants.CORRELATION_ID, String.class); final String sessionId = getConfiguration().getSessionId(); if (inputBody instanceof Iterable<?>) { serviceBusSenderOperations.sendMessages(convertBodyToList((Iterable<?>) inputBody), configurationOptionsProxy.getServiceBusTransactionContext(exchange), applicationProperties, correlationId, sessionId); } else { Object convertedBody = inputBody instanceof BinaryData ? inputBody : getConfiguration().isBinary() ? convertBodyToBinary(exchange) : exchange.getMessage().getBody(String.class); serviceBusSenderOperations.sendMessages(convertedBody, configurationOptionsProxy.getServiceBusTransactionContext(exchange), applicationProperties, correlationId, sessionId); } }; } @SuppressWarnings("unchecked") private Consumer<Exchange> scheduleMessages() { return (exchange) -> { final Object inputBody = exchange.getMessage().getBody(); Map<String, Object> applicationProperties = exchange.getMessage().getHeader(ServiceBusConstants.APPLICATION_PROPERTIES, Map.class); if (applicationProperties == null) { applicationProperties = new HashMap<>(); } propagateHeaders(exchange, applicationProperties); final String correlationId = exchange.getMessage().getHeader(ServiceBusConstants.CORRELATION_ID, String.class); final String sessionId = getConfiguration().getSessionId(); if (inputBody instanceof Iterable<?>) { serviceBusSenderOperations.scheduleMessages(convertBodyToList((Iterable<?>) inputBody), configurationOptionsProxy.getScheduledEnqueueTime(exchange), configurationOptionsProxy.getServiceBusTransactionContext(exchange), applicationProperties, correlationId, sessionId); } else { Object convertedBody = inputBody instanceof BinaryData ? inputBody : getConfiguration().isBinary() ? convertBodyToBinary(exchange) : exchange.getMessage().getBody(String.class); serviceBusSenderOperations.scheduleMessages(convertedBody, configurationOptionsProxy.getScheduledEnqueueTime(exchange), configurationOptionsProxy.getServiceBusTransactionContext(exchange), applicationProperties, correlationId, sessionId); } }; } private List<?> convertBodyToList(final Iterable<?> inputBody) { return StreamSupport.stream(inputBody.spliterator(), false).map(this::convertMessageBody).toList(); } private Object convertBodyToBinary(Exchange exchange) { Object body = exchange.getMessage().getBody(); if (body instanceof InputStream) { return BinaryData.fromStream((InputStream) body); } else if (body instanceof Path) { return BinaryData.fromFile((Path) body); } else if (body instanceof File) { return BinaryData.fromFile(((File) body).toPath()); } else { return BinaryData.fromBytes(exchange.getMessage().getBody(byte[].class)); } } private Object convertMessageBody(Object inputBody) { TypeConverter typeConverter = getEndpoint().getCamelContext().getTypeConverter(); if (inputBody instanceof BinaryData) { return inputBody; } else if (getConfiguration().isBinary()) { if (inputBody instanceof InputStream) { return BinaryData.fromStream((InputStream) inputBody); } else if (inputBody instanceof Path) { return BinaryData.fromFile((Path) inputBody); } else if (inputBody instanceof File) { return BinaryData.fromFile(((File) inputBody).toPath()); } else { return typeConverter.convertTo(byte[].class, inputBody); } } else { return typeConverter.convertTo(String.class, inputBody); } } private void propagateHeaders(Exchange exchange, Map<String, Object> applicationProperties) { final HeaderFilterStrategy headerFilterStrategy = getConfiguration().getHeaderFilterStrategy(); applicationProperties.putAll( exchange.getMessage().getHeaders().entrySet().stream() .filter(entry -> !headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } }
ServiceBusProducer
java
apache__camel
components/camel-jt400/src/main/java/org/apache/camel/component/jt400/Jt400PgmCallException.java
{ "start": 901, "end": 1190 }
class ____ extends RuntimeCamelException { private static final long serialVersionUID = 1112933724598115479L; public Jt400PgmCallException(String message) { super(message); } public Jt400PgmCallException(Exception e) { super(e); } }
Jt400PgmCallException
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/HostFileManager.java
{ "start": 2170, "end": 5916 }
class ____ extends HostConfigManager { private static final Logger LOG = LoggerFactory.getLogger(HostFileManager.class); private Configuration conf; private HostSet includes = new HostSet(); private HostSet excludes = new HostSet(); @Override public void setConf(Configuration conf) { this.conf = conf; } @Override public Configuration getConf() { return conf; } @Override public void refresh() throws IOException { refresh(conf.get(DFSConfigKeys.DFS_HOSTS, ""), conf.get(DFSConfigKeys.DFS_HOSTS_EXCLUDE, "")); } private static HostSet readFile(String type, String filename) throws IOException { HostSet res = new HostSet(); if (!filename.isEmpty()) { HashSet<String> entrySet = new HashSet<String>(); HostsFileReader.readFileToSet(type, filename, entrySet); for (String str : entrySet) { InetSocketAddress addr = parseEntry(type, filename, str); if (addr != null) { res.add(addr); } } } return res; } @VisibleForTesting static InetSocketAddress parseEntry(String type, String fn, String line) { try { URI uri = new URI("dummy", line, null, null, null); int port = uri.getPort() == -1 ? 0 : uri.getPort(); InetSocketAddress addr = new InetSocketAddress(uri.getHost(), port); if (addr.isUnresolved()) { LOG.warn(String.format("Failed to resolve address `%s` in `%s`. " + "Ignoring in the %s list.", line, fn, type)); return null; } return addr; } catch (URISyntaxException e) { LOG.warn(String.format("Failed to parse `%s` in `%s`. " + "Ignoring in " + "the %s list.", line, fn, type)); } return null; } @Override public synchronized HostSet getIncludes() { return includes; } @Override public synchronized HostSet getExcludes() { return excludes; } // If the includes list is empty, act as if everything is in the // includes list. @Override public synchronized boolean isIncluded(DatanodeID dn) { return includes.isEmpty() || includes.match(dn.getResolvedAddress()); } @Override public synchronized boolean isExcluded(DatanodeID dn) { return isExcluded(dn.getResolvedAddress()); } private boolean isExcluded(InetSocketAddress address) { return excludes.match(address); } @Override public synchronized String getUpgradeDomain(final DatanodeID dn) { // The include/exclude files based config doesn't support upgrade domain // config. return null; } @Override public long getMaintenanceExpirationTimeInMS(DatanodeID dn) { // The include/exclude files based config doesn't support maintenance mode. return 0; } /** * Read the includes and excludes lists from the named files. Any previous * includes and excludes lists are discarded. * @param includeFile the path to the new includes list * @param excludeFile the path to the new excludes list * @throws IOException thrown if there is a problem reading one of the files */ private void refresh(String includeFile, String excludeFile) throws IOException { HostSet newIncludes = readFile("included", includeFile); HostSet newExcludes = readFile("excluded", excludeFile); refresh(newIncludes, newExcludes); } /** * Set the includes and excludes lists by the new HostSet instances. The * old instances are discarded. * @param newIncludes the new includes list * @param newExcludes the new excludes list */ @VisibleForTesting void refresh(HostSet newIncludes, HostSet newExcludes) { synchronized (this) { includes = newIncludes; excludes = newExcludes; } } }
HostFileManager
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/authentication/BearerTokenAuthenticationFilter.java
{ "start": 4070, "end": 14896 }
class ____ extends OncePerRequestFilter { private final AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver; private final AuthenticationConverter authenticationConverter; private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private AuthenticationEntryPoint authenticationEntryPoint = new BearerTokenAuthenticationEntryPoint(); private AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationEntryPointFailureHandler( (request, response, exception) -> this.authenticationEntryPoint.commence(request, response, exception)); private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository(); /** * Construct a {@code BearerTokenAuthenticationFilter} using the provided parameter(s) * @param authenticationManagerResolver */ public BearerTokenAuthenticationFilter( AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver) { this(authenticationManagerResolver, new BearerTokenAuthenticationConverter()); } /** * Construct a {@code BearerTokenAuthenticationFilter} using the provided parameter(s) * @param authenticationManager */ public BearerTokenAuthenticationFilter(AuthenticationManager authenticationManager) { this(authenticationManager, new BearerTokenAuthenticationConverter()); } /** * Construct this filter using the provided parameters * @param authenticationManager the {@link AuthenticationManager} to use * @param authenticationConverter the {@link AuthenticationConverter} to use * @since 7.0 * @see JwtAuthenticationProvider * @see OpaqueTokenAuthenticationProvider * @see BearerTokenAuthenticationConverter */ public BearerTokenAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationManager, "authenticationManager cannot be null"); Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationManagerResolver = (authentication) -> authenticationManager; this.authenticationConverter = authenticationConverter; } /** * Construct this filter using the provided parameters * @param authenticationManagerResolver the {@link AuthenticationManagerResolver} to * use * @param authenticationConverter the {@link AuthenticationConverter} to use * @since 7.0 * @see JwtAuthenticationProvider * @see OpaqueTokenAuthenticationProvider * @see BearerTokenAuthenticationConverter */ public BearerTokenAuthenticationFilter( AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver, AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationManagerResolver, "authenticationManagerResolver cannot be null"); Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationManagerResolver = authenticationManagerResolver; this.authenticationConverter = authenticationConverter; } /** * Extract any * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> from the request and attempt an authentication. * @param request * @param response * @param filterChain * @throws ServletException * @throws IOException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Authentication authenticationRequest; try { authenticationRequest = this.authenticationConverter.convert(request); } catch (OAuth2AuthenticationException invalid) { this.logger.trace("Sending to authentication entry point since failed to resolve bearer token", invalid); this.authenticationEntryPoint.commence(request, response, invalid); return; } if (authenticationRequest == null) { this.logger.trace("Did not process request since did not find bearer token"); filterChain.doFilter(request, response); return; } try { AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request); Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest); if (isDPoPBoundAccessToken(authenticationResult)) { // Prevent downgraded usage of DPoP-bound access tokens, // by rejecting a DPoP-bound access token received as a bearer token. BearerTokenError error = BearerTokenErrors.invalidToken("Invalid bearer token"); throw new OAuth2AuthenticationException(error); } Authentication current = this.securityContextHolderStrategy.getContext().getAuthentication(); if (current != null && current.isAuthenticated() && declaresToBuilder(authenticationResult)) { authenticationResult = authenticationResult.toBuilder().authorities((a) -> { Set<String> newAuthorities = a.stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toUnmodifiableSet()); for (GrantedAuthority currentAuthority : current.getAuthorities()) { if (!newAuthorities.contains(currentAuthority.getAuthority())) { a.add(currentAuthority); } } }).build(); } SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authenticationResult); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authenticationResult)); } filterChain.doFilter(request, response); } catch (AuthenticationException failed) { this.securityContextHolderStrategy.clearContext(); this.logger.trace("Failed to process authentication request", failed); this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed); } } private static boolean declaresToBuilder(Authentication authentication) { for (Method method : authentication.getClass().getDeclaredMethods()) { if (method.getName().equals("toBuilder") && method.getParameterTypes().length == 0) { return true; } } return false; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the * {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Set the {@link BearerTokenResolver} to use. Defaults to * {@link DefaultBearerTokenResolver}. * @param bearerTokenResolver the {@code BearerTokenResolver} to use * @deprecated Please provide an {@link AuthenticationConverter} in the constructor * instead * @see BearerTokenAuthenticationConverter */ @Deprecated public void setBearerTokenResolver(BearerTokenResolver bearerTokenResolver) { Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null"); if (this.authenticationConverter instanceof BearerTokenAuthenticationConverter converter) { converter.setBearerTokenResolver(bearerTokenResolver); } else { throw new IllegalArgumentException( "You cannot both specify an AuthenticationConverter and a BearerTokenResolver."); } } /** * Set the {@link AuthenticationEntryPoint} to use. Defaults to * {@link BearerTokenAuthenticationEntryPoint}. * @param authenticationEntryPoint the {@code AuthenticationEntryPoint} to use */ public void setAuthenticationEntryPoint(final AuthenticationEntryPoint authenticationEntryPoint) { Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null"); this.authenticationEntryPoint = authenticationEntryPoint; } /** * Set the {@link AuthenticationFailureHandler} to use. Default implementation invokes * {@link AuthenticationEntryPoint}. * @param authenticationFailureHandler the {@code AuthenticationFailureHandler} to use * @since 5.2 */ public void setAuthenticationFailureHandler(final AuthenticationFailureHandler authenticationFailureHandler) { Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null"); this.authenticationFailureHandler = authenticationFailureHandler; } /** * Set the {@link AuthenticationDetailsSource} to use. Defaults to * {@link WebAuthenticationDetailsSource}. * @param authenticationDetailsSource the {@code AuthenticationDetailsSource} to use * @since 5.5 * @deprecated Please provide an {@link AuthenticationConverter} in the constructor * and set the {@link AuthenticationDetailsSource} there instead. For example, you can * use {@link BearerTokenAuthenticationConverter#setAuthenticationDetailsSource} * @see BearerTokenAuthenticationConverter */ @Deprecated public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "authenticationDetailsSource cannot be null"); if (this.authenticationConverter instanceof BearerTokenAuthenticationConverter converter) { converter.setAuthenticationDetailsSource(authenticationDetailsSource); } else { throw new IllegalArgumentException( "You cannot specify both an AuthenticationConverter and an AuthenticationDetailsSource"); } } private static boolean isDPoPBoundAccessToken(Authentication authentication) { if (!(authentication instanceof AbstractOAuth2TokenAuthenticationToken<?> accessTokenAuthentication)) { return false; } ClaimAccessor accessTokenClaims = accessTokenAuthentication::getTokenAttributes; String jwkThumbprintClaim = null; Map<String, Object> confirmationMethodClaim = accessTokenClaims.getClaimAsMap("cnf"); if (!CollectionUtils.isEmpty(confirmationMethodClaim) && confirmationMethodClaim.containsKey("jkt")) { jwkThumbprintClaim = (String) confirmationMethodClaim.get("jkt"); } return StringUtils.hasText(jwkThumbprintClaim); } }
BearerTokenAuthenticationFilter
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/innerclass/InnerClassTest.java
{ "start": 816, "end": 1823 }
class ____ { @WithClasses({Person.class, Dummy.class, Inner.class, Two.class}) @Test void test() { System.out.println( getMetaModelSourceAsString( InnerClassTest.class ) ); System.out.println( getMetaModelSourceAsString( Dummy.class ) ); System.out.println( getMetaModelSourceAsString( Person.class ) ); assertEquals( getMetaModelSourceAsString( Inner.class ), getMetaModelSourceAsString( Two.class ) ); assertMetamodelClassGeneratedFor( Inner.class ); assertMetamodelClassGeneratedFor( Two.class ); assertMetamodelClassGeneratedFor( Dummy.Inner.class ); assertMetamodelClassGeneratedFor( Person.class ); assertMetamodelClassGeneratedFor( Person.PersonId.class ); assertNoMetamodelClassGeneratedFor( Dummy.class ); assertMetamodelClassGeneratedFor( Dummy.DummyEmbeddable.class ); System.out.println( getMetaModelSourceAsString( Dummy.DummyEmbeddable.class ) ); } @Entity(name = "Inner") @NamedQuery(name = "allInner", query = "from Inner") public static
InnerClassTest
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/ConfigurationStrSubstitutor.java
{ "start": 1175, "end": 1811 }
class ____ extends StrSubstitutor { public ConfigurationStrSubstitutor() {} public ConfigurationStrSubstitutor(final Map<String, String> valueMap) { super(valueMap); } public ConfigurationStrSubstitutor(final Properties properties) { super(properties); } public ConfigurationStrSubstitutor(final StrLookup lookup) { super(lookup); } public ConfigurationStrSubstitutor(final StrSubstitutor other) { super(other); } @Override public String toString() { return "ConfigurationStrSubstitutor{" + super.toString() + "}"; } }
ConfigurationStrSubstitutor
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/records/ContainerFinishData.java
{ "start": 1357, "end": 2762 }
class ____ { @Public @Unstable public static ContainerFinishData newInstance(ContainerId containerId, long finishTime, String diagnosticsInfo, int containerExitCode, ContainerState containerState) { ContainerFinishData containerFD = Records.newRecord(ContainerFinishData.class); containerFD.setContainerId(containerId); containerFD.setFinishTime(finishTime); containerFD.setDiagnosticsInfo(diagnosticsInfo); containerFD.setContainerExitStatus(containerExitCode); containerFD.setContainerState(containerState); return containerFD; } @Public @Unstable public abstract ContainerId getContainerId(); @Public @Unstable public abstract void setContainerId(ContainerId containerId); @Public @Unstable public abstract long getFinishTime(); @Public @Unstable public abstract void setFinishTime(long finishTime); @Public @Unstable public abstract String getDiagnosticsInfo(); @Public @Unstable public abstract void setDiagnosticsInfo(String diagnosticsInfo); @Public @Unstable public abstract int getContainerExitStatus(); @Public @Unstable public abstract void setContainerExitStatus(int containerExitStatus); @Public @Unstable public abstract ContainerState getContainerState(); @Public @Unstable public abstract void setContainerState(ContainerState containerState); }
ContainerFinishData
java
spring-projects__spring-boot
module/spring-boot-micrometer-tracing/src/main/java/org/springframework/boot/micrometer/tracing/autoconfigure/prometheus/PrometheusExemplarsAutoConfiguration.java
{ "start": 2444, "end": 3437 }
class ____ implements SpanContext { private final SingletonSupplier<Tracer> tracer; LazyTracingSpanContext(ObjectProvider<Tracer> tracerProvider) { this.tracer = SingletonSupplier.of(tracerProvider::getObject); } @Override public @Nullable String getCurrentTraceId() { Span currentSpan = currentSpan(); return (currentSpan != null) ? currentSpan.context().traceId() : null; } @Override public @Nullable String getCurrentSpanId() { Span currentSpan = currentSpan(); return (currentSpan != null) ? currentSpan.context().spanId() : null; } @Override public boolean isCurrentSpanSampled() { Span currentSpan = currentSpan(); if (currentSpan == null) { return false; } Boolean sampled = currentSpan.context().sampled(); return sampled != null && sampled; } @Override public void markCurrentSpanAsExemplar() { } private @Nullable Span currentSpan() { return this.tracer.obtain().currentSpan(); } } }
LazyTracingSpanContext
java
alibaba__fastjson
src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectF2.java
{ "start": 92, "end": 556 }
class ____ { private int a; private int b; private List<Integer> c; private boolean d; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public List<Integer> getC() { return c; } public void setC(List<Integer> c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } }
ObjectF2
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JavaPluginAction.java
{ "start": 15800, "end": 15911 }
class ____ than a lambda due to * https://github.com/gradle/gradle/issues/5510. */ private static final
rather
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrarTests.java
{ "start": 16112, "end": 16586 }
class ____ { private @Nullable String name; @NestedConfigurationProperty private @Nullable SampleType sampleType; public @Nullable String getName() { return this.name; } public void setName(@Nullable String name) { this.name = name; } public @Nullable SampleType getSampleType() { return this.sampleType; } public void setSampleType(@Nullable SampleType sampleType) { this.sampleType = sampleType; } } public static
WithExternalNested
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KTableKTableInnerJoin.java
{ "start": 3041, "end": 6092 }
class ____ extends ContextualProcessor<K, Change<V1>, K, Change<VOut>> { private final KTableValueGetter<K, V2> valueGetter; private Sensor droppedRecordsSensor; KTableKTableJoinProcessor(final KTableValueGetter<K, V2> valueGetter) { this.valueGetter = valueGetter; } @Override public void init(final ProcessorContext<K, Change<VOut>> context) { super.init(context); droppedRecordsSensor = droppedRecordsSensor( Thread.currentThread().getName(), context.taskId().toString(), (StreamsMetricsImpl) context.metrics() ); valueGetter.init(context); } @Override public void process(final Record<K, Change<V1>> record) { // we do join iff keys are equal, thus, if key is null we cannot join and just ignore the record if (record.key() == null) { if (context().recordMetadata().isPresent()) { final RecordMetadata recordMetadata = context().recordMetadata().get(); LOG.warn( "Skipping record due to null key. " + "topic=[{}] partition=[{}] offset=[{}]", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset() ); } else { LOG.warn( "Skipping record due to null key. Topic, partition, and offset not known." ); } droppedRecordsSensor.record(); return; } // drop out-of-order records from versioned tables (cf. KIP-914) if (useVersionedSemantics && !record.value().isLatest) { LOG.info("Skipping out-of-order record from versioned table while performing table-table join."); droppedRecordsSensor.record(); return; } VOut newValue = null; final long resultTimestamp; VOut oldValue = null; final ValueAndTimestamp<V2> valueAndTimestampRight = valueGetter.get(record.key()); final V2 valueRight = getValueOrNull(valueAndTimestampRight); if (valueRight == null) { return; } resultTimestamp = Math.max(record.timestamp(), valueAndTimestampRight.timestamp()); if (record.value().newValue != null) { newValue = joiner.apply(record.value().newValue, valueRight); } if (sendOldValues && record.value().oldValue != null) { oldValue = joiner.apply(record.value().oldValue, valueRight); } context().forward(record.withValue(new Change<>(newValue, oldValue, record.value().isLatest)).withTimestamp(resultTimestamp)); } @Override public void close() { valueGetter.close(); } } private
KTableKTableJoinProcessor
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/checkpointing/StreamCheckpointNotifierITCase.java
{ "start": 7100, "end": 10509 }
class ____ extends RichSourceFunction<Long> implements ParallelSourceFunction<Long>, CheckpointListener, ListCheckpointed<Integer> { static final List<Long>[] COMPLETED_CHECKPOINTS = createCheckpointLists(PARALLELISM); static AtomicLong numPostFailureNotifications = new AtomicLong(); // operator behaviour private final long numElements; private final int notificationsToWaitFor; private int index; private int step; private volatile boolean notificationAlready; private volatile boolean isRunning = true; GeneratingSourceFunction(long numElements, int notificationsToWaitFor) { this.numElements = numElements; this.notificationsToWaitFor = notificationsToWaitFor; } @Override public void open(OpenContext openContext) throws IOException { step = getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(); // if index has been restored, it is not 0 any more if (index == 0) { index = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); } } @Override public void run(SourceContext<Long> ctx) throws Exception { final Object lockingObject = ctx.getCheckpointLock(); while (isRunning && index < numElements) { long result = index % 10; synchronized (lockingObject) { index += step; ctx.collect(result); } } // if the program goes fast and no notifications come through, we // wait until all tasks had a chance to see a notification while (isRunning && numPostFailureNotifications.get() < notificationsToWaitFor) { Thread.sleep(50); } } @Override public void cancel() { isRunning = false; } @Override public List<Integer> snapshotState(long checkpointId, long timestamp) throws Exception { return Collections.singletonList(this.index); } @Override public void restoreState(List<Integer> state) throws Exception { if (state.isEmpty() || state.size() > 1) { throw new RuntimeException( "Test failed due to unexpected recovered state size " + state.size()); } this.index = state.get(0); } @Override public void notifyCheckpointComplete(long checkpointId) { // record the ID of the completed checkpoint int partition = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); COMPLETED_CHECKPOINTS[partition].add(checkpointId); // if this is the first time we get a notification since the failure, // tell the source function if (OnceFailingReducer.hasFailed && !notificationAlready) { notificationAlready = true; GeneratingSourceFunction.numPostFailureNotifications.incrementAndGet(); } } @Override public void notifyCheckpointAborted(long checkpointId) {} } /** * Identity transform on Long values wrapping the output in a tuple. As an implementation for * the {@link CheckpointListener}
GeneratingSourceFunction
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/DefaultComponentTest.java
{ "start": 1687, "end": 12030 }
class ____ extends DefaultComponent { private MyComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) { return null; } } @Test public void testGetAndRemoveParameterEmptyMap() { Map<String, Object> parameters = new HashMap<>(); MyComponent my = new MyComponent(this.context); Integer value = my.getAndRemoveParameter(parameters, "size", Integer.class); assertNull(value); } @Test public void testGetAndRemoveParameterEmptyMapDefault() { Map<String, Object> parameters = new HashMap<>(); MyComponent my = new MyComponent(this.context); Integer value = my.getAndRemoveParameter(parameters, "size", Integer.class, 5); assertEquals(5, value.intValue()); } @Test public void testGetAndRemoveParameterEmptyMapDefaultIsNull() { Map<String, Object> parameters = new HashMap<>(); MyComponent my = new MyComponent(this.context); Integer value = my.getAndRemoveParameter(parameters, "size", Integer.class, null); assertNull(value); } @Test public void testGetAndRemoveParameterToInteger() { Map<String, Object> parameters = new HashMap<>(); parameters.put("size", 200); MyComponent my = new MyComponent(this.context); Integer value = my.getAndRemoveParameter(parameters, "size", Integer.class); assertEquals(200, value.intValue()); } @Test public void testGetAndRemoveParameterToIntegerDefault() { Map<String, Object> parameters = new HashMap<>(); parameters.put("size", 200); MyComponent my = new MyComponent(this.context); Integer value = my.getAndRemoveParameter(parameters, "level", Integer.class, 4); assertEquals(4, value.intValue()); } @Test public void testResolveAndRemoveReferenceParameter() { Map<String, Object> parameters = new HashMap<>(); parameters.put("date", "#beginning"); MyComponent my = new MyComponent(this.context); Date value = my.resolveAndRemoveReferenceParameter(parameters, "date", Date.class); assertEquals(new Date(0), value); // usage of leading # is optional parameters.put("date", "beginning"); value = my.resolveAndRemoveReferenceParameter(parameters, "date", Date.class); assertEquals(new Date(0), value); } @Test public void testResolveAndRemoveReferenceParameterWithConversion() { Map<String, Object> parameters = new HashMap<>(); parameters.put("number", "#numeric"); MyComponent my = new MyComponent(this.context); Integer value = my.resolveAndRemoveReferenceParameter(parameters, "number", Integer.class); assertEquals(12345, value.intValue()); } @Test public void testResolveAndRemoveReferenceParameterWithFailedConversion() { Map<String, Object> parameters = new HashMap<>(); parameters.put("number", "#non-numeric"); MyComponent my = new MyComponent(this.context); TypeConversionException ex = assertThrows(TypeConversionException.class, () -> my.resolveAndRemoveReferenceParameter(parameters, "number", Integer.class), "Should have thrown an exception"); assertEquals( "Error during type conversion from type: java.lang.String " + "to the required type: java.lang.Integer " + "with value abc due to java.lang.NumberFormatException: For input string: \"abc\"", ex.getMessage()); } @Test public void testResolveAndRemoveReferenceParameterNotInRegistry() { Map<String, Object> parameters = new HashMap<>(); parameters.put("date", "#somewhen"); MyComponent my = new MyComponent(this.context); NoSuchBeanException e = assertThrows(NoSuchBeanException.class, () -> my.resolveAndRemoveReferenceParameter(parameters, "date", Date.class), "returned without finding object in registry"); assertEquals("No bean could be found in the registry for: somewhen of type: java.util.Date", e.getMessage()); } @Test public void testResolveAndRemoveReferenceParameterNotInMapDefault() { Map<String, Object> parameters = new HashMap<>(); parameters.put("date", "#beginning"); MyComponent my = new MyComponent(this.context); Date value = my.resolveAndRemoveReferenceParameter(parameters, "wrong", Date.class, new Date(1)); assertEquals(new Date(1), value); } @Test public void testResolveAndRemoveReferenceParameterNotInMapNull() { Map<String, Object> parameters = new HashMap<>(); parameters.put("date", "#beginning"); MyComponent my = new MyComponent(this.context); Date value = my.resolveAndRemoveReferenceParameter(parameters, "wrong", Date.class); assertNull(value); } @Test public void testResolveAndRemoveReferenceListParameterElement() { Map<String, Object> parameters = new HashMap<>(); parameters.put("dates", "#bean1"); MyComponent my = new MyComponent(this.context); List<Date> values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(1, values.size()); assertEquals(new Date(10), values.get(0)); } @Test public void testResolveAndRemoveReferenceListParameterListComma() { Map<String, Object> parameters = new HashMap<>(); parameters.put("dates", "#bean1,#bean2"); MyComponent my = new MyComponent(this.context); List<Date> values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(2, values.size()); assertEquals(new Date(10), values.get(0)); assertEquals(new Date(11), values.get(1)); // usage of leading # is optional parameters.put("dates", "bean1,bean2"); values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(2, values.size()); assertEquals(new Date(10), values.get(0)); assertEquals(new Date(11), values.get(1)); } @Test public void testResolveAndRemoveReferenceListParameterListCommaTrim() { Map<String, Object> parameters = new HashMap<>(); parameters.put("dates", " #bean1 , #bean2 "); MyComponent my = new MyComponent(this.context); List<Date> values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(2, values.size()); assertEquals(new Date(10), values.get(0)); assertEquals(new Date(11), values.get(1)); // usage of leading # is optional parameters.put("dates", " bean1 , bean2 "); values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(2, values.size()); assertEquals(new Date(10), values.get(0)); assertEquals(new Date(11), values.get(1)); } @Test public void testResolveAndRemoveReferenceListParameterListBean() { Map<String, Object> parameters = new HashMap<>(); parameters.put("dates", "#listBean"); MyComponent my = new MyComponent(this.context); List<Date> values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(2, values.size()); assertEquals(new Date(10), values.get(0)); assertEquals(new Date(11), values.get(1)); // usage of leading # is optional parameters.put("dates", "#listBean"); values = my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class); assertEquals(2, values.size()); assertEquals(new Date(10), values.get(0)); assertEquals(new Date(11), values.get(1)); } @Test public void testResolveAndRemoveReferenceListParameterInvalidBean() { Map<String, Object> parameters = new HashMap<>(); parameters.put("dates", "#bean1,#bean3"); MyComponent my = new MyComponent(this.context); NoSuchBeanException e = assertThrows(NoSuchBeanException.class, () -> my.resolveAndRemoveReferenceListParameter(parameters, "dates", Date.class), "returned without finding object in registry"); assertEquals("No bean could be found in the registry for: bean3 of type: java.util.Date", e.getMessage()); } @Test public void testGetAndRemoveOrResolveReferenceParameter() { Map<String, Object> parameters = new HashMap<>(); parameters.put("size", 123); parameters.put("date", "#bean1"); MyComponent my = new MyComponent(this.context); Integer value = my.getAndRemoveOrResolveReferenceParameter(parameters, "size", Integer.class); assertNotNull(value); assertEquals(123, value.intValue()); assertEquals(1, parameters.size()); Date bean1 = my.getAndRemoveOrResolveReferenceParameter(parameters, "date", Date.class); assertNotNull(bean1); assertEquals(new Date(10), bean1); assertEquals(0, parameters.size()); Integer age = my.getAndRemoveOrResolveReferenceParameter(parameters, "age", Integer.class, 7); assertNotNull(age); assertEquals(7, age.intValue()); } @Test public void testContextShouldBeSet() { MyComponent my = new MyComponent(null); IllegalArgumentException e = assertThrows(IllegalArgumentException.class, my::start, "Should have thrown a IllegalArgumentException"); assertEquals("camelContext must be specified", e.getMessage()); } @Override protected Registry createCamelRegistry() throws Exception { Date bean1 = new Date(10); Date bean2 = new Date(11); Registry registry = super.createCamelRegistry(); registry.bind("beginning", new Date(0)); registry.bind("bean1", bean1); registry.bind("bean2", bean2); registry.bind("listBean", Arrays.asList(bean1, bean2)); registry.bind("numeric", "12345"); registry.bind("non-numeric", "abc"); return registry; } }
MyComponent
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/PrimitiveTypeClaimApplicationScopedBeanTest.java
{ "start": 274, "end": 940 }
class ____ { @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClass(PrimitiveTypeClaimApplicationScopedEndpoint.class)) .assertException(t -> { assertTrue(t.getMessage().startsWith( "java.lang.String type can not be used to represent JWT claims in @Singleton or @ApplicationScoped beans, make the bean @RequestScoped" + " or wrap this type with")); }); @Test public void test() { Assertions.fail(); } }
PrimitiveTypeClaimApplicationScopedBeanTest
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/authentication/ForwardAuthenticationFailureHandlerTests.java
{ "start": 1262, "end": 2187 }
class ____ { @Test public void invalidForwardUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new ForwardAuthenticationFailureHandler("aaa")); } @Test public void emptyForwardUrl() { assertThatIllegalArgumentException().isThrownBy(() -> new ForwardAuthenticationFailureHandler("")); } @Test public void responseIsForwarded() throws Exception { ForwardAuthenticationFailureHandler fafh = new ForwardAuthenticationFailureHandler("/forwardUrl"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); AuthenticationException e = mock(AuthenticationException.class); fafh.onAuthenticationFailure(request, response, e); assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl"); assertThat(request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isEqualTo(e); } }
ForwardAuthenticationFailureHandlerTests
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/util/DisabledOnHibernateCondition.java
{ "start": 1788, "end": 2950 }
class ____ { private static final Pattern PATTERN = Pattern.compile("(\\d+)+"); private final int[] components; private VersionMatcher(int[] components) { this.components = components; } /** * Parse the given version string into a {@link VersionMatcher}. * * @param version * @return */ public static VersionMatcher parse(String version) { Matcher matcher = PATTERN.matcher(version); List<Integer> ints = new ArrayList<>(); while (matcher.find()) { ints.add(Integer.parseInt(matcher.group())); } return new VersionMatcher(ints.stream().mapToInt(value -> value).toArray()); } /** * Match the given version against another VersionMatcher. This matcher's version spec controls the expected length. * If the other version is shorter, then the match returns {@code false}. * * @param version * @return */ public boolean matches(VersionMatcher version) { for (int i = 0; i < components.length; i++) { if (version.components.length <= i) { return false; } if (components[i] != version.components[i]) { return false; } } return true; } } }
VersionMatcher
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DifferentNameButSameTest.java
{ "start": 2283, "end": 2516 }
interface ____ { A.B test(); B test2(); } """) .addOutputLines( "Test.java", """ package pkg; import pkg.A.B;
Test
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/event/EventUtilsTest.java
{ "start": 1821, "end": 2033 }
class ____ { private int count; public void eventOccurred() { count++; } public int getCount() { return count; } } public static
EventCounter
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/ClusterResourceListener.java
{ "start": 3824, "end": 4072 }
interface ____ { /** * A callback method that a user can implement to get updates for {@link ClusterResource}. * @param clusterResource cluster metadata */ void onUpdate(ClusterResource clusterResource); }
ClusterResourceListener
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java
{ "start": 1798, "end": 3688 }
class ____ implements MetricsSource { @Deprecated @Metric("Duration for a continuous scheduling run") MutableRate continuousSchedulingRun; @Metric("Duration to handle a node update") MutableRate nodeUpdateCall; @Metric("Duration for a update thread run") MutableRate updateThreadRun; private static final MetricsInfo RECORD_INFO = info("FSOpDurations", "Durations of FairScheduler calls or thread-runs"); private final MetricsRegistry registry; private boolean isExtended = false; private static final FSOpDurations INSTANCE = new FSOpDurations(); public static FSOpDurations getInstance(boolean isExtended) { INSTANCE.setExtended(isExtended); return INSTANCE; } private FSOpDurations() { registry = new MetricsRegistry(RECORD_INFO); registry.tag(RECORD_INFO, "FSOpDurations"); MetricsSystem ms = DefaultMetricsSystem.instance(); if (ms != null) { ms.register(RECORD_INFO.name(), RECORD_INFO.description(), this); } } private synchronized void setExtended(boolean isExtended) { if (isExtended == INSTANCE.isExtended) return; continuousSchedulingRun.setExtended(isExtended); nodeUpdateCall.setExtended(isExtended); updateThreadRun.setExtended(isExtended); INSTANCE.isExtended = isExtended; } @Override public synchronized void getMetrics(MetricsCollector collector, boolean all) { registry.snapshot(collector.addRecord(registry.info()), all); } @Deprecated public void addContinuousSchedulingRunDuration(long value) { continuousSchedulingRun.add(value); } public void addNodeUpdateDuration(long value) { nodeUpdateCall.add(value); } public void addUpdateThreadRunDuration(long value) { updateThreadRun.add(value); } @VisibleForTesting public boolean hasUpdateThreadRunChanged() { return updateThreadRun.changed(); } }
FSOpDurations
java
resilience4j__resilience4j
resilience4j-framework-common/src/main/java/io/github/resilience4j/common/bulkhead/configuration/CommonThreadPoolBulkheadConfigurationProperties.java
{ "start": 9381, "end": 9802 }
class ____ of {@link ContextPropagator} * * @param contextPropagators subclass of {@link ContextPropagator} * @return return builder instance back for fluent set up */ public InstanceProperties setContextPropagators(Class<? extends ContextPropagator>... contextPropagators) { this.contextPropagators = contextPropagators; return this; } } }
type
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/CheckForbiddenApisTask.java
{ "start": 20313, "end": 21057 }
class ____ implements Logger { private final org.gradle.api.logging.Logger delegate; GradleForbiddenApiLogger(org.gradle.api.logging.Logger delegate) { this.delegate = delegate; } @Override public void error(String msg) { delegate.error(msg); } @Override public void warn(String msg) { delegate.warn(msg); } @Override public void info(String msg) { delegate.info(msg); } @Override public void debug(String msg) { delegate.debug(msg); } }; }
GradleForbiddenApiLogger
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/datatypes/FileName.java
{ "start": 1458, "end": 1854 }
class ____ implements AnonymizableDataType<String> { private final String fileName; private String anonymizedFileName; private static final String PREV_DIR = ".."; private static final String[] KNOWN_SUFFIXES = new String[] {".xml", ".jar", ".txt", ".tar", ".zip", ".json", ".gzip", ".lzo"}; /** * A composite state for filename. */ public static
FileName
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/serializer/Serializer.java
{ "start": 1016, "end": 1903 }
interface ____<T> { /** * Write an object of type T to the given OutputStream. * <p>Note: Implementations should not close the given OutputStream * (or any decorators of that OutputStream) but rather leave this up * to the caller. * @param object the object to serialize * @param outputStream the output stream * @throws IOException in case of errors writing to the stream */ void serialize(T object, OutputStream outputStream) throws IOException; /** * Turn an object of type T into a serialized byte array. * @param object the object to serialize * @return the resulting byte array * @throws IOException in case of serialization failure * @since 5.2.7 */ default byte[] serializeToByteArray(T object) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); serialize(object, out); return out.toByteArray(); } }
Serializer
java
google__guava
android/guava-tests/test/com/google/common/io/FileBackedOutputStreamAndroidIncompatibleTest.java
{ "start": 1024, "end": 1753 }
class ____ extends IoTestCase { public void testFinalizeDeletesFile() throws Exception { byte[] data = newPreFilledByteArray(100); FileBackedOutputStream out = new FileBackedOutputStream(0, true); write(out, data, 0, 100, true); File file = out.getFile(); assertEquals(100, file.length()); assertTrue(file.exists()); out.close(); // Make sure that finalize deletes the file out = null; // times out and throws RuntimeException on failure GcFinalization.awaitDone( new GcFinalization.FinalizationPredicate() { @Override public boolean isDone() { return !file.exists(); } }); } }
FileBackedOutputStreamAndroidIncompatibleTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/functions/sink/legacy/RichSinkFunction.java
{ "start": 1217, "end": 1266 }
interface ____. */ @Internal public abstract
instead
java
apache__spark
common/kvstore/src/main/java/org/apache/spark/util/kvstore/RocksDBIterator.java
{ "start": 1111, "end": 7358 }
class ____<T> implements KVStoreIterator<T> { private static final Cleaner CLEANER = Cleaner.create(); private final RocksDB db; private final boolean ascending; private final RocksIterator it; private final Class<T> type; private final RocksDBTypeInfo ti; private final RocksDBTypeInfo.Index index; private final byte[] indexKeyPrefix; private final byte[] end; private final long max; private final Cleaner.Cleanable cleanable; private final RocksDBIterator.ResourceCleaner resourceCleaner; private boolean checkedNext; private byte[] next; private boolean closed; private long count; RocksDBIterator(Class<T> type, RocksDB db, KVStoreView<T> params) throws Exception { this.db = db; this.ascending = params.ascending; this.it = db.db().newIterator(); this.type = type; this.ti = db.getTypeInfo(type); this.index = ti.index(params.index); this.max = params.max; this.resourceCleaner = new RocksDBIterator.ResourceCleaner(it, db); this.cleanable = CLEANER.register(this, resourceCleaner); JavaUtils.checkArgument(!index.isChild() || params.parent != null, "Cannot iterate over child index %s without parent value.", params.index); byte[] parent = index.isChild() ? index.parent().childPrefix(params.parent) : null; this.indexKeyPrefix = index.keyPrefix(parent); byte[] firstKey; if (params.first != null) { if (ascending) { firstKey = index.start(parent, params.first); } else { firstKey = index.end(parent, params.first); } } else if (ascending) { firstKey = index.keyPrefix(parent); } else { firstKey = index.end(parent); } it.seek(firstKey); byte[] end = null; if (ascending) { if (params.last != null) { end = index.end(parent, params.last); } else { end = index.end(parent); } } else { if (params.last != null) { end = index.start(parent, params.last); } if(!it.isValid()) { throw new NoSuchElementException(); } if (compare(it.key(), indexKeyPrefix) > 0) { it.prev(); } } this.end = end; if (params.skip > 0) { skip(params.skip); } } @Override public boolean hasNext() { if (!checkedNext && !closed) { next = loadNext(); checkedNext = true; } if (!closed && next == null) { try { close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } } return next != null; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } checkedNext = false; try { T ret; if (index == null || index.isCopy()) { ret = db.serializer.deserialize(next, type); } else { byte[] key = ti.buildKey(false, ti.naturalIndex().keyPrefix(null), next); ret = db.get(key, type); } next = null; return ret; } catch (Exception e) { if (e instanceof RuntimeException re) throw re; throw new RuntimeException(e); } } @Override public List<T> next(int max) { List<T> list = new ArrayList<>(max); while (hasNext() && list.size() < max) { list.add(next()); } return list; } @Override public boolean skip(long n) { if(closed) return false; long skipped = 0; while (skipped < n) { if (next != null) { checkedNext = false; next = null; skipped++; continue; } if (!it.isValid()) { checkedNext = true; return false; } if (!isEndMarker(it.key())) { skipped++; } if (ascending) { it.next(); } else { it.prev(); } } return hasNext(); } @Override public synchronized void close() throws IOException { db.notifyIteratorClosed(it); if (!closed) { try { it.close(); } finally { closed = true; next = null; cancelResourceClean(); } } } /** * Prevent ResourceCleaner from actually releasing resources after close it. */ private void cancelResourceClean() { this.resourceCleaner.setStartedToFalse(); this.cleanable.clean(); } @VisibleForTesting ResourceCleaner getResourceCleaner() { return resourceCleaner; } RocksIterator internalIterator() { return it; } private byte[] loadNext() { if (count >= max) { return null; } while (it.isValid()) { Map.Entry<byte[], byte[]> nextEntry = new AbstractMap.SimpleEntry<>(it.key(), it.value()); byte[] nextKey = nextEntry.getKey(); // Next key is not part of the index, stop. if (!startsWith(nextKey, indexKeyPrefix)) { return null; } // If the next key is an end marker, then skip it. if (isEndMarker(nextKey)) { if (ascending) { it.next(); } else { it.prev(); } continue; } // If there's a known end key and iteration has gone past it, stop. if (end != null) { int comp = compare(nextKey, end) * (ascending ? 1 : -1); if (comp > 0) { return null; } } count++; if (ascending) { it.next(); } else { it.prev(); } // Next element is part of the iteration, return it. return nextEntry.getValue(); } return null; } @VisibleForTesting static boolean startsWith(byte[] key, byte[] prefix) { if (key.length < prefix.length) { return false; } for (int i = 0; i < prefix.length; i++) { if (key[i] != prefix[i]) { return false; } } return true; } private boolean isEndMarker(byte[] key) { return (key.length > 2 && key[key.length - 2] == RocksDBTypeInfo.KEY_SEPARATOR && key[key.length - 1] == RocksDBTypeInfo.END_MARKER[0]); } static int compare(byte[] a, byte[] b) { int diff = 0; int minLen = Math.min(a.length, b.length); for (int i = 0; i < minLen; i++) { diff += (a[i] - b[i]); if (diff != 0) { return diff; } } return a.length - b.length; } static
RocksDBIterator
java
assertj__assertj-core
assertj-guava/src/main/java/org/assertj/guava/api/MultisetAssert.java
{ "start": 1461, "end": 5983 }
class ____<T> extends AbstractIterableAssert<MultisetAssert<T>, Multiset<? extends T>, T, ObjectAssert<T>> { protected MultisetAssert(Multiset<? extends T> actual) { super(actual, MultisetAssert.class); } /** * Verifies the actual {@link Multiset} contains the given value <b>exactly</b> the given number of times. * <p> * Example : * * <pre><code class='java'> Multiset&lt;String&gt; actual = HashMultiset.create(); * actual.add("shoes", 2); * * // assertion succeeds * assertThat(actual).contains(2, "shoes"); * * // assertions fail * assertThat(actual).contains(1, "shoes"); * assertThat(actual).contains(3, "shoes");</code></pre> * * @param expectedCount the exact number of times the given value should appear in the set * @param expected the value which to expect * * @return this {@link MultisetAssert} for fluent chaining * * @throws AssertionError if the actual {@link Multiset} is null * @throws AssertionError if the actual {@link Multiset} contains the given value a number of times different to the given count */ public MultisetAssert<T> contains(int expectedCount, T expected) { isNotNull(); checkArgument(expectedCount >= 0, "The expected count should not be negative."); int actualCount = actual.count(expected); if (actualCount != expectedCount) { throw assertionError(shouldContainTimes(actual, expected, expectedCount, actualCount)); } return myself; } /** * Verifies the actual {@link Multiset} contains the given value <b>at least</b> the given number of times. * <p> * Example : * * <pre><code class='java'> Multiset&lt;String&gt; actual = HashMultiset.create(); * actual.add("shoes", 2); * * // assertions succeed * assertThat(actual).containsAtLeast(1, "shoes"); * assertThat(actual).containsAtLeast(2, "shoes"); * * // assertion fails * assertThat(actual).containsAtLeast(3, "shoes");</code></pre> * * @param minimumCount the minimum number of times the given value should appear in the set * @param expected the value which to expect * * @return this {@link MultisetAssert} for fluent chaining * * @throws AssertionError if the actual {@link Multiset} is null * @throws AssertionError if the actual {@link Multiset} contains the given value fewer times than the given count */ public MultisetAssert<T> containsAtLeast(int minimumCount, T expected) { isNotNull(); checkArgument(minimumCount >= 0, "The minimum count should not be negative."); int actualCount = actual.count(expected); if (actualCount < minimumCount) { throw assertionError(shouldContainAtLeastTimes(actual, expected, minimumCount, actualCount)); } return myself; } /** * Verifies the actual {@link Multiset} contains the given value <b>at most</b> the given number of times. * <p> * Example : * * <pre><code class='java'> Multiset&lt;String&gt; actual = HashMultiset.create(); * actual.add("shoes", 2); * * // assertions succeed * assertThat(actual).containsAtMost(3, "shoes"); * assertThat(actual).containsAtMost(2, "shoes"); * * // assertion fails * assertThat(actual).containsAtMost(1, "shoes");</code></pre> * * * @param maximumCount the maximum number of times the given value should appear in the set * * @param expected the value which to expect * @return this {@link MultisetAssert} for fluent chaining * * @throws AssertionError if the actual {@link Multiset} is null * @throws AssertionError if the actual {@link Multiset} contains the given value more times than the given count */ public MultisetAssert<T> containsAtMost(int maximumCount, T expected) { isNotNull(); checkArgument(maximumCount >= 0, "The maximum count should not be negative."); int actualCount = actual.count(expected); if (actualCount > maximumCount) { throw assertionError(shouldContainAtMostTimes(actual, expected, maximumCount, actualCount)); } return myself; } @Override protected ObjectAssert<T> toAssert(T value, String description) { return null; } @Override protected MultisetAssert<T> newAbstractIterableAssert(Iterable<? extends T> iterable) { // actual may not have been a HashMultiset but there is no easy elegant to build the same Multiset subtype. Multiset<T> filtered = HashMultiset.create(); iterable.forEach(filtered::add); return new MultisetAssert<>(filtered); } }
MultisetAssert
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/internal/Exceptions.java
{ "start": 522, "end": 3068 }
class ____ { /** * Unwrap the exception if the given {@link Throwable} is a {@link ExecutionException} or {@link CompletionException}. * * @param t the root cause * @return the unwrapped {@link Throwable#getCause() cause} or the actual {@link Throwable}. */ public static Throwable unwrap(Throwable t) { if (t instanceof ExecutionException || t instanceof CompletionException) { return t.getCause(); } return t; } /** * Prepare an unchecked {@link RuntimeException} that will bubble upstream if thrown by an operator. * * @param t the root cause * @return an unchecked exception that should choose bubbling up over error callback path. */ public static RuntimeException bubble(Throwable t) { Throwable throwableToUse = unwrap(t); if (throwableToUse instanceof TimeoutException) { return new RedisCommandTimeoutException(throwableToUse); } if (throwableToUse instanceof InterruptedException) { Thread.currentThread().interrupt(); return new RedisCommandInterruptedException(throwableToUse); } if (throwableToUse instanceof RedisCommandExecutionException) { return ExceptionFactory.createExecutionException(throwableToUse.getMessage(), throwableToUse); } if (throwableToUse instanceof RedisException) { return (RedisException) throwableToUse; } if (throwableToUse instanceof RuntimeException) { return (RuntimeException) throwableToUse; } return new RedisException(throwableToUse); } /** * Prepare an unchecked {@link RuntimeException} that will bubble upstream for synchronization usage (i.e. on calling * {@link Future#get()}). * * @param t the root cause * @return an unchecked exception that should choose bubbling up over error callback path. */ public static RuntimeException fromSynchronization(Throwable t) { Throwable throwableToUse = unwrap(t); if (throwableToUse instanceof RedisCommandTimeoutException) { return new RedisCommandTimeoutException(throwableToUse); } if (throwableToUse instanceof RedisCommandExecutionException) { return bubble(throwableToUse); } if (throwableToUse instanceof RuntimeException) { return new RedisException(throwableToUse); } return bubble(throwableToUse); } }
Exceptions
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/webapp/dao/CounterGroupInfo.java
{ "start": 1263, "end": 1887 }
class ____ { protected String counterGroupName; @XmlElement(name = "counter") protected ArrayList<CounterInfo> counter; public CounterGroupInfo() { } public CounterGroupInfo(String name, CounterGroup group, CounterGroup mg, CounterGroup rg) { this.counterGroupName = name; this.counter = new ArrayList<CounterInfo>(); for (Counter c : group) { Counter mc = mg == null ? null : mg.findCounter(c.getName()); Counter rc = rg == null ? null : rg.findCounter(c.getName()); CounterInfo cinfo = new CounterInfo(c, mc, rc); this.counter.add(cinfo); } } }
CounterGroupInfo
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/FirstDoubleByTimestampGroupingAggregatorFunction.java
{ "start": 1185, "end": 16057 }
class ____ implements GroupingAggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("timestamps", ElementType.LONG), new IntermediateStateDesc("values", ElementType.DOUBLE) ); private final FirstDoubleByTimestampAggregator.GroupingState state; private final List<Integer> channels; private final DriverContext driverContext; public FirstDoubleByTimestampGroupingAggregatorFunction(List<Integer> channels, FirstDoubleByTimestampAggregator.GroupingState state, DriverContext driverContext) { this.channels = channels; this.state = state; this.driverContext = driverContext; } public static FirstDoubleByTimestampGroupingAggregatorFunction create(List<Integer> channels, DriverContext driverContext) { return new FirstDoubleByTimestampGroupingAggregatorFunction(channels, FirstDoubleByTimestampAggregator.initGrouping(driverContext), driverContext); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public GroupingAggregatorFunction.AddInput prepareProcessRawInputPage(SeenGroupIds seenGroupIds, Page page) { DoubleBlock valueBlock = page.getBlock(channels.get(0)); LongBlock timestampBlock = page.getBlock(channels.get(1)); DoubleVector valueVector = valueBlock.asVector(); if (valueVector == null) { maybeEnableGroupIdTracking(seenGroupIds, valueBlock, timestampBlock); return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void close() { } }; } LongVector timestampVector = timestampBlock.asVector(); if (timestampVector == null) { maybeEnableGroupIdTracking(seenGroupIds, valueBlock, timestampBlock); return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, valueBlock, timestampBlock); } @Override public void close() { } }; } return new GroupingAggregatorFunction.AddInput() { @Override public void add(int positionOffset, IntArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueVector, timestampVector); } @Override public void add(int positionOffset, IntBigArrayBlock groupIds) { addRawInput(positionOffset, groupIds, valueVector, timestampVector); } @Override public void add(int positionOffset, IntVector groupIds) { addRawInput(positionOffset, groupIds, valueVector, timestampVector); } @Override public void close() { } }; } private void addRawInput(int positionOffset, IntArrayBlock groups, DoubleBlock valueBlock, LongBlock timestampBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; if (valueBlock.isNull(valuesPosition)) { continue; } if (timestampBlock.isNull(valuesPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valueStart = valueBlock.getFirstValueIndex(valuesPosition); int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition); for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { double valueValue = valueBlock.getDouble(valueOffset); int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition); int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition); for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) { long timestampValue = timestampBlock.getLong(timestampOffset); FirstDoubleByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } } } private void addRawInput(int positionOffset, IntArrayBlock groups, DoubleVector valueVector, LongVector timestampVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); double valueValue = valueVector.getDouble(valuesPosition); long timestampValue = timestampVector.getLong(valuesPosition); FirstDoubleByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } @Override public void addIntermediateInput(int positionOffset, IntArrayBlock groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongBlock timestamps = (LongBlock) timestampsUncast; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } DoubleBlock values = (DoubleBlock) valuesUncast; assert timestamps.getPositionCount() == values.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valuesPosition = groupPosition + positionOffset; FirstDoubleByTimestampAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition); } } } private void addRawInput(int positionOffset, IntBigArrayBlock groups, DoubleBlock valueBlock, LongBlock timestampBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; if (valueBlock.isNull(valuesPosition)) { continue; } if (timestampBlock.isNull(valuesPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valueStart = valueBlock.getFirstValueIndex(valuesPosition); int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition); for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { double valueValue = valueBlock.getDouble(valueOffset); int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition); int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition); for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) { long timestampValue = timestampBlock.getLong(timestampOffset); FirstDoubleByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } } } private void addRawInput(int positionOffset, IntBigArrayBlock groups, DoubleVector valueVector, LongVector timestampVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int valuesPosition = groupPosition + positionOffset; int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); double valueValue = valueVector.getDouble(valuesPosition); long timestampValue = timestampVector.getLong(valuesPosition); FirstDoubleByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } @Override public void addIntermediateInput(int positionOffset, IntBigArrayBlock groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongBlock timestamps = (LongBlock) timestampsUncast; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } DoubleBlock values = (DoubleBlock) valuesUncast; assert timestamps.getPositionCount() == values.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { if (groups.isNull(groupPosition)) { continue; } int groupStart = groups.getFirstValueIndex(groupPosition); int groupEnd = groupStart + groups.getValueCount(groupPosition); for (int g = groupStart; g < groupEnd; g++) { int groupId = groups.getInt(g); int valuesPosition = groupPosition + positionOffset; FirstDoubleByTimestampAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition); } } } private void addRawInput(int positionOffset, IntVector groups, DoubleBlock valueBlock, LongBlock timestampBlock) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int valuesPosition = groupPosition + positionOffset; if (valueBlock.isNull(valuesPosition)) { continue; } if (timestampBlock.isNull(valuesPosition)) { continue; } int groupId = groups.getInt(groupPosition); int valueStart = valueBlock.getFirstValueIndex(valuesPosition); int valueEnd = valueStart + valueBlock.getValueCount(valuesPosition); for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { double valueValue = valueBlock.getDouble(valueOffset); int timestampStart = timestampBlock.getFirstValueIndex(valuesPosition); int timestampEnd = timestampStart + timestampBlock.getValueCount(valuesPosition); for (int timestampOffset = timestampStart; timestampOffset < timestampEnd; timestampOffset++) { long timestampValue = timestampBlock.getLong(timestampOffset); FirstDoubleByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } } } private void addRawInput(int positionOffset, IntVector groups, DoubleVector valueVector, LongVector timestampVector) { for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int valuesPosition = groupPosition + positionOffset; int groupId = groups.getInt(groupPosition); double valueValue = valueVector.getDouble(valuesPosition); long timestampValue = timestampVector.getLong(valuesPosition); FirstDoubleByTimestampAggregator.combine(state, groupId, valueValue, timestampValue); } } @Override public void addIntermediateInput(int positionOffset, IntVector groups, Page page) { state.enableGroupIdTracking(new SeenGroupIds.Empty()); assert channels.size() == intermediateBlockCount(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongBlock timestamps = (LongBlock) timestampsUncast; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } DoubleBlock values = (DoubleBlock) valuesUncast; assert timestamps.getPositionCount() == values.getPositionCount(); for (int groupPosition = 0; groupPosition < groups.getPositionCount(); groupPosition++) { int groupId = groups.getInt(groupPosition); int valuesPosition = groupPosition + positionOffset; FirstDoubleByTimestampAggregator.combineIntermediate(state, groupId, timestamps, values, valuesPosition); } } private void maybeEnableGroupIdTracking(SeenGroupIds seenGroupIds, DoubleBlock valueBlock, LongBlock timestampBlock) { if (valueBlock.mayHaveNulls()) { state.enableGroupIdTracking(seenGroupIds); } if (timestampBlock.mayHaveNulls()) { state.enableGroupIdTracking(seenGroupIds); } } @Override public void selectedMayContainUnseenGroups(SeenGroupIds seenGroupIds) { state.enableGroupIdTracking(seenGroupIds); } @Override public void evaluateIntermediate(Block[] blocks, int offset, IntVector selected) { state.toIntermediate(blocks, offset, selected, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, IntVector selected, GroupingAggregatorEvaluationContext ctx) { blocks[offset] = FirstDoubleByTimestampAggregator.evaluateFinal(state, selected, ctx); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
FirstDoubleByTimestampGroupingAggregatorFunction
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java
{ "start": 12471, "end": 12872 }
class ____ extends ShortParam { /** * Parameter name. */ public static final String NAME = HttpFSFileSystem.UNMASKED_PERMISSION_PARAM; /** * Constructor. */ public UnmaskedPermissionParam() { super(NAME, (short) -1, 8); } } /** * Class for AclPermission parameter. */ @InterfaceAudience.Private public static
UnmaskedPermissionParam
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/foreignkeyjoin/ForeignKeyExtractor.java
{ "start": 1201, "end": 1641 }
interface ____ two factory methods: * <ul> * <li>{@link #fromFunction(Function)} - when the foreign key depends only on the value</li> * <li>{@link #fromBiFunction(BiFunction)} - when the foreign key depends on both key and value</li> * </ul> * * @param <KLeft> Type of primary table's key * @param <VLeft> Type of primary table's value * @param <KRight> Type of the foreign key to extract */ @FunctionalInterface public
provides
java
quarkusio__quarkus
integration-tests/test-extension/extension-that-defines-junit-test-extensions/deployment/src/main/java/io/quarkiverse/acme/deployment/ExtensionProcessor.java
{ "start": 254, "end": 608 }
class ____ { private static final String FEATURE = "extension-that-has-capability-for-tests"; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(FEATURE); } @BuildStep BytecodeTransformerBuildItem reworkClassLoadingOfParameterizedSourceTest2() { // Ideally, we would not hardcode
ExtensionProcessor
java
elastic__elasticsearch
modules/transport-netty4/src/main/java/org/elasticsearch/http/netty4/internal/HttpHeadersAuthenticatorUtils.java
{ "start": 1495, "end": 5923 }
class ____ HttpHeadersAuthenticatorUtils() {} /** * Supplies a netty {@code ChannelInboundHandler} that runs the provided {@param validator} on the HTTP request headers. * The HTTP headers of the to-be-authenticated {@link HttpRequest} must be wrapped by the special * {@link HttpHeadersWithAuthenticationContext}, see {@link #wrapAsMessageWithAuthenticationContext(HttpMessage)}. */ public static Netty4HttpHeaderValidator getValidatorInboundHandler(HttpValidator validator, ThreadContext threadContext) { return new Netty4HttpHeaderValidator((httpRequest, channel, listener) -> { // make sure authentication only runs on properly wrapped "authenticable" headers implementation if (httpRequest.headers() instanceof HttpHeadersWithAuthenticationContext httpHeadersWithAuthenticationContext) { validator.validate(httpRequest, channel, ActionListener.wrap(aVoid -> { httpHeadersWithAuthenticationContext.setAuthenticationContext(threadContext.newStoredContext()); // a successful authentication needs to signal to the {@link Netty4HttpHeaderValidator} to resume // forwarding the request beyond the headers part listener.onResponse(null); }, e -> listener.onFailure(new HttpHeadersValidationException(e)))); } else { // cannot authenticate the request because it's not wrapped correctly, see {@link #wrapAsMessageWithAuthenticationContext} listener.onFailure(new HttpHeadersValidationException(new IllegalStateException("Cannot authenticate unwrapped requests"))); } }, threadContext); } /** * Given a {@link DefaultHttpRequest} argument, this returns a new {@link DefaultHttpRequest} instance that's identical to the * passed-in one, but the headers of the latter can be authenticated, in the sense that the channel handlers returned by * {@link #getValidatorInboundHandler(HttpValidator, ThreadContext)} can use this to convey the authentication result context. */ public static HttpMessage wrapAsMessageWithAuthenticationContext(HttpMessage newlyDecodedMessage) { assert newlyDecodedMessage instanceof HttpRequest; DefaultHttpRequest httpRequest = (DefaultHttpRequest) newlyDecodedMessage; HttpHeadersWithAuthenticationContext httpHeadersWithAuthenticationContext = new HttpHeadersWithAuthenticationContext( newlyDecodedMessage.headers() ); return new DefaultHttpRequest( httpRequest.protocolVersion(), httpRequest.method(), httpRequest.uri(), httpHeadersWithAuthenticationContext ); } /** * Returns the authentication thread context for the {@param request}. */ public static ThreadContext.StoredContext extractAuthenticationContext(org.elasticsearch.http.HttpRequest request) { HttpHeadersWithAuthenticationContext authenticatedHeaders = unwrapAuthenticatedHeaders(request); return authenticatedHeaders != null ? authenticatedHeaders.authenticationContextSetOnce.get() : null; } /** * Translates the netty request internal type to a {@link HttpPreRequest} instance that code outside the network plugin has access to. */ public static HttpPreRequest asHttpPreRequest(HttpRequest request) { return new HttpPreRequest() { @Override public RestRequest.Method method() { return translateRequestMethod(request.method()); } @Override public String uri() { return request.uri(); } @Override public Map<String, List<String>> getHeaders() { return getHttpHeadersAsMap(request.headers()); } }; } private static HttpHeadersWithAuthenticationContext unwrapAuthenticatedHeaders(org.elasticsearch.http.HttpRequest request) { if (request instanceof Netty4HttpRequest == false) { return null; } if (((Netty4HttpRequest) request).getNettyRequest().headers() instanceof HttpHeadersWithAuthenticationContext == false) { return null; } return (HttpHeadersWithAuthenticationContext) (((Netty4HttpRequest) request).getNettyRequest().headers()); } }
private
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/analytics/AnalyticsFeatureSetUsage.java
{ "start": 749, "end": 2322 }
class ____ extends XPackFeatureUsage { private final AnalyticsStatsAction.Response response; public AnalyticsFeatureSetUsage(boolean available, boolean enabled, AnalyticsStatsAction.Response response) { super(XPackField.ANALYTICS, available, enabled); this.response = response; } public AnalyticsFeatureSetUsage(StreamInput input) throws IOException { super(input); this.response = new AnalyticsStatsAction.Response(input); } @Override public int hashCode() { return Objects.hash(available, enabled, response); } @Override protected void innerXContent(XContentBuilder builder, Params params) throws IOException { super.innerXContent(builder, params); if (response != null) { response.toXContent(builder, params); } } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.zero(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); response.writeTo(out); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AnalyticsFeatureSetUsage other = (AnalyticsFeatureSetUsage) obj; return Objects.equals(available, other.available) && Objects.equals(enabled, other.enabled) && Objects.equals(response, other.response); } }
AnalyticsFeatureSetUsage
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/jaxb/mapping/spi/JaxbMappedSuperclass.java
{ "start": 181, "end": 310 }
interface ____ extends JaxbEntityOrMappedSuperclass { @Override JaxbAttributesContainerImpl getAttributes(); }
JaxbMappedSuperclass
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldHaveTime.java
{ "start": 885, "end": 1516 }
class ____ extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldHaveTime}</code>. * @param actual the actual value in the failed assertion. * @param expectedTimestamp the expected timestamp. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldHaveTime(Date actual, long expectedTimestamp) { return new ShouldHaveTime(actual, expectedTimestamp); } private ShouldHaveTime(Date actual, long expectedTimestamp) { super("%nExpecting%n %s%nto have time:%n %s%nbut was:%n %s", actual, expectedTimestamp, actual.getTime()); } }
ShouldHaveTime
java
apache__camel
components/camel-crypto-pgp/src/test/java/org/apache/camel/converter/crypto/PGPDataFormatTest.java
{ "start": 3365, "end": 41622 }
class ____ extends AbstractPGPDataFormatTest { private static final String PUB_KEY_RING_SUBKEYS_FILE_NAME = "org/apache/camel/component/crypto/pubringSubKeys.gpg"; private static final String SEC_KEY_RING_FILE_NAME = "org/apache/camel/component/crypto/secring.gpg"; private static final String PUB_KEY_RING_FILE_NAME = "org/apache/camel/component/crypto/pubring.gpg"; PGPDataFormat encryptor = new PGPDataFormat(); PGPDataFormat decryptor = new PGPDataFormat(); @BeforeEach public void setUpEncryptorAndDecryptor() { // the following keyring contains a primary key with KeyFlag "Certify" and a subkey for signing and a subkey for encryption encryptor.setKeyFileName(PUB_KEY_RING_SUBKEYS_FILE_NAME); encryptor.setSignatureKeyFileName("org/apache/camel/component/crypto/secringSubKeys.gpg"); encryptor.setSignaturePassword("Abcd1234"); encryptor.setKeyUserid("keyflag"); encryptor.setSignatureKeyUserid("keyflag"); encryptor.setIntegrity(false); encryptor.setFileName("fileNameABC"); // the following keyring contains a primary key with KeyFlag "Certify" and a subkey for signing and a subkey for encryption decryptor.setKeyFileName("org/apache/camel/component/crypto/secringSubKeys.gpg"); decryptor.setSignatureKeyFileName(PUB_KEY_RING_SUBKEYS_FILE_NAME); decryptor.setPassword("Abcd1234"); decryptor.setSignatureKeyUserid("keyflag"); } protected String getKeyFileName() { return PUB_KEY_RING_FILE_NAME; } protected String getKeyFileNameSec() { return SEC_KEY_RING_FILE_NAME; } protected String getKeyUserId() { return "sdude@nowhere.net"; } protected List<String> getKeyUserIds() { List<String> userids = new ArrayList<>(2); userids.add("second"); userids.add(getKeyUserId()); return userids; } protected List<String> getSignatureKeyUserIds() { List<String> userids = new ArrayList<>(2); userids.add("second"); userids.add(getKeyUserId()); return userids; } protected String getKeyPassword() { return "sdude"; } protected String getProvider() { return "BC"; } protected int getAlgorithm() { return SymmetricKeyAlgorithmTags.TRIPLE_DES; } protected int getHashAlgorithm() { return HashAlgorithmTags.SHA256; } protected int getCompressionAlgorithm() { return CompressionAlgorithmTags.BZIP2; } @Test void testEncryption() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:inline")); } @Test void testEncryption2() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:inline2")); } @Test void testEncryptionArmor() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:inline-armor")); } @Test void testEncryptionSigned() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:inline-sign")); } @Test void testEncryptionKeyRingByteArray() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:key-ring-byte-array")); } @Test void testEncryptionSignedKeyRingByteArray() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:sign-key-ring-byte-array")); } @Test void testSeveralSignerKeys() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:several-signer-keys")); } @Test void testOneUserIdWithSeveralKeys() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:one-userid-several-keys")); } @Test void testKeyAccess() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:key_access")); } @Test void testVerifyExceptionNoPublicKeyFoundCorrespondingToSignatureUserIds() throws Exception { setupExpectations(context, 1, "mock:encrypted"); MockEndpoint exception = setupExpectations(context, 1, "mock:exception"); String payload = "Hi Alice, Be careful Eve is listening, signed Bob"; Map<String, Object> headers = getHeaders(); template.sendBodyAndHeaders("direct:verify_exception_sig_userids", payload, headers); MockEndpoint.assertIsSatisfied(context); checkThrownException(exception, IllegalArgumentException.class, null, "No public key found for the key ID(s)"); } @Test void testVerifyExceptionNoPassphraseSpecifiedForSignatureKeyUserId() throws Exception { MockEndpoint exception = setupExpectations(context, 1, "mock:exception"); String payload = "Hi Alice, Be careful Eve is listening, signed Bob"; Map<String, Object> headers = new HashMap<>(); // add signature user id which does not have a passphrase headers.put(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID, "userIDWithNoPassphrase"); // the following entry is necessary for the dynamic test headers.put(PGPKeyAccessDataFormat.KEY_USERID, "second"); template.sendBodyAndHeaders("direct:several-signer-keys", payload, headers); MockEndpoint.assertIsSatisfied(context); checkThrownException(exception, IllegalArgumentException.class, null, "No passphrase specified for signature key user ID"); } /** * You get three keys with the UserId "keyflag", a primary key and its two sub-keys. The sub-key with KeyFlag * {@link KeyFlags#SIGN_DATA} should be used for signing and the sub-key with KeyFlag {@link KeyFlags#ENCRYPT_COMMS} * or {@link KeyFlags#ENCRYPT_COMMS} or {@link KeyFlags#ENCRYPT_STORAGE} should be used for decryption. * * @throws Exception */ @Test void testKeyFlagSelectsCorrectKey() throws Exception { MockEndpoint mockKeyFlag = getMockEndpoint("mock:encrypted_keyflag"); mockKeyFlag.setExpectedMessageCount(1); template.sendBody("direct:keyflag", "Test Message"); MockEndpoint.assertIsSatisfied(context); List<Exchange> exchanges = mockKeyFlag.getExchanges(); assertEquals(1, exchanges.size()); Exchange exchange = exchanges.get(0); Message inMess = exchange.getIn(); assertNotNull(inMess); // must contain exactly one encryption key and one signature assertEquals(1, inMess.getHeader(PGPKeyAccessDataFormat.NUMBER_OF_ENCRYPTION_KEYS)); assertEquals(1, inMess.getHeader(PGPKeyAccessDataFormat.NUMBER_OF_SIGNING_KEYS)); } /** * You get three keys with the UserId "keyflag", a primary key and its two sub-keys. The sub-key with KeyFlag * {@link KeyFlags#SIGN_DATA} should be used for signing and the sub-key with KeyFlag {@link KeyFlags#ENCRYPT_COMMS} * or {@link KeyFlags#ENCRYPT_COMMS} or {@link KeyFlags#ENCRYPT_STORAGE} should be used for decryption. * <p> * Tests also the decryption and verifying part with the subkeys. * * @throws Exception */ @Test void testDecryptVerifyWithSubkey() throws Exception { // do not use doRoundTripEncryptionTests("direct:subkey"); because otherwise you get an error in the dynamic test String payload = "Test Message"; MockEndpoint mockSubkey = getMockEndpoint("mock:unencrypted"); mockSubkey.expectedBodiesReceived(payload); template.sendBody("direct:subkey", payload); MockEndpoint.assertIsSatisfied(context); } @Test void testEmptyBody() throws Exception { String payload = ""; MockEndpoint mockSubkey = getMockEndpoint("mock:unencrypted"); mockSubkey.expectedBodiesReceived(payload); template.sendBody("direct:subkey", payload); MockEndpoint.assertIsSatisfied(context); } @Test void testExceptionDecryptorIncorrectInputFormatNoPGPMessage() throws Exception { String payload = "Not Correct Format"; MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkeyUnmarshal", payload); MockEndpoint.assertIsSatisfied(context); checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format."); } @Test void testExceptionDecryptorIncorrectInputFormatPGPSignedData() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); createSignature(bos); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkeyUnmarshal", bos.toByteArray()); MockEndpoint.assertIsSatisfied(context); checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format."); } @Test void testEncryptSignWithoutCompressedDataPacket() { assertDoesNotThrow(() -> doRoundTripEncryptionTests("direct:encrypt-sign-without-compressed-data-packet")); // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // //// createEncryptedNonCompressedData(bos, PUB_KEY_RING_SUBKEYS_FILE_NAME); // // MockEndpoint mock = getMockEndpoint("mock:exception"); // mock.expectedMessageCount(1); // template.sendBody("direct:encrypt-sign-without-compressed-data-packet", bos.toByteArray()); // assertMockEndpointsSatisfied(); // // //checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format."); } @Test void testExceptionDecryptorNoKeyFound() throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); createEncryptedNonCompressedData(bos, PUB_KEY_RING_FILE_NAME); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkeyUnmarshal", bos.toByteArray()); MockEndpoint.assertIsSatisfied(context); checkThrownException(mock, PGPException.class, null, "PGP message is encrypted with a key which could not be found in the Secret Keyring"); } void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception { PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath))); OutputStream encOut = encGen.open(bos, new byte[512]); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]); try { litOut.write("Test Message Without Compression".getBytes("UTF-8")); litOut.flush(); } finally { IOHelper.close(litOut); IOHelper.close(encOut, bos); } } private void createSignature(OutputStream out) throws Exception { PGPSecretKey pgpSec = readSecretKey(); PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(getProvider()).build( "sdude".toCharArray())); PGPSignatureGenerator sGen = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder( pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1).setProvider(getProvider())); sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey); BCPGOutputStream bOut = new BCPGOutputStream(out); InputStream fIn = new ByteArrayInputStream("Test Signature".getBytes("UTF-8")); int ch; while ((ch = fIn.read()) >= 0) { sGen.update((byte) ch); } fIn.close(); sGen.generate().encode(bOut); } static PGPSecretKey readSecretKey() throws Exception { InputStream input = new ByteArrayInputStream(getSecKeyRing()); PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("Can't find signing key in key ring."); } static PGPPublicKey readPublicKey(String keyringPath) throws Exception { InputStream input = new ByteArrayInputStream(getKeyRing(keyringPath)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); } @Test void testExceptionDecryptorIncorrectInputFormatSymmetricEncryptedData() throws Exception { byte[] payload = "Not Correct Format".getBytes("UTF-8"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5) .setSecureRandom(new SecureRandom()).setProvider(getProvider())); encGen.addMethod(new JcePBEKeyEncryptionMethodGenerator("pw".toCharArray())); OutputStream encOut = encGen.open(bos, new byte[1024]); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP); OutputStream comOut = new BufferedOutputStream(comData.open(encOut)); PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator(); OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[1024]); litOut.write(payload); litOut.flush(); litOut.close(); comOut.close(); encOut.close(); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkeyUnmarshal", bos.toByteArray()); MockEndpoint.assertIsSatisfied(context); checkThrownException(mock, IllegalArgumentException.class, null, "The input message body has an invalid format."); } @Test void testExceptionForSignatureVerificationOptionNoSignatureAllowed() throws Exception { decryptor.setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkey", "Test Message"); MockEndpoint.assertIsSatisfied(context); checkThrownException(mock, PGPException.class, null, "PGP message contains a signature although a signature is not expected"); } @Test void testExceptionForSignatureVerificationOptionRequired() throws Exception { encryptor.setSignatureKeyUserid(null); // no signature decryptor.setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_REQUIRED); MockEndpoint mock = getMockEndpoint("mock:exception"); mock.expectedMessageCount(1); template.sendBody("direct:subkey", "Test Message"); MockEndpoint.assertIsSatisfied(context); checkThrownException(mock, PGPException.class, null, "PGP message does not contain any signatures although a signature is expected"); } @Test void testSignatureVerificationOptionIgnore() throws Exception { // encryptor is sending a PGP message with signature! Decryptor is ignoreing the signature decryptor.setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_IGNORE); decryptor.setSignatureKeyUserids(null); decryptor.setSignatureKeyFileName(null); // no public keyring! --> no signature validation possible String payload = "Test Message"; MockEndpoint mock = getMockEndpoint("mock:unencrypted"); mock.expectedBodiesReceived(payload); template.sendBody("direct:subkey", payload); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder[] createRouteBuilders() { return new RouteBuilder[] { new RouteBuilder() { public void configure() throws Exception { onException(Exception.class).handled(true).to("mock:exception"); // START SNIPPET: pgp-format // Public Key FileName String keyFileName = getKeyFileName(); // Private Key FileName String keyFileNameSec = getKeyFileNameSec(); // Keyring Userid Used to Encrypt String keyUserid = getKeyUserId(); // Private key password String keyPassword = getKeyPassword(); from("direct:inline").marshal().pgp(keyFileName, keyUserid).to("mock:encrypted").unmarshal() .pgp(keyFileNameSec, null, keyPassword).to("mock:unencrypted"); // END SNIPPET: pgp-format // START SNIPPET: pgp-format-header PGPDataFormat pgpEncrypt = new PGPDataFormat(); pgpEncrypt.setKeyFileName(keyFileName); pgpEncrypt.setKeyUserid(keyUserid); pgpEncrypt.setProvider(getProvider()); pgpEncrypt.setAlgorithm(getAlgorithm()); pgpEncrypt.setCompressionAlgorithm(getCompressionAlgorithm()); PGPDataFormat pgpDecrypt = new PGPDataFormat(); pgpDecrypt.setKeyFileName(keyFileNameSec); pgpDecrypt.setPassword(keyPassword); pgpDecrypt.setProvider(getProvider()); pgpDecrypt.setSignatureVerificationOption( PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED); from("direct:inline2").marshal(pgpEncrypt).to("mock:encrypted").unmarshal(pgpDecrypt).to("mock:unencrypted"); from("direct:inline-armor").marshal().pgp(keyFileName, keyUserid, null, true, true).to("mock:encrypted") .unmarshal() .pgp(keyFileNameSec, null, keyPassword, true, true).to("mock:unencrypted"); // END SNIPPET: pgp-format-header // START SNIPPET: pgp-format-signature PGPDataFormat pgpSignAndEncrypt = new PGPDataFormat(); pgpSignAndEncrypt.setKeyFileName(keyFileName); pgpSignAndEncrypt.setKeyUserid(keyUserid); pgpSignAndEncrypt.setSignatureKeyFileName(keyFileNameSec); PGPPassphraseAccessor passphraseAccessor = getPassphraseAccessor(); pgpSignAndEncrypt.setSignatureKeyUserid("Super <sdude@nowhere.net>"); // must be the exact user Id because passphrase is searched in accessor pgpSignAndEncrypt.setPassphraseAccessor(passphraseAccessor); pgpSignAndEncrypt.setProvider(getProvider()); pgpSignAndEncrypt.setAlgorithm(getAlgorithm()); pgpSignAndEncrypt.setHashAlgorithm(getHashAlgorithm()); pgpSignAndEncrypt.setCompressionAlgorithm(getCompressionAlgorithm()); PGPDataFormat pgpVerifyAndDecrypt = new PGPDataFormat(); pgpVerifyAndDecrypt.setKeyFileName(keyFileNameSec); pgpVerifyAndDecrypt.setPassword(keyPassword); pgpVerifyAndDecrypt.setSignatureKeyFileName(keyFileName); pgpVerifyAndDecrypt.setProvider(getProvider()); pgpVerifyAndDecrypt.setSignatureKeyUserid(keyUserid); // restrict verification to public keys with certain User ID from("direct:inline-sign").marshal(pgpSignAndEncrypt).to("mock:encrypted").unmarshal(pgpVerifyAndDecrypt) .to("mock:unencrypted"); // END SNIPPET: pgp-format-signature // test verifying exception, no public key found corresponding to signature key userIds from("direct:verify_exception_sig_userids").marshal(pgpSignAndEncrypt).to("mock:encrypted") .setHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERIDS) .constant(Arrays.asList(new String[] { "wrong1", "wrong2" })) .setHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID).constant("wrongUserID") .unmarshal(pgpVerifyAndDecrypt) .to("mock:unencrypted"); /* ---- key ring as byte array -- */ // START SNIPPET: pgp-format-key-ring-byte-array PGPDataFormat pgpEncryptByteArray = new PGPDataFormat(); pgpEncryptByteArray.setEncryptionKeyRing(getPublicKeyRing()); pgpEncryptByteArray.setKeyUserids(getKeyUserIds()); pgpEncryptByteArray.setProvider(getProvider()); pgpEncryptByteArray.setAlgorithm(SymmetricKeyAlgorithmTags.DES); pgpEncryptByteArray.setCompressionAlgorithm(CompressionAlgorithmTags.UNCOMPRESSED); PGPDataFormat pgpDecryptByteArray = new PGPDataFormat(); pgpDecryptByteArray.setEncryptionKeyRing(getSecKeyRing()); pgpDecryptByteArray.setPassphraseAccessor(passphraseAccessor); pgpDecryptByteArray.setProvider(getProvider()); from("direct:key-ring-byte-array").streamCaching().marshal(pgpEncryptByteArray).to("mock:encrypted") .unmarshal(pgpDecryptByteArray).to("mock:unencrypted"); // END SNIPPET: pgp-format-key-ring-byte-array // START SNIPPET: pgp-format-signature-key-ring-byte-array PGPDataFormat pgpSignAndEncryptByteArray = new PGPDataFormat(); pgpSignAndEncryptByteArray.setKeyUserid(keyUserid); pgpSignAndEncryptByteArray.setSignatureKeyRing(getSecKeyRing()); pgpSignAndEncryptByteArray.setSignatureKeyUserid(keyUserid); pgpSignAndEncryptByteArray.setSignaturePassword(keyPassword); pgpSignAndEncryptByteArray.setProvider(getProvider()); pgpSignAndEncryptByteArray.setAlgorithm(SymmetricKeyAlgorithmTags.BLOWFISH); pgpSignAndEncryptByteArray.setHashAlgorithm(HashAlgorithmTags.RIPEMD160); pgpSignAndEncryptByteArray.setCompressionAlgorithm(CompressionAlgorithmTags.ZLIB); PGPDataFormat pgpVerifyAndDecryptByteArray = new PGPDataFormat(); pgpVerifyAndDecryptByteArray.setPassphraseAccessor(passphraseAccessor); pgpVerifyAndDecryptByteArray.setEncryptionKeyRing(getSecKeyRing()); pgpVerifyAndDecryptByteArray.setProvider(getProvider()); // restrict verification to public keys with certain User ID pgpVerifyAndDecryptByteArray.setSignatureKeyUserids(getSignatureKeyUserIds()); pgpVerifyAndDecryptByteArray .setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_REQUIRED); from("direct:sign-key-ring-byte-array").streamCaching() // encryption key ring can also be set as header .setHeader(PGPDataFormat.ENCRYPTION_KEY_RING).constant(getPublicKeyRing()) .marshal(pgpSignAndEncryptByteArray) // it is recommended to remove the header immediately when it is no longer needed .removeHeader(PGPDataFormat.ENCRYPTION_KEY_RING).to("mock:encrypted") // signature key ring can also be set as header .setHeader(PGPDataFormat.SIGNATURE_KEY_RING).constant(getPublicKeyRing()) .unmarshal(pgpVerifyAndDecryptByteArray) // it is recommended to remove the header immediately when it is no longer needed .removeHeader(PGPDataFormat.SIGNATURE_KEY_RING).to("mock:unencrypted"); // END SNIPPET: pgp-format-signature-key-ring-byte-array // START SNIPPET: pgp-format-several-signer-keys PGPDataFormat pgpSignAndEncryptSeveralSignerKeys = new PGPDataFormat(); pgpSignAndEncryptSeveralSignerKeys.setKeyUserid(keyUserid); pgpSignAndEncryptSeveralSignerKeys.setEncryptionKeyRing(getPublicKeyRing()); pgpSignAndEncryptSeveralSignerKeys.setSignatureKeyRing(getSecKeyRing()); List<String> signerUserIds = new ArrayList<>(); signerUserIds.add("Third (comment third) <email@third.com>"); signerUserIds.add("Second <email@second.com>"); pgpSignAndEncryptSeveralSignerKeys.setSignatureKeyUserids(signerUserIds); Map<String, String> userId2Passphrase = new HashMap<>(); userId2Passphrase.put("Third (comment third) <email@third.com>", "sdude"); userId2Passphrase.put("Second <email@second.com>", "sdude"); PGPPassphraseAccessor passphraseAccessorSeveralKeys = new DefaultPGPPassphraseAccessor(userId2Passphrase); pgpSignAndEncryptSeveralSignerKeys.setPassphraseAccessor(passphraseAccessorSeveralKeys); PGPDataFormat pgpVerifyAndDecryptSeveralSignerKeys = new PGPDataFormat(); pgpVerifyAndDecryptSeveralSignerKeys.setPassphraseAccessor(passphraseAccessor); pgpVerifyAndDecryptSeveralSignerKeys.setEncryptionKeyRing(getSecKeyRing()); pgpVerifyAndDecryptSeveralSignerKeys.setSignatureKeyRing(getPublicKeyRing()); pgpVerifyAndDecryptSeveralSignerKeys.setProvider(getProvider()); // only specify one expected signature List<String> expectedSigUserIds = new ArrayList<>(); expectedSigUserIds.add("Second <email@second.com>"); pgpVerifyAndDecryptSeveralSignerKeys.setSignatureKeyUserids(expectedSigUserIds); from("direct:several-signer-keys").streamCaching().marshal(pgpSignAndEncryptSeveralSignerKeys) .to("mock:encrypted") .unmarshal(pgpVerifyAndDecryptSeveralSignerKeys).to("mock:unencrypted"); // END SNIPPET: pgp-format-several-signer-keys // test encryption by several key and signing by serveral keys where the keys are specified by one User ID part PGPDataFormat pgpSignAndEncryptOneUserIdWithServeralKeys = new PGPDataFormat(); pgpSignAndEncryptOneUserIdWithServeralKeys.setEncryptionKeyRing(getPublicKeyRing()); pgpSignAndEncryptOneUserIdWithServeralKeys.setSignatureKeyRing(getSecKeyRing()); // the two private keys have the same password therefore we do not need a passphrase accessor pgpSignAndEncryptOneUserIdWithServeralKeys.setPassword(getKeyPassword()); PGPDataFormat pgpVerifyAndDecryptOneUserIdWithServeralKeys = new PGPDataFormat(); pgpVerifyAndDecryptOneUserIdWithServeralKeys.setPassword(getKeyPassword()); pgpVerifyAndDecryptOneUserIdWithServeralKeys.setEncryptionKeyRing(getSecKeyRing()); pgpVerifyAndDecryptOneUserIdWithServeralKeys.setSignatureKeyRing(getPublicKeyRing()); pgpVerifyAndDecryptOneUserIdWithServeralKeys.setProvider(getProvider()); pgpVerifyAndDecryptOneUserIdWithServeralKeys.setSignatureKeyUserids(expectedSigUserIds); from("direct:one-userid-several-keys") // there are two keys which have a User ID which contains the string "econd" .setHeader(PGPKeyAccessDataFormat.KEY_USERID) .constant("econd") .setHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID) .constant("econd") .marshal(pgpSignAndEncryptOneUserIdWithServeralKeys) // it is recommended to remove the header immediately when it is no longer needed .removeHeader(PGPKeyAccessDataFormat.KEY_USERID) .removeHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID) .to("mock:encrypted") // only specify one expected signature key, to check the first signature .setHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID) .constant("Second <email@second.com>") .unmarshal(pgpVerifyAndDecryptOneUserIdWithServeralKeys) // do it again but now check the second signature key // there are two keys which have a User ID which contains the string "econd" .setHeader(PGPKeyAccessDataFormat.KEY_USERID).constant("econd") .setHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID) .constant("econd").marshal(pgpSignAndEncryptOneUserIdWithServeralKeys) // it is recommended to remove the header immediately when it is no longer needed .removeHeader(PGPKeyAccessDataFormat.KEY_USERID) .removeHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID) // only specify one expected signature key, to check the second signature .setHeader(PGPKeyAccessDataFormat.SIGNATURE_KEY_USERID) .constant("Third (comment third) <email@third.com>") .unmarshal(pgpVerifyAndDecryptOneUserIdWithServeralKeys).to("mock:unencrypted"); } }, new RouteBuilder() { public void configure() { onException(Exception.class).handled(true).to("mock:exception"); from("direct:keyflag").marshal(encryptor).to("mock:encrypted_keyflag"); // test that the correct subkey is selected during decrypt and verify from("direct:subkey").marshal(encryptor).to("mock:encrypted").unmarshal(decryptor).to("mock:unencrypted"); from("direct:subkeyUnmarshal").unmarshal(decryptor).to("mock:unencrypted"); } }, new RouteBuilder() { public void configure() throws Exception { PGPPublicKeyAccessor publicKeyAccessor = new DefaultPGPPublicKeyAccessor(getPublicKeyRing()); //password cannot be set dynamically! PGPSecretKeyAccessor secretKeyAccessor = new DefaultPGPSecretKeyAccessor(getSecKeyRing(), "sdude", getProvider()); PGPKeyAccessDataFormat dfEncryptSignKeyAccess = new PGPKeyAccessDataFormat(); dfEncryptSignKeyAccess.setPublicKeyAccessor(publicKeyAccessor); dfEncryptSignKeyAccess.setSecretKeyAccessor(secretKeyAccessor); dfEncryptSignKeyAccess.setKeyUserid(getKeyUserId()); dfEncryptSignKeyAccess.setSignatureKeyUserid(getKeyUserId()); PGPKeyAccessDataFormat dfDecryptVerifyKeyAccess = new PGPKeyAccessDataFormat(); dfDecryptVerifyKeyAccess.setPublicKeyAccessor(publicKeyAccessor); dfDecryptVerifyKeyAccess.setSecretKeyAccessor(secretKeyAccessor); dfDecryptVerifyKeyAccess.setSignatureKeyUserid(getKeyUserId()); from("direct:key_access").marshal(dfEncryptSignKeyAccess).to("mock:encrypted") .unmarshal(dfDecryptVerifyKeyAccess) .to("mock:unencrypted"); } }, new RouteBuilder() { public void configure() throws Exception { // START SNIPPET: pgp-encrypt-sign-without-compressed-data-packet PGPDataFormat pgpEncryptSign = new PGPDataFormat(); pgpEncryptSign.setKeyUserid(getKeyUserId()); pgpEncryptSign.setSignatureKeyRing(getSecKeyRing()); pgpEncryptSign.setSignatureKeyUserid(getKeyUserId()); pgpEncryptSign.setSignaturePassword(getKeyPassword()); pgpEncryptSign.setProvider(getProvider()); pgpEncryptSign.setAlgorithm(SymmetricKeyAlgorithmTags.BLOWFISH); pgpEncryptSign.setHashAlgorithm(HashAlgorithmTags.RIPEMD160); // without compressed data packet pgpEncryptSign.setWithCompressedDataPacket(false); PGPDataFormat pgpVerifyAndDecryptByteArray = new PGPDataFormat(); pgpVerifyAndDecryptByteArray.setPassphraseAccessor(getPassphraseAccessor()); pgpVerifyAndDecryptByteArray.setEncryptionKeyRing(getSecKeyRing()); pgpVerifyAndDecryptByteArray.setProvider(getProvider()); // restrict verification to public keys with certain User ID pgpVerifyAndDecryptByteArray.setSignatureKeyUserids(getSignatureKeyUserIds()); pgpVerifyAndDecryptByteArray .setSignatureVerificationOption(PGPKeyAccessDataFormat.SIGNATURE_VERIFICATION_OPTION_REQUIRED); from("direct:encrypt-sign-without-compressed-data-packet").streamCaching() // encryption key ring can also be set as header .setHeader(PGPDataFormat.ENCRYPTION_KEY_RING).constant(getPublicKeyRing()).marshal(pgpEncryptSign) // it is recommended to remove the header immediately when it is no longer needed .removeHeader(PGPDataFormat.ENCRYPTION_KEY_RING).to("mock:encrypted") // signature key ring can also be set as header .setHeader(PGPDataFormat.SIGNATURE_KEY_RING).constant(getPublicKeyRing()) .unmarshal(pgpVerifyAndDecryptByteArray) // it is recommended to remove the header immediately when it is no longer needed .removeHeader(PGPDataFormat.SIGNATURE_KEY_RING).to("mock:unencrypted"); // END SNIPPET: pgp-encrypt-sign-without-compressed-data-packet } } }; } public static byte[] getPublicKeyRing() throws Exception { return getKeyRing(PUB_KEY_RING_FILE_NAME); } public static byte[] getSecKeyRing() throws Exception { return getKeyRing(SEC_KEY_RING_FILE_NAME); } private static byte[] getKeyRing(String fileName) throws IOException { InputStream is = PGPDataFormatTest.class.getClassLoader().getResourceAsStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(is, output); output.close(); return output.toByteArray(); } public static PGPPassphraseAccessor getPassphraseAccessor() { Map<String, String> userId2Passphrase = Collections.singletonMap("Super <sdude@nowhere.net>", "sdude"); PGPPassphraseAccessor passphraseAccessor = new DefaultPGPPassphraseAccessor(userId2Passphrase); return passphraseAccessor; } public static void checkThrownException( MockEndpoint mock, Class<? extends Exception> cl, Class<? extends Exception> expectedCauseClass, String expectedMessagePart) throws Exception { Exception e = (Exception) mock.getExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT); assertNotNull(e, "Expected excpetion " + cl.getName() + " missing"); if (e.getClass() != cl) { String stackTrace = ExceptionHelper.stackTraceToString(e); fail("Exception " + cl.getName() + " excpected, but was " + e.getClass().getName() + ": " + stackTrace); } if (expectedMessagePart != null) { if (e.getMessage() == null) { fail("Expected excption does not contain a message. Stack trace: " + ExceptionHelper.stackTraceToString(e)); } else { if (!e.getMessage().contains(expectedMessagePart)) { fail("Expected excption message does not contain a expected message part " + expectedMessagePart + ". Stack trace: " + ExceptionHelper.stackTraceToString(e)); } } } if (expectedCauseClass != null) { Throwable cause = e.getCause(); assertNotNull(cause, "Expected cause exception" + expectedCauseClass.getName() + " missing"); if (expectedCauseClass != cause.getClass()) { fail("Cause exception " + expectedCauseClass.getName() + " expected, but was " + cause.getClass().getName() + ": " + ExceptionHelper.stackTraceToString(e)); } } } }
PGPDataFormatTest
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RJsonBucketAsync.java
{ "start": 850, "end": 14113 }
interface ____<V> extends RBucketAsync<V> { /** * Get Json object/objects by JSONPath * * @param codec object codec * @param paths JSON paths * @return object * * @param <T> the type of object */ <T> RFuture<T> getAsync(JsonCodec codec, String... paths); /** * Sets Json object by JSONPath only if previous value is empty * * @param path JSON path * @param value object * @return {@code true} if successful, or {@code false} if * value was already set */ RFuture<Boolean> setIfAbsentAsync(String path, Object value); /** * Use {@link #setIfAbsentAsync(String, Object)} instead * * @param path JSON path * @param value object * @return {@code true} if successful, or {@code false} if * value was already set */ @Deprecated RFuture<Boolean> trySetAsync(String path, Object value); /** * Sets Json object by JSONPath only if previous value is non-empty * * @param path JSON path * @param value object * @return {@code true} if successful, or {@code false} if * element wasn't set */ RFuture<Boolean> setIfExistsAsync(String path, Object value); /** * Atomically sets the value to the given updated value * by given JSONPath, only if serialized state of * the current value equals to serialized state of the expected value. * * @param path JSON path * @param expect the expected value * @param update the new value * @return {@code true} if successful; or {@code false} if the actual value * was not equal to the expected value. */ RFuture<Boolean> compareAndSetAsync(String path, Object expect, Object update); /** * Retrieves current value of element specified by JSONPath * and replaces it with <code>newValue</code>. * * @param codec object codec * @param path JSON path * @param newValue value to set * @return previous value */ <T> RFuture<T> getAndSetAsync(JsonCodec codec, String path, Object newValue); /** * Stores object into element by specified JSONPath. * * @param path JSON path * @param value value to set * @return void */ RFuture<Void> setAsync(String path, Object value); /** * Returns size of string data by JSONPath * * @param path JSON path * @return size of string */ RFuture<Long> stringSizeAsync(String path); /** * Returns list of string data size by JSONPath. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @return list of string data sizes */ RFuture<List<Long>> stringSizeMultiAsync(String path); /** * Appends string data to element specified by JSONPath. * Returns new size of string data. * * @param path JSON path * @param value data * @return size of string data */ RFuture<Long> stringAppendAsync(String path, Object value); /** * Appends string data to elements specified by JSONPath. * Returns new size of string data. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param value data * @return list of string data sizes */ RFuture<List<Long>> stringAppendMultiAsync(String path, Object value); /** * Appends values to array specified by JSONPath. * Returns new size of array. * * @param path JSON path * @param values values to append * @return size of array */ RFuture<Long> arrayAppendAsync(String path, Object... values); /** * Appends values to arrays specified by JSONPath. * Returns new size of arrays. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param values values to append * @return list of arrays size */ RFuture<List<Long>> arrayAppendMultiAsync(String path, Object... values); /** * Returns index of object in array specified by JSONPath. * -1 means object not found. * * @param path JSON path * @param value value to search * @return index in array */ RFuture<Long> arrayIndexAsync(String path, Object value); /** * Returns index of object in arrays specified by JSONPath. * -1 means object not found. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param value value to search * @return list of index in arrays */ RFuture<List<Long>> arrayIndexMultiAsync(String path, Object value); /** * Returns index of object in array specified by JSONPath * in range between <code>start</code> (inclusive) and <code>end</code> (exclusive) indexes. * -1 means object not found. * * @param path JSON path * @param value value to search * @param start start index, inclusive * @param end end index, exclusive * @return index in array */ RFuture<Long> arrayIndexAsync(String path, Object value, long start, long end); /** * Returns index of object in arrays specified by JSONPath * in range between <code>start</code> (inclusive) and <code>end</code> (exclusive) indexes. * -1 means object not found. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param value value to search * @param start start index, inclusive * @param end end index, exclusive * @return list of index in arrays */ RFuture<List<Long>> arrayIndexMultiAsync(String path, Object value, long start, long end); /** * Inserts values into array specified by JSONPath. * Values are inserted at defined <code>index</code>. * * @param path JSON path * @param index array index at which values are inserted * @param values values to insert * @return size of array */ RFuture<Long> arrayInsertAsync(String path, long index, Object... values); /** * Inserts values into arrays specified by JSONPath. * Values are inserted at defined <code>index</code>. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param index array index at which values are inserted * @param values values to insert * @return list of arrays size */ RFuture<List<Long>> arrayInsertMultiAsync(String path, long index, Object... values); /** * Returns size of array specified by JSONPath. * * @param path JSON path * @return size of array */ RFuture<Long> arraySizeAsync(String path); /** * Returns size of arrays specified by JSONPath. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @return list of arrays size */ RFuture<List<Long>> arraySizeMultiAsync(String path); /** * Polls last element of array specified by JSONPath. * * @param codec object codec * @param path JSON path * @return last element * * @param <T> the type of object */ <T> RFuture<T> arrayPollLastAsync(JsonCodec codec, String path); /** * Polls last element of arrays specified by JSONPath. * Compatible only with enhanced syntax starting with '$' character. * * @param codec object codec * @param path JSON path * @return list of last elements * * @param <T> the type of object */ <T> RFuture<List<T>> arrayPollLastMultiAsync(JsonCodec codec, String path); /** * Polls first element of array specified by JSONPath. * * @param codec object codec * @param path JSON path * @return first element * * @param <T> the type of object */ <T> RFuture<T> arrayPollFirstAsync(JsonCodec codec, String path); /** * Polls first element of arrays specified by JSONPath. * Compatible only with enhanced syntax starting with '$' character. * * @param codec object codec * @param path JSON path * @return list of first elements * * @param <T> the type of object */ <T> RFuture<List<T>> arrayPollFirstMultiAsync(JsonCodec codec, String path); /** * Pops element located at index of array specified by JSONPath. * * @param codec object codec * @param path JSON path * @param index array index * @return element * * @param <T> the type of object */ <T> RFuture<T> arrayPopAsync(JsonCodec codec, String path, long index); /** * Pops elements located at index of arrays specified by JSONPath. * Compatible only with enhanced syntax starting with '$' character. * * @param codec object codec * @param path JSON path * @param index array index * @return list of elements * * @param <T> the type of object */ <T> RFuture<List<T>> arrayPopMultiAsync(JsonCodec codec, String path, long index); /** * Trims array specified by JSONPath in range * between <code>start</code> (inclusive) and <code>end</code> (inclusive) indexes. * * @param path JSON path * @param start start index, inclusive * @param end end index, inclusive * @return length of array */ RFuture<Long> arrayTrimAsync(String path, long start, long end); /** * Trims arrays specified by JSONPath in range * between <code>start</code> (inclusive) and <code>end</code> (inclusive) indexes. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param start start index, inclusive * @param end end index, inclusive * @return length of array */ RFuture<List<Long>> arrayTrimMultiAsync(String path, long start, long end); /** * Clears json container. * * @return number of cleared containers */ RFuture<Long> clearAsync(); /** * Clears json container specified by JSONPath. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @return number of cleared containers */ RFuture<Long> clearAsync(String path); /** * Increments the current value specified by JSONPath by <code>delta</code>. * * @param path JSON path * @param delta increment value * @return the updated value */ <T extends Number> RFuture<T> incrementAndGetAsync(String path, T delta); /** * Increments the current values specified by JSONPath by <code>delta</code>. * Compatible only with enhanced syntax starting with '$' character. * * @param path JSON path * @param delta increment value * @return list of updated value */ <T extends Number> RFuture<List<T>> incrementAndGetMultiAsync(String path, T delta); /** * Merges object into element by the specified JSONPath. * * @param path JSON path * @param value value to merge */ RFuture<Void> mergeAsync(String path, Object value); /** * Returns keys amount in JSON container * * @return keys amount */ RFuture<Long> countKeysAsync(); /** * Returns keys amount in JSON container specified by JSONPath * * @param path JSON path * @return keys amount */ RFuture<Long> countKeysAsync(String path); /** * Returns list of keys amount in JSON containers specified by JSONPath * * @param path JSON path * @return list of keys amount */ RFuture<List<Long>> countKeysMultiAsync(String path); /** * Returns list of keys in JSON container * * @return list of keys */ RFuture<List<String>> getKeysAsync(); /** * Returns list of keys in JSON container specified by JSONPath * * @param path JSON path * @return list of keys */ RFuture<List<String>> getKeysAsync(String path); /** * Returns list of keys in JSON containers specified by JSONPath * * @param path JSON path * @return list of keys */ RFuture<List<List<String>>> getKeysMultiAsync(String path); /** * Toggle boolean value specified by JSONPath * * @param path JSON path * @return new boolean value */ RFuture<Boolean> toggleAsync(String path); /** * Toggle boolean values specified by JSONPath * * @param path JSON path * @return list of boolean values */ RFuture<List<Boolean>> toggleMultiAsync(String path); /** * Returns type of element * * @return type of element */ RFuture<JsonType> getTypeAsync(); /** * Returns type of element specified by JSONPath * * @param path JSON path * @return type of element */ RFuture<JsonType> getTypeAsync(String path); /** * Deletes JSON elements specified by JSONPath * * @param path JSON path * @return number of deleted elements */ RFuture<Long> deleteAsync(String path); }
RJsonBucketAsync
java
reactor__reactor-core
reactor-core/src/jcstress/java/reactor/util/concurrent/SpscArrayQueueStressTest.java
{ "start": 1041, "end": 1718 }
class ____ { @JCStressTest @Outcome(id = {"5, 1, 2, 3, 4, 5"}, expect = Expect.ACCEPTABLE, desc = "None consumed, all in order") @Outcome(id = {"4, 1, 2, 3, 4, 5"}, expect = Expect.ACCEPTABLE, desc = "1 consumed, all in order") @Outcome(id = {"3, 1, 2, 3, 4, 5"}, expect = Expect.ACCEPTABLE, desc = "2 consumed, all in order") @Outcome(id = {"2, 1, 2, 3, 4, 5"}, expect = Expect.ACCEPTABLE, desc = "3 consumed, all in order") @Outcome(id = {"1, 1, 2, 3, 4, 5"}, expect = Expect.ACCEPTABLE, desc = "4 consumed, all in order") @Outcome(id = {"0, 1, 2, 3, 4, 5"}, expect = Expect.ACCEPTABLE, desc = "All consumed, all in order") @State public static
SpscArrayQueueStressTest
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/JacksonImpl.java
{ "start": 2770, "end": 4953 }
class ____ mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz)); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public String toJson(Object obj) { try { return getMapper().writeValueAsString(obj); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public String toPrettyJson(Object obj) { try { return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } @Override public Object convertObject(Object obj, Type type) { JsonMapper mapper = getMapper(); return mapper.convertValue(obj, mapper.constructType(type)); } @Override public Object convertObject(Object obj, Class<?> clazz) { return getMapper().convertValue(obj, clazz); } protected JsonMapper getMapper() { JsonMapper mapper = this.mapper; if (mapper == null) { synchronized (this) { mapper = this.mapper; if (mapper == null) { this.mapper = mapper = createBuilder().build(); } } } return mapper; } protected Builder createBuilder() { Builder builder = JsonMapper.builder() .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .serializationInclusion(Include.NON_NULL) .addModule(new JavaTimeModule()); for (Module module : customModules) { builder.addModule(module); } return builder; } public void addModule(Module module) { synchronized (this) { customModules.add(module); // Invalidate the mapper to rebuild it this.mapper = null; } } }
return
java
spring-projects__spring-framework
spring-core-test/src/main/java/org/springframework/aot/agent/InvocationsRecorderClassTransformer.java
{ "start": 1130, "end": 1266 }
class ____ in the list of packages considered for instrumentation. * * @author Brian Clozel * @see InvocationsRecorderClassVisitor */
is
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/classrolesallowed/ClassRolesAllowedBaseResourceWithoutPathExtParentRes_SecurityOnInterface.java
{ "start": 81, "end": 240 }
class ____ extends ClassRolesAllowedParentResourceWithPath_SecurityOnInterface { }
ClassRolesAllowedBaseResourceWithoutPathExtParentRes_SecurityOnInterface
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/bcextensions/ScopeInfoImpl.java
{ "start": 175, "end": 1080 }
class ____ implements ScopeInfo { private final org.jboss.jandex.IndexView jandexIndex; private final org.jboss.jandex.MutableAnnotationOverlay annotationOverlay; private final io.quarkus.arc.processor.ScopeInfo arcScopeInfo; ScopeInfoImpl(org.jboss.jandex.IndexView jandexIndex, org.jboss.jandex.MutableAnnotationOverlay annotationOverlay, io.quarkus.arc.processor.ScopeInfo arcScopeInfo) { this.jandexIndex = jandexIndex; this.annotationOverlay = annotationOverlay; this.arcScopeInfo = arcScopeInfo; } @Override public ClassInfo annotation() { org.jboss.jandex.ClassInfo jandexClass = jandexIndex.getClassByName(arcScopeInfo.getDotName()); return new ClassInfoImpl(jandexIndex, annotationOverlay, jandexClass); } @Override public boolean isNormal() { return arcScopeInfo.isNormal(); } }
ScopeInfoImpl
java
apache__kafka
connect/api/src/main/java/org/apache/kafka/connect/header/Header.java
{ "start": 1188, "end": 2437 }
interface ____ { /** * The header's key, which is not necessarily unique within the set of headers on a Kafka message. * * @return the header's key; never null */ String key(); /** * Return the {@link Schema} associated with this header, if there is one. Not all headers will have schemas. * * @return the header's schema, or null if no schema is associated with this header */ Schema schema(); /** * Get the header's value as deserialized by Connect's header converter. * * @return the deserialized object representation of the header's value; may be null */ Object value(); /** * Return a new {@link Header} object that has the same key but with the supplied value. * * @param schema the schema for the new value; may be null * @param value the new value * @return the new {@link Header}; never null */ Header with(Schema schema, Object value); /** * Return a new {@link Header} object that has the same schema and value but with the supplied key. * * @param key the key for the new header; may not be null * @return the new {@link Header}; never null */ Header rename(String key); }
Header
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/ArraySliceUnnestFunction.java
{ "start": 989, "end": 3028 }
class ____ extends AbstractSqmSelfRenderingFunctionDescriptor { private final boolean castEmptyArrayLiteral; public ArraySliceUnnestFunction(boolean castEmptyArrayLiteral) { super( "array_slice", StandardArgumentsValidators.composite( new ArgumentTypesValidator( null, ANY, INTEGER, INTEGER ), ArrayArgumentValidator.DEFAULT_INSTANCE ), ArrayViaArgumentReturnTypeResolver.DEFAULT_INSTANCE, StandardFunctionArgumentTypeResolvers.composite( StandardFunctionArgumentTypeResolvers.invariant( ANY, INTEGER, INTEGER ), StandardFunctionArgumentTypeResolvers.IMPLIED_RESULT_TYPE ) ); this.castEmptyArrayLiteral = castEmptyArrayLiteral; } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { final Expression arrayExpression = (Expression) sqlAstArguments.get( 0 ); final Expression startIndexExpression = (Expression) sqlAstArguments.get( 1 ); final Expression endIndexExpression = (Expression) sqlAstArguments.get( 2 ); sqlAppender.append( "case when "); arrayExpression.accept( walker ); sqlAppender.append( " is not null and "); startIndexExpression.accept( walker ); sqlAppender.append( " is not null and "); endIndexExpression.accept( walker ); sqlAppender.append( " is not null then coalesce((select array_agg(t.val) from unnest(" ); arrayExpression.accept( walker ); sqlAppender.append( ") with ordinality t(val,idx) where t.idx between " ); startIndexExpression.accept( walker ); sqlAppender.append( " and " ); endIndexExpression.accept( walker ); sqlAppender.append( "),"); if ( castEmptyArrayLiteral ) { sqlAppender.append( "cast(array[] as " ); sqlAppender.append( DdlTypeHelper.getCastTypeName( returnType, walker.getSessionFactory().getTypeConfiguration() ) ); sqlAppender.append( ')' ); } else { sqlAppender.append( "array[]" ); } sqlAppender.append(") end" ); } }
ArraySliceUnnestFunction
java
google__guava
android/guava/src/com/google/common/collect/ImmutableSortedMap.java
{ "start": 23229, "end": 32182 }
class ____<K, V> extends ImmutableMap.Builder<K, V> { private transient @Nullable Object[] keys; private transient @Nullable Object[] values; private final Comparator<? super K> comparator; /** * Creates a new builder. The returned builder is equivalent to the builder generated by {@link * ImmutableSortedMap#orderedBy}. */ public Builder(Comparator<? super K> comparator) { this(comparator, ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); } private Builder(Comparator<? super K> comparator, int initialCapacity) { this.comparator = checkNotNull(comparator); this.keys = new @Nullable Object[initialCapacity]; this.values = new @Nullable Object[initialCapacity]; } private void ensureCapacity(int minCapacity) { if (minCapacity > keys.length) { int newCapacity = ImmutableCollection.Builder.expandedCapacity(keys.length, minCapacity); this.keys = Arrays.copyOf(keys, newCapacity); this.values = Arrays.copyOf(values, newCapacity); } } /** * Associates {@code key} with {@code value} in the built map. Duplicate keys, according to the * comparator (which might be the keys' natural order), are not allowed, and will cause {@link * #build} to fail. */ @CanIgnoreReturnValue @Override public Builder<K, V> put(K key, V value) { ensureCapacity(size + 1); checkEntryNotNull(key, value); keys[size] = key; values[size] = value; size++; return this; } /** * Adds the given {@code entry} to the map, making it immutable if necessary. Duplicate keys, * according to the comparator (which might be the keys' natural order), are not allowed, and * will cause {@link #build} to fail. * * @since 11.0 */ @CanIgnoreReturnValue @Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { super.put(entry); return this; } /** * Associates all of the given map's keys and values in the built map. Duplicate keys, according * to the comparator (which might be the keys' natural order), are not allowed, and will cause * {@link #build} to fail. * * @throws NullPointerException if any key or value in {@code map} is null */ @CanIgnoreReturnValue @Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { super.putAll(map); return this; } /** * Adds all the given entries to the built map. Duplicate keys, according to the comparator * (which might be the keys' natural order), are not allowed, and will cause {@link #build} to * fail. * * @throws NullPointerException if any key, value, or entry is null * @since 19.0 */ @CanIgnoreReturnValue @Override public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { super.putAll(entries); return this; } /** * Throws an {@code UnsupportedOperationException}. * * @since 19.0 * @deprecated Unsupported by ImmutableSortedMap.Builder. */ @CanIgnoreReturnValue @Override @Deprecated @DoNotCall("Always throws UnsupportedOperationException") public final Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { throw new UnsupportedOperationException("Not available on ImmutableSortedMap.Builder"); } /* * While the current implementation returns `this`, that's not something we mean to guarantee. * Anyway, the purpose of this method is to implement a BinaryOperator combiner for a Collector, * so its return value will get used naturally. */ @SuppressWarnings("CanIgnoreReturnValueSuggester") Builder<K, V> combine(ImmutableSortedMap.Builder<K, V> other) { ensureCapacity(size + other.size); System.arraycopy(other.keys, 0, this.keys, this.size, other.size); System.arraycopy(other.values, 0, this.values, this.size, other.size); size += other.size; return this; } /** * Returns a newly-created immutable sorted map. * * <p>Prefer the equivalent method {@link #buildOrThrow()} to make it explicit that the method * will throw an exception if there are duplicate keys. The {@code build()} method will soon be * deprecated. * * @throws IllegalArgumentException if any two keys are equal according to the comparator (which * might be the keys' natural order) */ @Override public ImmutableSortedMap<K, V> build() { return buildOrThrow(); } /** * Returns a newly-created immutable sorted map, or throws an exception if any two keys are * equal. * * @throws IllegalArgumentException if any two keys are equal according to the comparator (which * might be the keys' natural order) * @since 31.0 */ @Override @SuppressWarnings("unchecked") // see inline comments public ImmutableSortedMap<K, V> buildOrThrow() { switch (size) { case 0: return emptyMap(comparator); case 1: // We're careful to put only K and V instances in. // requireNonNull is safe because the first `size` elements have been filled in. ImmutableSortedMap<K, V> result = of(comparator, (K) requireNonNull(keys[0]), (V) requireNonNull(values[0])); return result; default: Object[] sortedKeys = Arrays.copyOf(keys, size); // We're careful to put only K instances in. K[] sortedKs = (K[]) sortedKeys; Arrays.sort(sortedKs, comparator); Object[] sortedValues = new Object[size]; // We might, somehow, be able to reorder values in-place. But it doesn't seem like // there's a way around creating the separate sortedKeys array, and if we're allocating // one array of size n, we might as well allocate two -- to say nothing of the allocation // done in Arrays.sort. for (int i = 0; i < size; i++) { // We're careful to put only K instances in. if (i > 0 && comparator.compare((K) sortedKeys[i - 1], (K) sortedKeys[i]) == 0) { throw new IllegalArgumentException( "keys required to be distinct but compared as equal: " + sortedKeys[i - 1] + " and " + sortedKeys[i]); } // requireNonNull is safe because the first `size` elements have been filled in. // We're careful to put only K instances in. int index = Arrays.binarySearch((K[]) sortedKeys, (K) requireNonNull(keys[i]), comparator); sortedValues[index] = requireNonNull(values[i]); } return new ImmutableSortedMap<K, V>( new RegularImmutableSortedSet<K>( ImmutableList.<K>asImmutableList(sortedKeys), comparator), ImmutableList.<V>asImmutableList(sortedValues)); } } /** * Throws UnsupportedOperationException. A future version may support this operation. Then the * value for any given key will be the one that was last supplied in a {@code put} operation for * that key. * * @throws UnsupportedOperationException always * @since 31.1 * @deprecated This method is not currently implemented, and may never be. */ @DoNotCall @Deprecated @Override public final ImmutableSortedMap<K, V> buildKeepingLast() { // TODO(emcmanus): implement throw new UnsupportedOperationException( "ImmutableSortedMap.Builder does not yet implement buildKeepingLast()"); } } private final transient RegularImmutableSortedSet<K> keySet; private final transient ImmutableList<V> valueList; private final transient @Nullable ImmutableSortedMap<K, V> descendingMap; ImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) { this(keySet, valueList, null); } ImmutableSortedMap( RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList, @Nullable ImmutableSortedMap<K, V> descendingMap) { this.keySet = keySet; this.valueList = valueList; this.descendingMap = descendingMap; } @Override public int size() { return valueList.size(); } @Override public @Nullable V get(@Nullable Object key) { int index = keySet.indexOf(key); return (index == -1) ? null : valueList.get(index); } @Override boolean isPartialView() { return keySet.isPartialView() || valueList.isPartialView(); } /** Returns an immutable set of the mappings in this map, sorted by the key ordering. */ @Override public ImmutableSet<Entry<K, V>> entrySet() { return super.entrySet(); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { final
Builder
java
apache__rocketmq
common/src/test/java/org/apache/rocketmq/common/compression/CompressionTest.java
{ "start": 1113, "end": 4527 }
class ____ { private int level; private Compressor zstd; private Compressor zlib; private Compressor lz4; @Before public void setUp() { level = 5; zstd = CompressorFactory.getCompressor(CompressionType.ZSTD); zlib = CompressorFactory.getCompressor(CompressionType.ZLIB); lz4 = CompressorFactory.getCompressor(CompressionType.LZ4); } @Test public void testCompressionZlib() throws IOException { assertThat(CompressionType.of("zlib")).isEqualTo(CompressionType.ZLIB); assertThat(CompressionType.of(" ZLiB ")).isEqualTo(CompressionType.ZLIB); assertThat(CompressionType.of("ZLIB")).isEqualTo(CompressionType.ZLIB); int randomKB = 4096; Random random = new Random(); for (int i = 0; i < 5; ++i) { String message = RandomStringUtils.randomAlphanumeric(random.nextInt(randomKB) * 1024); byte[] srcBytes = message.getBytes(StandardCharsets.UTF_8); byte[] compressed = zlib.compress(srcBytes, level); byte[] decompressed = zlib.decompress(compressed); // compression ratio may be negative for some random string data // assertThat(compressed.length).isLessThan(srcBytes.length); assertThat(decompressed).isEqualTo(srcBytes); assertThat(new String(decompressed)).isEqualTo(message); } } @Test public void testCompressionZstd() throws IOException { assertThat(CompressionType.of("zstd")).isEqualTo(CompressionType.ZSTD); assertThat(CompressionType.of("ZStd ")).isEqualTo(CompressionType.ZSTD); assertThat(CompressionType.of("ZSTD")).isEqualTo(CompressionType.ZSTD); int randomKB = 4096; Random random = new Random(); for (int i = 0; i < 5; ++i) { String message = RandomStringUtils.randomAlphanumeric(random.nextInt(randomKB) * 1024); byte[] srcBytes = message.getBytes(StandardCharsets.UTF_8); byte[] compressed = zstd.compress(srcBytes, level); byte[] decompressed = zstd.decompress(compressed); // compression ratio may be negative for some random string data // assertThat(compressed.length).isLessThan(srcBytes.length); assertThat(decompressed).isEqualTo(srcBytes); assertThat(new String(decompressed)).isEqualTo(message); } } @Test public void testCompressionLz4() throws IOException { assertThat(CompressionType.of("lz4")).isEqualTo(CompressionType.LZ4); int randomKB = 4096; Random random = new Random(); for (int i = 0; i < 5; ++i) { String message = RandomStringUtils.randomAlphanumeric(random.nextInt(randomKB) * 1024); byte[] srcBytes = message.getBytes(StandardCharsets.UTF_8); byte[] compressed = lz4.compress(srcBytes, level); byte[] decompressed = lz4.decompress(compressed); // compression ratio may be negative for some random string data // assertThat(compressed.length).isLessThan(srcBytes.length); assertThat(decompressed).isEqualTo(srcBytes); assertThat(new String(decompressed)).isEqualTo(message); } } @Test(expected = RuntimeException.class) public void testCompressionUnsupportedType() { CompressionType.of("snappy"); } }
CompressionTest
java
grpc__grpc-java
binder/src/androidTest/java/io/grpc/binder/HostServices.java
{ "start": 8730, "end": 8837 }
class ____ extends HostService {} /** The second concrete host service */ public static final
HostService1
java
google__dagger
javatests/dagger/internal/codegen/BindsDependsOnSubcomponentValidationTest.java
{ "start": 6515, "end": 6881 }
interface ____"); }); } @Test public void testSetValueBindings() { Source parentComponent = CompilerTests.javaSource( "test.ParentComponent", "package test;", "", "import dagger.Component;", "", "@Component(modules = ParentModule.class)", "
ParentComponent
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlKillStatement.java
{ "start": 1113, "end": 1939 }
enum ____ { CONNECTION, QUERY } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public SQLExpr getThreadId() { return threadIds.get(0); } public void setThreadId(SQLExpr threadId) { if (this.threadIds.isEmpty()) { this.threadIds.add(threadId); return; } this.threadIds.set(0, threadId); } public List<SQLExpr> getThreadIds() { return threadIds; } protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, threadIds); } visitor.endVisit(this); } @Override public List<SQLObject> getChildren() { return Collections.<SQLObject>emptyList(); } }
Type
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/EncryptionS3ClientFactory.java
{ "start": 11536, "end": 12586 }
class ____ of the Keyring provider to instantiate. * @param conf The Configuration object to be passed to the Keyring provider constructor. * @return An instance of the specified Keyring provider. * @throws RuntimeException If unable to create the Keyring provider instance. */ private Keyring getKeyringProvider(String className, Configuration conf) { Class<? extends Keyring> keyringProviderClass = getCustomKeyringProviderClass(className); try { return ReflectionUtils.newInstance(keyringProviderClass, conf); } catch (Exception e) { LOG.warn("Failed to create Keyring provider", e); // This is for testing purposes to support CustomKeyring.java try { return ReflectionUtils.newInstance(keyringProviderClass, conf, new Class[] {Configuration.class}, conf); } catch (Exception ex) { throw new RuntimeException("Failed to create Keyring provider", ex); } } } /** * Retrieves the Class object for the custom Keyring provider based on the provided
name
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpKeyUriConsumeIT.java
{ "start": 1232, "end": 2484 }
class ____ extends SftpServerTestSupport { @Test public void testSftpSimpleConsume() throws Exception { String expected = "Hello World"; // create file using regular file template.sendBodyAndHeader("file://" + service.getFtpRootDir(), expected, Exchange.FILE_NAME, "hello.txt"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedHeaderReceived(Exchange.FILE_NAME, "hello.txt"); mock.expectedBodiesReceived(expected); context.getRouteController().startRoute("foo"); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("sftp://localhost:{{ftp.server.port}}/{{ftp.root.dir}}?username=admin" + "&knownHostsUri=file:" + service.getKnownHostsFile() + "&privateKeyUri=file:./src/test/resources/id_rsa&privateKeyPassphrase=secret&useUserKnownHostsFile=false&delay=10000&disconnect=true") .routeId("foo").noAutoStartup().to("mock:result"); } }; } }
SftpKeyUriConsumeIT
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/qualifiers/RepeatingQualifierClassTest.java
{ "start": 2119, "end": 2344 }
class ____ implements SomePlace { public String ping() { return "home"; } } @Singleton @Location("farAway") @Location("dreamland") @NotAQualifier("ignored") public static
Home
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/ITestAbfsOutputStreamStatistics.java
{ "start": 1623, "end": 10142 }
class ____ extends AbstractAbfsIntegrationTest { private static final int OPERATIONS = 10; private static final Logger LOG = LoggerFactory.getLogger(ITestAbfsOutputStreamStatistics.class); public ITestAbfsOutputStreamStatistics() throws Exception { } /** * Tests to check bytes uploaded successfully in {@link AbfsOutputStream}. */ @Test public void testAbfsOutputStreamUploadingBytes() throws IOException { describe("Testing bytes uploaded successfully by AbfsOutputSteam"); final AzureBlobFileSystem fs = getFileSystem(); Path uploadBytesFilePath = path(getMethodName()); String testBytesToUpload = "bytes"; try ( AbfsOutputStream outForSomeBytes = createAbfsOutputStreamWithFlushEnabled( fs, uploadBytesFilePath) ) { AbfsOutputStreamStatisticsImpl abfsOutputStreamStatisticsForUploadBytes = getAbfsOutputStreamStatistics(outForSomeBytes); //Test for zero bytes To upload. assertEquals(0, abfsOutputStreamStatisticsForUploadBytes.getBytesToUpload(), "Mismatch in bytes to upload"); outForSomeBytes.write(testBytesToUpload.getBytes()); outForSomeBytes.flush(); abfsOutputStreamStatisticsForUploadBytes = getAbfsOutputStreamStatistics(outForSomeBytes); //Test for bytes to upload. assertEquals(testBytesToUpload.getBytes().length, abfsOutputStreamStatisticsForUploadBytes.getBytesToUpload(), "Mismatch in bytes to upload"); //Test for successful bytes uploaded. assertEquals(testBytesToUpload.getBytes().length, abfsOutputStreamStatisticsForUploadBytes.getBytesUploadSuccessful(), "Mismatch in successful bytes uploaded"); } try ( AbfsOutputStream outForLargeBytes = createAbfsOutputStreamWithFlushEnabled( fs, uploadBytesFilePath)) { for (int i = 0; i < OPERATIONS; i++) { outForLargeBytes.write(testBytesToUpload.getBytes()); } outForLargeBytes.flush(); AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outForLargeBytes); //Test for bytes to upload. assertEquals(OPERATIONS * (testBytesToUpload.getBytes().length), abfsOutputStreamStatistics.getBytesToUpload(), "Mismatch in bytes to upload"); //Test for successful bytes uploaded. assertEquals(OPERATIONS * (testBytesToUpload.getBytes().length), abfsOutputStreamStatistics.getBytesUploadSuccessful(), "Mismatch in successful bytes uploaded"); } } /** * Tests to check correct values of queue shrunk operations in * AbfsOutputStream. * * After writing data, AbfsOutputStream doesn't upload the data until * flushed. Hence, flush() method is called after write() to test queue * shrink operations. */ @Test public void testAbfsOutputStreamQueueShrink() throws IOException { describe("Testing queue shrink operations by AbfsOutputStream"); final AzureBlobFileSystem fs = getFileSystem(); Path queueShrinkFilePath = path(getMethodName()); String testQueueShrink = "testQueue"; if (fs.getAbfsStore().isAppendBlobKey(fs.makeQualified(queueShrinkFilePath).toString())) { // writeOperationsQueue is not used for appendBlob, hence queueShrink is 0 return; } try (AbfsOutputStream outForOneOp = createAbfsOutputStreamWithFlushEnabled( fs, queueShrinkFilePath)) { AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outForOneOp); //Test for shrinking queue zero time. assertEquals(0, abfsOutputStreamStatistics.getQueueShrunkOps(), "Mismatch in queue shrunk operations"); } /* * After writing in the loop we flush inside the loop to ensure the write * operation done in that loop is considered to be done which would help * us triggering the shrinkWriteOperationQueue() method each time after * the write operation. * If we call flush outside the loop, then it will take all the write * operations inside the loop as one write operation. * */ try ( AbfsOutputStream outForLargeOps = createAbfsOutputStreamWithFlushEnabled( fs, queueShrinkFilePath)) { for (int i = 0; i < OPERATIONS; i++) { outForLargeOps.write(testQueueShrink.getBytes()); outForLargeOps.flush(); } AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outForLargeOps); /* * After a write operation is done, it is in a task queue where it is * removed. Hence, to get the correct expected value we get the size of * the task queue from AbfsOutputStream and subtract it with total * write operations done to get the number of queue shrinks done. * */ assertEquals(OPERATIONS - outForLargeOps.getWriteOperationsSize(), abfsOutputStreamStatistics.getQueueShrunkOps(), "Mismatch in queue shrunk operations"); } } /** * Tests to check correct values of write current buffer operations done by * AbfsOutputStream. * * After writing data, AbfsOutputStream doesn't upload data till flush() is * called. Hence, flush() calls were made after write(). */ @Test public void testAbfsOutputStreamWriteBuffer() throws IOException { describe("Testing write current buffer operations by AbfsOutputStream"); final AzureBlobFileSystem fs = getFileSystem(); Path writeBufferFilePath = path(getMethodName()); String testWriteBuffer = "Buffer"; try (AbfsOutputStream outForOneOp = createAbfsOutputStreamWithFlushEnabled( fs, writeBufferFilePath)) { AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outForOneOp); //Test for zero time writing buffer to service. assertEquals(0, abfsOutputStreamStatistics.getWriteCurrentBufferOperations(), "Mismatch in write current buffer operations"); outForOneOp.write(testWriteBuffer.getBytes()); outForOneOp.flush(); abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outForOneOp); //Test for one time writing buffer to service. assertEquals(1, abfsOutputStreamStatistics.getWriteCurrentBufferOperations(), "Mismatch in write current buffer operations"); } try ( AbfsOutputStream outForLargeOps = createAbfsOutputStreamWithFlushEnabled( fs, writeBufferFilePath)) { /* * Need to flush each time after we write to actually write the data * into the data store and thus, get the writeCurrentBufferToService() * method triggered and increment the statistic. */ for (int i = 0; i < OPERATIONS; i++) { outForLargeOps.write(testWriteBuffer.getBytes()); outForLargeOps.flush(); } AbfsOutputStreamStatisticsImpl abfsOutputStreamStatistics = getAbfsOutputStreamStatistics(outForLargeOps); //Test for 10 times writing buffer to service. assertEquals(OPERATIONS, abfsOutputStreamStatistics.getWriteCurrentBufferOperations(), "Mismatch in write current buffer operations"); } } /** * Test to check correct value of time spent on a PUT request in * AbfsOutputStream. */ @Test public void testAbfsOutputStreamDurationTrackerPutRequest() throws IOException { describe("Testing to check if DurationTracker for PUT request is working " + "correctly."); AzureBlobFileSystem fs = getFileSystem(); Path pathForPutRequest = path(getMethodName()); try(AbfsOutputStream outputStream = createAbfsOutputStreamWithFlushEnabled(fs, pathForPutRequest)) { outputStream.write('a'); outputStream.hflush(); IOStatistics ioStatistics = extractStatistics(fs); LOG.info("AbfsOutputStreamStats info: {}", ioStatisticsToPrettyString(ioStatistics)); Assertions.assertThat( lookupMeanStatistic(ioStatistics, AbfsStatistic.HTTP_PUT_REQUEST.getStatName() + StoreStatisticNames.SUFFIX_MEAN).mean()) .describedAs("Mismatch in timeSpentOnPutRequest DurationTracker") .isGreaterThan(0.0); } } /** * Method to get the AbfsOutputStream statistics. * * @param out AbfsOutputStream whose statistics is needed. * @return AbfsOutputStream statistics implementation
ITestAbfsOutputStreamStatistics
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/env/YamlTestPropertySourceTests.java
{ "start": 1465, "end": 1978 }
class ____ { @ParameterizedTest @CsvSource(delimiterString = "->", textBlock = """ environments.dev.url -> https://dev.example.com environments.dev.name -> 'Developer Setup' environments.prod.url -> https://prod.example.com environments.prod.name -> 'My Cool App' """) void propertyIsAvailableInEnvironment(String property, String value, @Autowired ConfigurableEnvironment env) { assertThat(env.getProperty(property)).isEqualTo(value); } @Configuration static
YamlTestPropertySourceTests
java
spring-projects__spring-security
config/src/integration-test/java/org/springframework/security/config/ldap/LdapBindAuthenticationManagerFactoryITests.java
{ "start": 6066, "end": 6599 }
class ____ extends BaseLdapServerConfig { static GrantedAuthoritiesMapper AUTHORITIES_MAPPER; @Bean AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) { LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource); factory.setUserDnPatterns("uid={0},ou=people"); factory.setAuthoritiesMapper(AUTHORITIES_MAPPER); return factory.createAuthenticationManager(); } } @Configuration @EnableWebSecurity static
CustomAuthoritiesMapperConfig
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/utils/FederationStateStoreFacade.java
{ "start": 22597, "end": 23180 }
class ____ which a retry proxy is required * @param retryPolicy the policy for retrying method call failures * @param <T> The type of the instance. * @return a retry proxy for the specified interface */ public static <T> Object createRetryInstance(Configuration conf, String configuredClassName, String defaultValue, Class<T> type, RetryPolicy retryPolicy) { return RetryProxy.create(type, createInstance(conf, configuredClassName, defaultValue, type), retryPolicy); } /** * Helper method to create instances of Object using the
for
java
apache__avro
doc/examples/mr-example/src/main/java/example/AvroWordCount.java
{ "start": 1265, "end": 1339 }
class ____ extends Configured implements Tool { public static
AvroWordCount
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/deployment/src/test/java/io/quarkus/restclient/interceptor/RestClientInterceptorTest.java
{ "start": 1969, "end": 2054 }
interface ____ { } @Foo @Priority(1) @Interceptor public static
Foo
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/grant/MySqlGrantTest_11.java
{ "start": 969, "end": 2376 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "GRANT CREATE TABLESPACE ON mydb.* TO 'someuser'@'somehost';"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); String output = SQLUtils.toMySqlString(stmt); assertEquals("GRANT CREATE TABLESPACE ON mydb.* TO 'someuser'@'somehost';", // output); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("City"))); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); // assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); } }
MySqlGrantTest_11
java
apache__dubbo
dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java
{ "start": 4482, "end": 12804 }
class ____ implements MetadataReport { protected static final String DEFAULT_ROOT = "dubbo"; protected static final int ONE_DAY_IN_MILLISECONDS = 60 * 24 * 60 * 1000; private static final int FOUR_HOURS_IN_MILLISECONDS = 60 * 4 * 60 * 1000; // Log output protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are // the list of notified service providers final Properties properties = new Properties(); private final ExecutorService reportCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); final Map<MetadataIdentifier, Object> allMetadataReports = new ConcurrentHashMap<>(4); private final AtomicLong lastCacheChanged = new AtomicLong(); final Map<MetadataIdentifier, Object> failedReports = new ConcurrentHashMap<>(4); private URL reportURL; boolean syncReport; // Local disk cache file File file; private AtomicBoolean initialized = new AtomicBoolean(false); public MetadataReportRetry metadataReportRetry; private ScheduledExecutorService reportTimerScheduler; private final boolean reportMetadata; private final boolean reportDefinition; protected ApplicationModel applicationModel; public AbstractMetadataReport(URL reportServerURL) { setUrl(reportServerURL); applicationModel = reportServerURL.getOrDefaultApplicationModel(); boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true); // Start file save timer String defaultFilename = SystemPropertyConfigUtils.getSystemProperty(USER_HOME) + DUBBO_METADATA + reportServerURL.getApplication() + "-" + replace(reportServerURL.getAddress(), ":", "-") + CACHE; String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename); File file = null; if (localCacheEnabled && ConfigUtils.isNotEmpty(filename)) { file = new File(filename); if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new IllegalArgumentException("Invalid service store file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!"); } } // if this file exists, firstly delete it. if (!initialized.getAndSet(true) && file.exists()) { file.delete(); } } this.file = file; loadProperties(); syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false); metadataReportRetry = new MetadataReportRetry( reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); // cycle report the data switch if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) { reportTimerScheduler = Executors.newSingleThreadScheduledExecutor( new NamedThreadFactory("DubboMetadataReportTimer", true)); reportTimerScheduler.scheduleAtFixedRate( this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); } this.reportMetadata = reportServerURL.getParameter(REPORT_METADATA_KEY, false); this.reportDefinition = reportServerURL.getParameter(REPORT_DEFINITION_KEY, true); } public URL getUrl() { return reportURL; } protected void setUrl(URL url) { if (url == null) { throw new IllegalArgumentException("metadataReport url == null"); } this.reportURL = url; } private void doSaveProperties(long version) { if (version < lastCacheChanged.get()) { return; } if (file == null) { return; } // Save try { File lockfile = new File(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { lockfile.createNewFile(); } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { throw new IOException( "Can not lock the metadataReport cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); } // Save try { if (!file.exists()) { file.createNewFile(); } Properties tmpProperties; if (!syncReport) { // When syncReport = false, properties.setProperty and properties.store are called from the same // thread(reportCacheExecutor), so deep copy is not required tmpProperties = properties; } else { // Using store method and setProperty method of the this.properties will cause lock contention // under multi-threading, so deep copy a new container tmpProperties = new Properties(); Set<Map.Entry<Object, Object>> entries = properties.entrySet(); for (Map.Entry<Object, Object> entry : entries) { tmpProperties.setProperty((String) entry.getKey(), (String) entry.getValue()); } } try (FileOutputStream outputFile = new FileOutputStream(file)) { tmpProperties.store(outputFile, "Dubbo metadataReport Cache"); } } finally { lock.release(); } } } catch (Throwable e) { if (version < lastCacheChanged.get()) { return; } else { reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } logger.warn( COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to save service store file, cause: " + e.getMessage(), e); } } void loadProperties() { if (file != null && file.exists()) { try (InputStream in = new FileInputStream(file)) { properties.load(in); if (logger.isInfoEnabled()) { logger.info("Load service store file " + file + ", data: " + properties); } } catch (Throwable e) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Failed to load service store file" + file, e); } } } private void saveProperties(MetadataIdentifier metadataIdentifier, String value, boolean add, boolean sync) { if (file == null) { return; } try { if (add) { properties.setProperty(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), value); } else { properties.remove(metadataIdentifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); } long version = lastCacheChanged.incrementAndGet(); if (sync) { new SaveProperties(version).run(); } else { reportCacheExecutor.execute(new SaveProperties(version)); } } catch (Throwable t) { logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", t.getMessage(), t); } } @Override public String toString() { return getUrl().toString(); } private
AbstractMetadataReport
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/utils/TracingContext.java
{ "start": 2314, "end": 15688 }
class ____ { private final String clientCorrelationID; // passed over config by client private final String fileSystemID; // GUID for fileSystem instance private String clientRequestId = EMPTY_STRING; // GUID per http request //Optional, non-empty for methods that trigger two or more Store calls private String primaryRequestId; private String streamID; // appears per stream instance (read/write ops) private int retryCount; // retry number as recorded by AbfsRestOperation private FSOperationType opType; // two-lettered code representing Hadoop op private final TracingHeaderFormat format; // header ID display options private Listener listener = null; // null except when testing //final concatenated ID list set into x-ms-client-request-id header private String header = EMPTY_STRING; private String ingressHandler = EMPTY_STRING; private String position = EMPTY_STRING; // position of read/write in remote file private String metricResults = EMPTY_STRING; private String metricHeader = EMPTY_STRING; private ReadType readType = ReadType.UNKNOWN_READ; /** * If {@link #primaryRequestId} is null, this field shall be set equal * to the last part of the {@link #clientRequestId}'s UUID * in {@link #constructHeader(AbfsHttpOperation, String, String)} only on the * first API call for an operation. Subsequent retries for that operation * will not change this field. In case {@link #primaryRequestId} is non-null, * this field shall not be set. */ private String primaryRequestIdForRetry = EMPTY_STRING; private Integer operatedBlobCount = 0; // Only relevant for rename-delete over blob endpoint where it will be explicitly set. private static final Logger LOG = LoggerFactory.getLogger(AbfsClient.class); public static final int MAX_CLIENT_CORRELATION_ID_LENGTH = 72; public static final String CLIENT_CORRELATION_ID_PATTERN = "[a-zA-Z0-9-]*"; /** * Initialize TracingContext * @param clientCorrelationID Provided over config by client * @param fileSystemID Unique guid for AzureBlobFileSystem instance * @param opType Code indicating the high-level Hadoop operation that * triggered the current Store request * @param tracingHeaderFormat Format of IDs to be printed in header and logs * @param listener Holds instance of TracingHeaderValidator during testing, * null otherwise */ public TracingContext(String clientCorrelationID, String fileSystemID, FSOperationType opType, TracingHeaderFormat tracingHeaderFormat, Listener listener) { this.fileSystemID = fileSystemID; this.opType = opType; this.clientCorrelationID = clientCorrelationID; streamID = EMPTY_STRING; retryCount = 0; primaryRequestId = EMPTY_STRING; format = tracingHeaderFormat; this.listener = listener; } public TracingContext(String clientCorrelationID, String fileSystemID, FSOperationType opType, boolean needsPrimaryReqId, TracingHeaderFormat tracingHeaderFormat, Listener listener) { this(clientCorrelationID, fileSystemID, opType, tracingHeaderFormat, listener); primaryRequestId = needsPrimaryReqId ? UUID.randomUUID().toString() : ""; if (listener != null) { listener.updatePrimaryRequestID(primaryRequestId); } } public TracingContext(String clientCorrelationID, String fileSystemID, FSOperationType opType, boolean needsPrimaryReqId, TracingHeaderFormat tracingHeaderFormat, Listener listener, String metricResults) { this(clientCorrelationID, fileSystemID, opType, needsPrimaryReqId, tracingHeaderFormat, listener); this.metricResults = metricResults; } public TracingContext(TracingContext originalTracingContext) { this.fileSystemID = originalTracingContext.fileSystemID; this.streamID = originalTracingContext.streamID; this.clientCorrelationID = originalTracingContext.clientCorrelationID; this.opType = originalTracingContext.opType; this.retryCount = 0; this.primaryRequestId = originalTracingContext.primaryRequestId; this.format = originalTracingContext.format; this.position = originalTracingContext.getPosition(); this.ingressHandler = originalTracingContext.getIngressHandler(); this.operatedBlobCount = originalTracingContext.operatedBlobCount; if (originalTracingContext.listener != null) { this.listener = originalTracingContext.listener.getClone(); } this.metricResults = originalTracingContext.metricResults; this.readType = originalTracingContext.readType; } public static String validateClientCorrelationID(String clientCorrelationID) { if ((clientCorrelationID.length() > MAX_CLIENT_CORRELATION_ID_LENGTH) || (!clientCorrelationID.matches(CLIENT_CORRELATION_ID_PATTERN))) { LOG.debug( "Invalid config provided; correlation id not included in header."); return EMPTY_STRING; } return clientCorrelationID; } public void setPrimaryRequestID() { primaryRequestId = UUID.randomUUID().toString(); if (listener != null) { listener.updatePrimaryRequestID(primaryRequestId); } } public void setStreamID(String stream) { streamID = stream; } public void setOperation(FSOperationType operation) { this.opType = operation; } public int getRetryCount() { return retryCount; } public void setRetryCount(int retryCount) { this.retryCount = retryCount; } public void setListener(Listener listener) { this.listener = listener; } /** * Concatenate all components separated by (:) into a string and set into * X_MS_CLIENT_REQUEST_ID header of the http operation * Following are the components in order of concatenation: * <ul> * <li>version - not present for versions less than v1</li> * <li>clientCorrelationId</li> * <li>clientRequestId</li> * <li>fileSystemId</li> * <li>primaryRequestId</li> * <li>streamId</li> * <li>opType</li> * <li>retryHeader - this contains retryCount, failureReason and retryPolicy underscore separated</li> * <li>ingressHandler</li> * <li>position of read/write in the remote file</li> * <li>operatedBlobCount - number of blobs operated on by this request</li> * <li>operationSpecificHeader - different operation types can publish info relevant to that operation</li> * <li>httpOperationHeader - suffix for network library used</li> * </ul> * @param httpOperation AbfsHttpOperation instance to set header into * connection * @param previousFailure Failure seen before this API trigger on same operation * from AbfsClient. * @param retryPolicyAbbreviation Retry policy used to get retry interval before this * API trigger on same operation from AbfsClient */ public void constructHeader(AbfsHttpOperation httpOperation, String previousFailure, String retryPolicyAbbreviation) { clientRequestId = UUID.randomUUID().toString(); switch (format) { case ALL_ID_FORMAT: header = TracingHeaderVersion.getCurrentVersion() + COLON + clientCorrelationID + COLON + clientRequestId + COLON + fileSystemID + COLON + getPrimaryRequestIdForHeader(retryCount > 0) + COLON + streamID + COLON + opType + COLON + getRetryHeader(previousFailure, retryPolicyAbbreviation) + COLON + ingressHandler + COLON + position + COLON + operatedBlobCount + COLON + getOperationSpecificHeader(opType) + COLON + httpOperation.getTracingContextSuffix(); metricHeader += !(metricResults.trim().isEmpty()) ? metricResults : EMPTY_STRING; break; case TWO_ID_FORMAT: header = TracingHeaderVersion.getCurrentVersion() + COLON + clientCorrelationID + COLON + clientRequestId; metricHeader += !(metricResults.trim().isEmpty()) ? metricResults : EMPTY_STRING; break; default: //case SINGLE_ID_FORMAT header = TracingHeaderVersion.getCurrentVersion() + COLON + clientRequestId; metricHeader += !(metricResults.trim().isEmpty()) ? metricResults : EMPTY_STRING; } if (listener != null) { //for testing listener.callTracingHeaderValidator(header, format); } httpOperation.setRequestProperty(HttpHeaderConfigurations.X_MS_CLIENT_REQUEST_ID, header); if (!metricHeader.equals(EMPTY_STRING)) { httpOperation.setRequestProperty(HttpHeaderConfigurations.X_MS_FECLIENT_METRICS, metricHeader); } /* * In case the primaryRequestId is an empty-string and if it is the first try to * API call (previousFailure shall be null), maintain the last part of clientRequestId's * UUID in primaryRequestIdForRetry. This field shall be used as primaryRequestId part * of the x-ms-client-request-id header in case of retry of the same API-request. */ if (primaryRequestId.isEmpty() && previousFailure == null) { String[] clientRequestIdParts = clientRequestId.split(String.valueOf(CHAR_HYPHEN)); primaryRequestIdForRetry = clientRequestIdParts[ clientRequestIdParts.length - 1]; } } /** * Provide value to be used as primaryRequestId part of x-ms-client-request-id header. * @param isRetry define if it's for a retry case. * @return {@link #primaryRequestIdForRetry}:If the {@link #primaryRequestId} * is an empty-string, and it's a retry iteration. * {@link #primaryRequestId} for other cases. */ private String getPrimaryRequestIdForHeader(final Boolean isRetry) { if (!primaryRequestId.isEmpty() || !isRetry) { return primaryRequestId; } return primaryRequestIdForRetry; } /** * Get the retry header string in format retryCount_failureReason_retryPolicyAbbreviation * retryCount is always there and 0 for first request. * failureReason is null for first request * retryPolicyAbbreviation is only present when request fails with ConnectionTimeout * @param previousFailure Previous failure reason, null if not a retried request * @param retryPolicyAbbreviation Abbreviation of retry policy used to get retry interval * @return String representing the retry header */ private String getRetryHeader(final String previousFailure, String retryPolicyAbbreviation) { String retryHeader = String.format("%d", retryCount); if (previousFailure == null) { return retryHeader; } if (CONNECTION_TIMEOUT_ABBREVIATION.equals(previousFailure) && retryPolicyAbbreviation != null) { return String.format("%s_%s_%s", retryHeader, previousFailure, retryPolicyAbbreviation); } return String.format("%s_%s", retryHeader, previousFailure); } /** * Get the operation specific header for the current operation type. * @param opType The operation type for which the header is needed * @return String representing the operation specific header */ private String getOperationSpecificHeader(FSOperationType opType) { // Similar header can be added for other operations in the future. switch (opType) { case READ: return getReadSpecificHeader(); default: return EMPTY_STRING; // no operation specific header } } /** * Get the operation specific header for read operations. * @return String representing the read specific header */ private String getReadSpecificHeader() { // More information on read can be added to this header in the future. // As underscore separated values. String readHeader = String.format("%s", readType.toString()); return readHeader; } public void setOperatedBlobCount(Integer count) { operatedBlobCount = count; } public FSOperationType getOpType() { return opType; } /** * Return header representing the request associated with the tracingContext * @return Header string set into X_MS_CLIENT_REQUEST_ID */ public String getHeader() { return header; } /** * Gets the ingress handler. * * @return the ingress handler as a String. */ public String getIngressHandler() { return ingressHandler; } /** * Gets the position. * * @return the position as a String. */ public String getPosition() { return position; } /** * Sets the ingress handler. * * @param ingressHandler the ingress handler to set, must not be null. */ public void setIngressHandler(final String ingressHandler) { this.ingressHandler = ingressHandler; if (listener != null) { listener.updateIngressHandler(ingressHandler); } } /** * Sets the position. * * @param position the position to set, must not be null. */ public void setPosition(final String position) { this.position = position; if (listener != null) { listener.updatePosition(position); } } /** * Sets the read type for the current operation. * @param readType the read type to set, must not be null. */ public void setReadType(ReadType readType) { this.readType = readType; if (listener != null) { listener.updateReadType(readType); } } /** * Returns the read type for the current operation. * * @return the read type for the request. */ public ReadType getReadType() { return readType; } }
TracingContext
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/TestUnwrapped.java
{ "start": 2566, "end": 2768 }
class ____ { public String street; public String addon; public String zip; public String town; public String country; } // [databind#2088] static
Address
java
apache__flink
flink-datastream/src/test/java/org/apache/flink/datastream/impl/stream/StreamTestUtils.java
{ "start": 3847, "end": 4838 }
class ____ implements TwoOutputStreamProcessFunction<Integer, Integer, Long> { private final Set<StateDeclaration> stateDeclarationSet; public NoOpTwoOutputStreamProcessFunction(Set<StateDeclaration> stateDeclarationSet) { this.stateDeclarationSet = stateDeclarationSet; } public NoOpTwoOutputStreamProcessFunction() { this(new HashSet<>()); } @Override public Set<StateDeclaration> usesStates() { return stateDeclarationSet; } @Override public void processRecord( Integer record, Collector<Integer> output1, Collector<Long> output2, TwoOutputPartitionedContext<Integer, Long> ctx) { // do nothing. } } /** * An implementation of the {@link TwoInputNonBroadcastStreamProcessFunction} that does nothing. */ public static
NoOpTwoOutputStreamProcessFunction
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/util/TrustManagerFactoryWrapper.java
{ "start": 843, "end": 1397 }
class ____ extends SimpleTrustManagerFactory { private final TrustManager tm; public TrustManagerFactoryWrapper(TrustManager tm) { this.tm = ObjectUtil.checkNotNull(tm, "tm"); } @Override protected void engineInit(KeyStore keyStore) throws Exception { } @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws Exception { } @Override protected TrustManager[] engineGetTrustManagers() { return new TrustManager[] {tm}; } }
TrustManagerFactoryWrapper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
{ "start": 127280, "end": 128133 }
class ____ { public int foo(Suit suit) { int x = 0; x = switch (suit) { case HEART, DIAMOND -> x + 1; case SPADE -> throw new RuntimeException(); case CLUB -> throw new NullPointerException(); case null -> throw new IllegalArgumentException(); }; return x; } } """) .setArgs( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion", "-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion=false") .setFixChooser(FixChoosers.SECOND) .doTest(TEXT_MATCH); } @Test public void switchByEnum_canRemoveDefault_error() { // Switch contain all
Test
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java
{ "start": 18292, "end": 19380 }
class ____ { String string() { return null; } Mono<String> monoString() { return null; } @ModelAttribute("myString") String stringWithAnnotation() { return null; } Rendering rendering() { return null; } Mono<Rendering> monoRendering() { return null; } FragmentsRendering fragmentsRendering() { return null; } Flux<Fragment> fragmentFlux() { return null; } Flux<ServerSentEvent<Fragment>> fragmentServerSentEventFlux() { return null; } Mono<List<Fragment>> monoFragmentList() { return null; } List<Fragment> fragmentList() { return null; } View view() { return null; } Mono<View> monoView() { return null; } void voidMethod() { } Mono<Void> monoVoid() { return null; } Completable completable() { return null; } Model model() { return null; } Map<?,?> map() { return null; } @ModelAttribute("myMap") Map<?,?> mapWithAnnotation() { return null; } TestBean testBean() { return null; } Long longValue() { return null; } @ModelAttribute("myLong") Long longModelAttribute() { return null; } Mono<?> monoWildcard() { return null; } } }
Handler
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/ProcessorErrorHandler.java
{ "start": 4640, "end": 5155 }
class ____ { static HiltError of(String message) { return of(message, Optional.empty()); } static HiltError of(String message, XElement element) { return of(message, Optional.of(element)); } private static HiltError of(String message, Optional<XElement> element) { return new AutoValue_ProcessorErrorHandler_HiltError( FAILURE_PREFIX + message + FAILURE_SUFFIX, element); } abstract String message(); abstract Optional<XElement> element(); } }
HiltError
java
google__error-prone
core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessInferenceTest.java
{ "start": 20005, "end": 20091 }
interface ____<T extends @Nullable Object> { T get(); }
NullableElementCollection
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/updatemethods/ErroneousOrganizationMapper2.java
{ "start": 410, "end": 1136 }
interface ____ { ErroneousOrganizationMapper2 INSTANCE = Mappers.getMapper( ErroneousOrganizationMapper2.class ); @Mapping(target = "type", constant = "commercial") void toOrganizationEntity(OrganizationDto dto, @MappingTarget OrganizationWithoutTypeGetterEntity entity); void toCompanyEntity(CompanyDto dto, @MappingTarget CompanyEntity entity); @Mapping(target = "type", source = "type") void toName(String type, @MappingTarget OrganizationTypeEntity entity); @Mappings({ @Mapping( target = "employees", ignore = true ), @Mapping( target = "secretaryToEmployee", ignore = true ) }) DepartmentEntity toDepartmentEntity(DepartmentDto dto);
ErroneousOrganizationMapper2