proj_name stringclasses 131
values | relative_path stringlengths 30 228 | class_name stringlengths 1 68 | func_name stringlengths 1 48 | masked_class stringlengths 78 9.82k | func_body stringlengths 46 9.61k | len_input int64 29 2.01k | len_output int64 14 1.94k | total int64 55 2.05k | relevant_context stringlengths 0 38.4k |
|---|---|---|---|---|---|---|---|---|---|
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/jpa/JpaJobConfiguration.java | JpaJobConfiguration | job | class JpaJobConfiguration {
@Bean
public JpaPagingItemReader<CustomerCredit> itemReader(EntityManagerFactory entityManagerFactory) {
return new JpaPagingItemReaderBuilder<CustomerCredit>().name("itemReader")
.entityManagerFactory(entityManagerFactory)
.queryString("select c from CustomerCredit c")
.build(... |
return new JobBuilder("ioSampleJob", jobRepository)
.start(new StepBuilder("step1", jobRepository)
.<CustomerCredit, CustomerCredit>chunk(2, jpaTransactionManager)
.reader(itemReader)
.processor(new CustomerCreditIncreaseProcessor())
.writer(itemWriter)
.build())
.build();
| 460 | 94 | 554 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/jpa/JpaRepositoryJobConfiguration.java | JpaRepositoryJobConfiguration | entityManagerFactory | class JpaRepositoryJobConfiguration {
@Bean
@StepScope
public RepositoryItemReader<CustomerCredit> itemReader(@Value("#{jobParameters['credit']}") Double credit,
CustomerCreditPagingAndSortingRepository repository) {
return new RepositoryItemReaderBuilder<CustomerCredit>().name("itemReader")
.pageSize(2)
... |
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setPersistenceUnitManager(persistenceUnitManager);
factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factoryBean.afterPropertiesSet();
return... | 519 | 95 | 614 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/launch/DefaultJobLoader.java | DefaultJobLoader | setProperty | class DefaultJobLoader implements JobLoader, ApplicationContextAware {
private ListableJobLocator registry;
private ApplicationContext applicationContext;
private final Map<String, String> configurations = new HashMap<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throw... |
int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(path);
BeanWrapperImpl wrapper = createBeanWrapper(path, index);
String key = path.substring(index + 1);
wrapper.setPropertyValue(key, value);
| 646 | 67 | 713 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loom/JobConfigurationForAsynchronousItemProcessingWithVirtualThreads.java | JobConfigurationForAsynchronousItemProcessingWithVirtualThreads | itemProcessor | class JobConfigurationForAsynchronousItemProcessingWithVirtualThreads {
@Bean
public ItemReader<Integer> itemReader() {
return new ListItemReader<>(Arrays.asList(0, 1, 2, 3, 4, 5));
}
@Bean
public AsyncItemProcessor<Integer, Integer> itemProcessor() {<FILL_FUNCTION_BODY>}
@Bean
public AsyncItemWriter<Intege... |
AsyncItemProcessor<Integer, Integer> asyncItemProcessor = new AsyncItemProcessor<>();
asyncItemProcessor.setDelegate(item -> {
System.out.println(Thread.currentThread() + ": processing item " + item);
return item + 1;
});
asyncItemProcessor.setTaskExecutor(new VirtualThreadTaskExecutor("spring-batch-"));... | 333 | 101 | 434 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loom/JobConfigurationForLaunchingJobsWithVirtualThreads.java | JobConfigurationForLaunchingJobsWithVirtualThreads | job | class JobConfigurationForLaunchingJobsWithVirtualThreads {
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager) {<FILL_FUNCTION_BODY>}
@Bean
public TaskExecutor taskExecutor() {
return new VirtualThreadTaskExecutor("spring-batch-");
}
} |
Step step = new StepBuilder("step", jobRepository).tasklet((contribution, chunkContext) -> {
String message = Thread.currentThread() + ": Hello virtual threads world!";
contribution.getStepExecution().getJobExecution().getExecutionContext().put("message", message);
return RepeatStatus.FINISHED;
}, transac... | 80 | 112 | 192 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loom/JobConfigurationForRunningConcurrentStepsWithVirtualThreads.java | JobConfigurationForRunningConcurrentStepsWithVirtualThreads | job | class JobConfigurationForRunningConcurrentStepsWithVirtualThreads {
@Bean
public ItemReader<Integer> itemReader() {
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6)) {
final Lock lock = new ReentrantLock();
@Override
public Integer read() {
this.lock.lock();
try {
Integer item = s... |
Step step = new StepBuilder("step", jobRepository).<Integer, Integer>chunk(2, transactionManager)
.reader(itemReader)
.writer(itemWriter)
.taskExecutor(new VirtualThreadTaskExecutor("spring-batch-"))
.build();
return new JobBuilder("job", jobRepository).start(step).build();
| 286 | 87 | 373 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loom/JobConfigurationForRunningParallelStepsWithVirtualThreads.java | JobConfigurationForRunningParallelStepsWithVirtualThreads | job | class JobConfigurationForRunningParallelStepsWithVirtualThreads {
@Bean
public Step step1(JobRepository jobRepository, JdbcTransactionManager transactionManager) {
return createStep("step1", jobRepository, transactionManager);
}
@Bean
public Step step2(JobRepository jobRepository, JdbcTransactionManager transa... |
Flow flow1 = new FlowBuilder<Flow>("subflow1").from(step1).end();
Flow flow2 = new FlowBuilder<Flow>("subflow2").from(step2).end();
Flow splitFlow = new FlowBuilder<Flow>("splitflow").split(new VirtualThreadTaskExecutor("spring-batch-"))
.add(flow1, flow2)
.build();
return new JobBuilder("job", jobRepo... | 227 | 122 | 349 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loom/JobConfigurationForRunningPartitionedStepsWithVirtualThreads.java | JobConfigurationForRunningPartitionedStepsWithVirtualThreads | tasklet | class JobConfigurationForRunningPartitionedStepsWithVirtualThreads {
@Bean
public Step managerStep(JobRepository jobRepository, Step workerStep, Partitioner partitioner) {
return new StepBuilder("managerStep", jobRepository).partitioner(workerStep.getName(), partitioner)
.step(workerStep)
.gridSize(4)
.ta... |
return (contribution, chunkContext) -> {
System.out.println(Thread.currentThread() + ": processing partition " + partitionData);
return RepeatStatus.FINISHED;
};
| 373 | 55 | 428 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loom/JobConfigurationForRunningSystemCommandTaskletsWithVirtualThreads.java | JobConfigurationForRunningSystemCommandTaskletsWithVirtualThreads | tasklet | class JobConfigurationForRunningSystemCommandTaskletsWithVirtualThreads {
@Bean
public SystemCommandTasklet tasklet() {<FILL_FUNCTION_BODY>}
@Bean
public Job job(JobRepository jobRepository, JdbcTransactionManager transactionManager, SystemCommandTasklet tasklet)
throws Exception {
Step step = new StepBuilde... |
SystemCommandTasklet systemCommandTasklet = new SystemCommandTasklet();
systemCommandTasklet.setCommand("java", "-version");
systemCommandTasklet.setCommandRunner(new JvmCommandRunner() {
@Override
public Process exec(String[] command, String[] envp, File dir) throws IOException {
System.out.println(Th... | 124 | 177 | 301 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/loop/LimitDecider.java | LimitDecider | decide | class LimitDecider implements JobExecutionDecider {
private int count = 0;
private int limit = 1;
@Override
public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecution stepExecution) {<FILL_FUNCTION_BODY>}
/**
* @param limit number of times to return "CONTINUE"
*/
public void setL... |
if (++count >= limit) {
return new FlowExecutionStatus("COMPLETED");
}
else {
return new FlowExecutionStatus("CONTINUE");
}
| 109 | 47 | 156 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mail/TestMailSender.java | TestMailSender | send | class TestMailSender implements MailSender {
private List<String> subjectsToFail = new ArrayList<>();
private final List<SimpleMailMessage> received = new ArrayList<>();
public void clear() {
received.clear();
}
@Override
public void send(SimpleMailMessage simpleMessage) throws MailException {
throw new U... |
Map<Object, Exception> failedMessages = new LinkedHashMap<>();
for (SimpleMailMessage simpleMessage : simpleMessages) {
if (subjectsToFail.contains(simpleMessage.getSubject())) {
failedMessages.put(simpleMessage, new MessagingException());
}
else {
received.add(simpleMessage);
}
}
if (!fail... | 193 | 117 | 310 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mail/UserMailItemProcessor.java | UserMailItemProcessor | process | class UserMailItemProcessor implements ItemProcessor<User, SimpleMailMessage> {
/**
* @see org.springframework.batch.item.ItemProcessor#process(java.lang.Object)
*/
@Nullable
@Override
public SimpleMailMessage process(User user) throws Exception {<FILL_FUNCTION_BODY>}
} |
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(user.getEmail());
message.setFrom("communications@thecompany.com");
message.setSubject(user.getName() + "'s Account Info");
message.setSentDate(new Date());
message.setText("Hello " + user.getName());
return message;
| 81 | 94 | 175 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/metrics/Job1Configuration.java | Job1Configuration | step2 | class Job1Configuration {
private final Random random;
public Job1Configuration() {
this.random = new Random();
}
@Bean
public Job job1(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("job1", jobRepository).start(step1(jobRepository, transactionManager))
... |
return new StepBuilder("step2", jobRepository).tasklet((contribution, chunkContext) -> {
System.out.println("world");
// simulate step failure
int nextInt = random.nextInt(3000);
Thread.sleep(nextInt);
if (nextInt % 5 == 0) {
throw new Exception("Boom!");
}
return RepeatStatus.FINISHED;
},... | 239 | 118 | 357 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/metrics/Job2Configuration.java | Job2Configuration | itemReader | class Job2Configuration {
private final Random random;
public Job2Configuration() {
this.random = new Random();
}
@Bean
public Job job2(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("job2", jobRepository).start(step(jobRepository, transactionManager)).bu... |
List<Integer> items = new LinkedList<>();
// read a random number of items in each run
for (int i = 0; i < random.nextInt(100); i++) {
items.add(i);
}
return new ListItemReader<>(items);
| 301 | 76 | 377 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/metrics/JobScheduler.java | JobScheduler | launchJob1 | class JobScheduler {
private final Job job1;
private final Job job2;
private final JobLauncher jobLauncher;
@Autowired
public JobScheduler(Job job1, Job job2, JobLauncher jobLauncher) {
this.job1 = job1;
this.job2 = job2;
this.jobLauncher = jobLauncher;
}
@Scheduled(cron = "*/10 * * * * *")
public vo... |
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(job1, jobParameters);
| 218 | 51 | 269 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/metrics/PrometheusConfiguration.java | PrometheusConfiguration | init | class PrometheusConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(PrometheusConfiguration.class);
@Value("${prometheus.job.name}")
private String prometheusJobName;
@Value("${prometheus.grouping.key}")
private String prometheusGroupingKey;
@Value("${prometheus.pushgateway.url}")
pr... |
pushGateway = new PushGateway(prometheusPushGatewayUrl);
groupingKey.put(prometheusGroupingKey, prometheusJobName);
PrometheusMeterRegistry prometheusMeterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
collectorRegistry = prometheusMeterRegistry.getPrometheusRegistry();
Metrics.globalRegis... | 282 | 118 | 400 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/jmx/InfiniteLoopWriter.java | InfiniteLoopWriter | write | class InfiniteLoopWriter implements StepExecutionListener, ItemWriter<Object> {
private static final Log LOG = LogFactory.getLog(InfiniteLoopWriter.class);
private StepExecution stepExecution;
private int count = 0;
/**
* @see org.springframework.batch.core.StepExecutionListener#beforeStep(StepExecution)
*/... |
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Job interrupted.", e);
}
stepExecution.setWriteCount(++count);
if (LOG.isInfoEnabled()) {
LOG.info("Executing infinite loop, at count=" + count);
}
| 160 | 108 | 268 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/jmx/JobExecutionNotificationPublisher.java | JobExecutionNotificationPublisher | publish | class JobExecutionNotificationPublisher
implements ApplicationListener<SimpleMessageApplicationEvent>, NotificationPublisherAware {
private static final Log LOG = LogFactory.getLog(JobExecutionNotificationPublisher.class);
private NotificationPublisher notificationPublisher;
private int notificationCount = 0;
... |
if (notificationPublisher != null) {
Notification notification = new Notification("JobExecutionApplicationEvent", this, notificationCount++,
message);
/*
* We can't create a notification with a null source, but we can set it to
* null after creation(!). We want it to be null so that Spring will re... | 338 | 134 | 472 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/jmx/SimpleMessageApplicationEvent.java | SimpleMessageApplicationEvent | toString | class SimpleMessageApplicationEvent extends ApplicationEvent {
private final String message;
public SimpleMessageApplicationEvent(Object source, String message) {
super(source);
this.message = message;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "message=[" + message + "], " + super.toString();
| 75 | 21 | 96 | <methods>public void <init>(java.lang.Object) ,public void <init>(java.lang.Object, java.time.Clock) ,public final long getTimestamp() <variables>private static final long serialVersionUID,private final long timestamp |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/quartz/JobLauncherDetails.java | JobLauncherDetails | getJobParametersFromJobMap | class JobLauncherDetails extends QuartzJobBean {
/**
* Special key in job data map for the name of a job to run.
*/
static final String JOB_NAME = "jobName";
private static final Log log = LogFactory.getLog(JobLauncherDetails.class);
private JobLocator jobLocator;
private JobLauncher jobLauncher;
/**
*... |
JobParametersBuilder builder = new JobParametersBuilder();
for (Entry<String, Object> entry : jobDataMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String && !key.equals(JOB_NAME)) {
builder.addString(key, (String) value);
}
else if (value ... | 486 | 237 | 723 | <methods>public void <init>() ,public final void execute(org.quartz.JobExecutionContext) throws org.quartz.JobExecutionException<variables> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mongodb/DeletionJobConfiguration.java | DeletionJobConfiguration | deletionStep | class DeletionJobConfiguration {
@Bean
public MongoItemReader<Person> mongoPersonReader(MongoTemplate mongoTemplate) {
Map<String, Sort.Direction> sortOptions = new HashMap<>();
sortOptions.put("name", Sort.Direction.DESC);
return new MongoItemReaderBuilder<Person>().name("personItemReader")
.collection("pe... |
return new StepBuilder("step", jobRepository).<Person, Person>chunk(2, transactionManager)
.reader(mongoPersonReader)
.writer(mongoPersonRemover)
.build();
| 338 | 54 | 392 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mongodb/InsertionJobConfiguration.java | InsertionJobConfiguration | mongoItemReader | class InsertionJobConfiguration {
@Bean
public MongoItemReader<Person> mongoItemReader(MongoTemplate mongoTemplate) {<FILL_FUNCTION_BODY>}
@Bean
public MongoItemWriter<Person> mongoItemWriter(MongoTemplate mongoTemplate) {
return new MongoItemWriterBuilder<Person>().template(mongoTemplate).collection("person_ou... |
Map<String, Sort.Direction> sortOptions = new HashMap<>();
sortOptions.put("name", Sort.Direction.DESC);
return new MongoItemReaderBuilder<Person>().name("personItemReader")
.collection("person_in")
.targetType(Person.class)
.template(mongoTemplate)
.jsonQuery("{}")
.sorts(sortOptions)
.build()... | 246 | 108 | 354 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mongodb/MongoDBConfiguration.java | MongoDBConfiguration | mongoClient | class MongoDBConfiguration {
@Value("${mongodb.host}")
private String mongodbHost;
@Value("${mongodb.port}")
private int mongodbPort;
@Value("${mongodb.database}")
private String mongodbDatabase;
@Bean
public MongoClient mongoClient() {<FILL_FUNCTION_BODY>}
@Bean
public MongoTemplate mongoTemplate(MongoC... |
String connectionString = "mongodb://" + this.mongodbHost + ":" + this.mongodbPort + "/" + this.mongodbDatabase;
return MongoClients.create(connectionString);
| 216 | 53 | 269 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mongodb/MongoDBSampleApp.java | MongoDBSampleApp | main | class MongoDBSampleApp {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
} |
Class<?>[] configurationClasses = { InsertionJobConfiguration.class, DeletionJobConfiguration.class,
MongoDBConfiguration.class };
ApplicationContext context = new AnnotationConfigApplicationContext(configurationClasses);
MongoTemplate mongoTemplate = context.getBean(MongoTemplate.class);
// clear collect... | 37 | 495 | 532 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/mongodb/Person.java | Person | toString | class Person {
private String id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getId() {
return id;
}
// setter used for data binding if items to delete (with known IDs)
// are read from a flat file for example
public void setId(String id) ... |
return "Person{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}';
| 169 | 33 | 202 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/BasicPartitioner.java | BasicPartitioner | partition | class BasicPartitioner extends SimplePartitioner {
private static final String PARTITION_KEY = "partition";
@Override
public Map<String, ExecutionContext> partition(int gridSize) {<FILL_FUNCTION_BODY>}
} |
Map<String, ExecutionContext> partitions = super.partition(gridSize);
int i = 0;
for (ExecutionContext context : partitions.values()) {
context.put(PARTITION_KEY, PARTITION_KEY + (i++));
}
return partitions;
| 60 | 72 | 132 | <methods>public non-sealed void <init>() ,public Map<java.lang.String,org.springframework.batch.item.ExecutionContext> partition(int) <variables>private static final java.lang.String PARTITION_KEY |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/DataSourceConfiguration.java | DataSourceConfiguration | dataSource | class DataSourceConfiguration {
@Value("${datasource.url}")
private String url;
@Value("${datasource.username}")
private String username;
@Value("${datasource.password}")
private String password;
@Bean
public DataSource dataSource() {<FILL_FUNCTION_BODY>}
@Bean
public JdbcTransactionManager transactionMa... |
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
| 123 | 57 | 180 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/aggregating/ManagerConfiguration.java | ManagerConfiguration | managerStep | class ManagerConfiguration {
private static final int GRID_SIZE = 3;
private final RemotePartitioningManagerStepBuilderFactory managerStepBuilderFactory;
public ManagerConfiguration(RemotePartitioningManagerStepBuilderFactory managerStepBuilderFactory) {
this.managerStepBuilderFactory = managerStepBuilderFacto... |
return this.managerStepBuilderFactory.get("managerStep")
.partitioner("workerStep", new BasicPartitioner())
.gridSize(GRID_SIZE)
.outputChannel(requests())
.inputChannel(replies())
.build();
| 358 | 66 | 424 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/aggregating/WorkerConfiguration.java | WorkerConfiguration | tasklet | class WorkerConfiguration {
private final RemotePartitioningWorkerStepBuilderFactory workerStepBuilderFactory;
public WorkerConfiguration(RemotePartitioningWorkerStepBuilderFactory workerStepBuilderFactory) {
this.workerStepBuilderFactory = workerStepBuilderFactory;
}
/*
* Configure inbound flow (requests co... |
return (contribution, chunkContext) -> {
System.out.println("processing " + partition);
return RepeatStatus.FINISHED;
};
| 398 | 45 | 443 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/polling/WorkerConfiguration.java | WorkerConfiguration | tasklet | class WorkerConfiguration {
private final RemotePartitioningWorkerStepBuilderFactory workerStepBuilderFactory;
public WorkerConfiguration(RemotePartitioningWorkerStepBuilderFactory workerStepBuilderFactory) {
this.workerStepBuilderFactory = workerStepBuilderFactory;
}
/*
* Configure inbound flow (requests co... |
return (contribution, chunkContext) -> {
System.out.println("processing " + partition);
return RepeatStatus.FINISHED;
};
| 285 | 45 | 330 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/retry/RetrySampleConfiguration.java | RetrySampleConfiguration | step | class RetrySampleConfiguration {
@Bean
public Job retrySample(JobRepository jobRepository, Step step) {
return new JobBuilder("retrySample", jobRepository).start(step).build();
}
@Bean
protected Step step(JobRepository jobRepository, JdbcTransactionManager transactionManager) {<FILL_FUNCTION_BODY>}
@Bean
pr... |
return new StepBuilder("step", jobRepository).<Trade, Object>chunk(1, transactionManager)
.reader(reader())
.writer(writer())
.faultTolerant()
.retry(Exception.class)
.retryLimit(3)
.build();
| 171 | 76 | 247 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/skip/SkippableExceptionDuringProcessSample.java | SkippableExceptionDuringProcessSample | itemReader | class SkippableExceptionDuringProcessSample {
private final PlatformTransactionManager transactionManager;
public SkippableExceptionDuringProcessSample(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Bean
public ItemReader<Integer> itemReader() {<FILL_FUNCTION... |
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6)) {
@Override
public Integer read() {
Integer item = super.read();
System.out.println("reading item = " + item);
return item;
}
};
| 390 | 84 | 474 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/skip/SkippableExceptionDuringReadSample.java | SkippableExceptionDuringReadSample | itemReader | class SkippableExceptionDuringReadSample {
private final PlatformTransactionManager transactionManager;
public SkippableExceptionDuringReadSample(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Bean
public ItemReader<Integer> itemReader() {<FILL_FUNCTION_BODY>... |
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6)) {
@Override
public Integer read() {
Integer item = super.read();
System.out.println("reading item = " + item);
if (item != null && item.equals(5)) {
System.out.println("Throwing exception on item " + item);
throw new IllegalArgu... | 343 | 137 | 480 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/skip/SkippableExceptionDuringWriteSample.java | SkippableExceptionDuringWriteSample | read | class SkippableExceptionDuringWriteSample {
private final PlatformTransactionManager transactionManager;
public SkippableExceptionDuringWriteSample(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Bean
public ItemReader<Integer> itemReader() {
return new List... |
Integer item = super.read();
System.out.println("reading item = " + item);
return item;
| 440 | 34 | 474 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/support/ExceptionThrowingItemReaderProxy.java | ExceptionThrowingItemReaderProxy | read | class ExceptionThrowingItemReaderProxy<T> implements ItemReader<T> {
private int counter = 0;
private int throwExceptionOnRecordNumber = 4;
private ItemReader<T> delegate;
/**
* @param throwExceptionOnRecordNumber The number of record on which exception should
* be thrown
*/
public void setThrowException... |
counter++;
if (counter == throwExceptionOnRecordNumber) {
throw new UnexpectedJobExecutionException("Planned failure on count=" + counter);
}
return delegate.read();
| 170 | 56 | 226 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/support/HeaderCopyCallback.java | HeaderCopyCallback | handleLine | class HeaderCopyCallback implements LineCallbackHandler, FlatFileHeaderCallback {
private String header = "";
@Override
public void handleLine(String line) {<FILL_FUNCTION_BODY>}
@Override
public void writeHeader(Writer writer) throws IOException {
writer.write("header from input: " + header);
}
} |
Assert.notNull(line, "line must not be null");
this.header = line;
| 85 | 28 | 113 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/support/RetrySampleItemWriter.java | RetrySampleItemWriter | write | class RetrySampleItemWriter<T> implements ItemWriter<T> {
private int counter = 0;
@Override
public void write(Chunk<? extends T> items) throws Exception {<FILL_FUNCTION_BODY>}
/**
* @return number of times {@link #write(Chunk)} method was called.
*/
public int getCounter() {
return counter;
}
} |
int current = counter;
counter += items.size();
if (current < 3 && (counter >= 2 || counter >= 3)) {
throw new IllegalStateException("Temporary error");
}
| 101 | 53 | 154 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/support/SummaryFooterCallback.java | SummaryFooterCallback | writeFooter | class SummaryFooterCallback implements StepExecutionListener, FlatFileFooterCallback {
private StepExecution stepExecution;
@Override
public void writeFooter(Writer writer) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecut... |
writer.write("footer - number of items written: " + stepExecution.getWriteCount());
| 85 | 26 | 111 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/validation/ValidationSampleConfiguration.java | ValidationSampleConfiguration | itemReader | class ValidationSampleConfiguration {
@Bean
public ListItemReader<Person> itemReader() {<FILL_FUNCTION_BODY>}
@Bean
public ListItemWriter<Person> itemWriter() {
return new ListItemWriter<>();
}
@Bean
public BeanValidatingItemProcessor<Person> itemValidator() throws Exception {
BeanValidatingItemProcessor<... |
Person person1 = new Person(1, "foo");
Person person2 = new Person(2, "");
return new ListItemReader<>(Arrays.asList(person1, person2));
| 259 | 53 | 312 | <no_super_class> |
spring-projects_spring-batch | spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/validation/domain/Person.java | Person | toString | class Person {
private int id;
@NotEmpty
private String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setN... |
return "Person{" + "id=" + id + ", name='" + name + '\'' + '}';
| 156 | 30 | 186 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/javastack-spring-boot-starter-sample/src/main/java/cn/javastack/springboot/starter/sample/Application.java | Application | commandLineRunner | class Application {
@Value("${debug}")
private boolean debug;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner commandLineRunner(TestService testService) {<FILL_FUNCTION_BODY>}
} |
return (args) -> {
log.info("debug mode: {}", debug);
log.info(testService.getServiceName());
};
| 84 | 41 | 125 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-actuator/src/main/java/cn/javastack/springboot/actuator/SecurityConfig.java | SecurityConfig | securityFilterChain | class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
@Bean
protected UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(Use... |
return http.authorizeHttpRequests((authorize) -> {
authorize.requestMatchers("/").permitAll()
.requestMatchers(EndpointRequest.to("health")).hasRole("ENDPOINT_ADMIN")
.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll();
... | 161 | 154 | 315 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-actuator/src/main/java/cn/javastack/springboot/actuator/endpoint/TestEndpoint.java | TestEndpoint | updateUser | class TestEndpoint {
@ReadOperation
public User getUser(@Selector Integer id) {
return new User(id, "james", 18);
}
@WriteOperation
public User updateUser(int id, @Nullable String name, @Nullable Integer age) {<FILL_FUNCTION_BODY>}
} |
User user = getUser(id);
user.setName(StringUtils.defaultIfBlank(name, user.getName()));
user.setAge(ObjectUtils.defaultIfNull(age, user.getAge()));
return user;
| 84 | 62 | 146 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-actuator/src/main/java/cn/javastack/springboot/actuator/observation/IndexObservation.java | IndexObservation | observe | class IndexObservation {
private final ObservationRegistry observationRegistry;
public void observe() {<FILL_FUNCTION_BODY>}
} |
Observation.createNotStarted("indexObservation", this.observationRegistry)
.lowCardinalityKeyValue("area", "cn")
.highCardinalityKeyValue("userId", "10099")
.observe(() -> {
// 执行观测时的业务逻辑
log.info("开始执行业务逻辑...");
... | 41 | 94 | 135 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-aop/src/main/java/cn/javastack/springboot/aop/aspect/CalcAspect.java | CalcAspect | around | class CalcAspect {
@Pointcut("execution(* cn.javastack.springboot.aop.service.CalcService.*(..))")
private void pointcut() {
}
@Before("pointcut()")
public void before() {
System.out.println("********** @Before 前置通知");
}
@After("pointcut()")
public void after() {
Syste... |
Object result;
System.out.println("环绕通知之前");
result = proceedingJoinPoint.proceed();
System.out.println("环绕通知之后");
return result;
| 253 | 50 | 303 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-aop/src/main/java/cn/javastack/springboot/aop/service/CalcServiceImpl.java | CalcServiceImpl | divide | class CalcServiceImpl implements CalcService {
@Override
public int divide(int x, int y) {<FILL_FUNCTION_BODY>}
} |
System.out.println("=========== CalcService 被调用了");
int result = x / y;
System.out.println("=========== CalcService 调用成功");
return result;
| 44 | 53 | 97 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-cache/src/main/java/cn/javastack/springboot/cache/CacheConfiguration.java | CacheConfiguration | myRedisCacheManagerBuilderCustomizer | class CacheConfiguration {
/**
* 优先配置文件中的配置
* @return
*/
@Bean
public RedisCacheManagerBuilderCustomizer myRedisCacheManagerBuilderCustomizer() {<FILL_FUNCTION_BODY>}
} |
return (builder) -> builder
.withCacheConfiguration("calc", RedisCacheConfiguration
.defaultCacheConfig().entryTtl(Duration.ofSeconds(5)))
.withCacheConfiguration("test", RedisCacheConfiguration
.defaultCacheConfig().entryTtl(Durat... | 65 | 79 | 144 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-cache/src/main/java/cn/javastack/springboot/cache/CacheService.java | CacheService | multiply | class CacheService {
@Cacheable("calc")
public int multiply(int a, int b) {<FILL_FUNCTION_BODY>}
} |
int c = a * b;
log.info("{} * {} = {}", a, b, c);
return c;
| 44 | 35 | 79 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-datasource/src/main/java/cn/javastack/springboot/ds/Application.java | Application | commandLineRunner | class Application {
public final JdbcTemplate jdbcTemplate;
public final UserDao userDao;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
@Transactional
public CommandLineRunner commandLineRunner() {<FILL_FUNCTION_BODY>}
} |
return (args) -> {
String username = jdbcTemplate.queryForObject("select username from t_user where id = 2",
String.class);
log.info("query username is : {}", username);
List<Map<String, Object>> list = jdbcTemplate.queryForList("select id from t_user");... | 92 | 111 | 203 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-datasource/src/main/java/cn/javastack/springboot/ds/dao/impl/UserDaoImpl.java | UserDaoImpl | update | class UserDaoImpl implements UserDao {
public final JdbcTemplate jdbcTemplate;
@Transactional
@Override
public void update() {<FILL_FUNCTION_BODY>}
} |
jdbcTemplate.execute("update t_user set username = 'Petty' where id = 1");
jdbcTemplate.execute("update t_user set username = 'Yoga' where id = 2");
throw new RuntimeException("test exception");
| 55 | 61 | 116 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-elasticsearch/src/main/java/cn/javastack/springboot/es/EsController.java | EsController | repoInsert | class EsController {
public static final String INDEX_JAVASTACK = "javastack";
private final ElasticsearchTemplate elasticsearchTemplate;
private final UserRepository userRepository;
@RequestMapping("/es/insert")
public User insert(@RequestParam("name") String name, @RequestParam("sex") int sex) ... |
// 新增
User user = new User(RandomUtils.nextInt(), name, sex);
userRepository.save(user);
// 查询
return userRepository.findByName(name).get(0);
| 276 | 58 | 334 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-features/src/main/java/cn/javastack/springboot/features/Application.java | Application | main | class Application {
/**
* 作者:栈长
* 来源微信公众号:Java技术栈
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* 作者:栈长
* 来源微信公众号:Java技术栈
*/
@Bean
@Order(500)
public CommandLineRunner commandLineRunner() {
return (args) -> {
// throw new ... |
SpringApplication springApplication = new SpringApplication(Application.class);
// 允许循环引用
springApplication.setAllowCircularReferences(true);
// 启动详细日志
springApplication.setLogStartupInfo(true);
// 图案输出模式
springApplication.setBannerMode(Banner.Mode.CONSOLE);
... | 149 | 103 | 252 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-features/src/main/java/cn/javastack/springboot/features/analyzer/PortInUseFailureAnalyzer.java | PortInUseFailureAnalyzer | analyze | class PortInUseFailureAnalyzer extends AbstractFailureAnalyzer<PortInUseException> {
@Override
protected FailureAnalysis analyze(Throwable rootFailure, PortInUseException cause) {<FILL_FUNCTION_BODY>}
} |
return new FailureAnalysis("你启动的端口 " + cause.getPort() + " 被占用了.",
"快检查下端口 " + cause.getPort() + " 被哪个程序占用了,或者强制杀掉进程.",
cause);
| 60 | 68 | 128 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-features/src/main/java/cn/javastack/springboot/features/listener/JavastackListener.java | JavastackListener | onApplicationEvent | class JavastackListener implements ApplicationListener<AvailabilityChangeEvent> {
@Override
public void onApplicationEvent(AvailabilityChangeEvent event) {<FILL_FUNCTION_BODY>}
} |
log.info("监听到事件:" + event);
if (ReadinessState.ACCEPTING_TRAFFIC == event.getState()) {
log.info("应用启动完成,可以请求了……");
}
| 52 | 59 | 111 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-jasypt/src/main/java/cn/javastack/springboot/jasypt/Application.java | Application | commandLineRunner | class Application {
@Value("${javastack.username}")
private String username;
@Value("${javastack.password}")
private String password;
/**
* 来源微信公众号:Java技术栈
* 作者:栈长
*/
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
/**
... |
return (args) -> {
log.info("javastack.username = {}", username);
log.info("javastack.password = {}", password);
};
| 164 | 47 | 211 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-knife4j/src/main/java/cn/javastack/springboot/knife4j/api/Knife4jController.java | Knife4jController | login | class Knife4jController {
/**
* Knife4j 测试接口问好
* 来源微信公众号:Java技术栈
* 作者:栈长
*/
@ApiImplicitParam(name = "name", value = "名称", required = true)
@ApiOperation(value = "公众号Java技术栈向你问好!")
@ApiOperationSupport(order = 2, author = "栈长")
@GetMapping("/knife4j/hi")
public ResponseEntit... |
if (StringUtils.isNotBlank(username) && "javastack".equals(password)) {
return ResponseEntity.ok("登录成功:" + username);
}
return ResponseEntity.ok("用户名或者密码有误:" + username);
| 364 | 65 | 429 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-knife4j/src/main/java/cn/javastack/springboot/knife4j/config/Knife4jConfiguration.java | Knife4jConfiguration | defaultDocket | class Knife4jConfiguration {
@Bean(value = "defaultDocket")
public Docket defaultDocket() {<FILL_FUNCTION_BODY>}
} |
// 联系人信息
Contact contact = new Contact("公众号:Java技术栈", "https://www.javastack.cn", "xx@javastack.cn");
// 创建 Docket
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("Knife4j 测试")
... | 46 | 216 | 262 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-logging/src/main/java/cn/javastack/springboot/logging/Application.java | Application | commandLineRunner | class Application {
public static void main(String[] args) {
System.setProperty("LOG_PATH", "./logs");
System.setProperty("LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE", "1KB");
SpringApplication.run(Application.class);
}
private static final org.apache.commons.logging.Log logger1 = org.apa... |
return (args) -> {
logger1.error("commons logging error...");
logger1.warn("commons logging warn");
logger1.info("commons logging info...");
logger1.debug("commons logging debug...");
logger2.error("slf4j error...");
logger2.warn("commons... | 183 | 116 | 299 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-mail/src/main/java/cn/javastack/springboot/mail/EmailController.java | EmailController | createMimeMsg | class EmailController {
private final JavaMailSender javaMailSender;
private final MailProperties mailProperties;
@RequestMapping("/sendEmail")
@ResponseBody
public boolean sendEmail(@RequestParam("email") String email,
@RequestParam("text") String text) {
try... |
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg, true);
mimeMessageHelper.setFrom(mailProperties.getFrom(), mailProperties.getPersonal());
mimeMessageHelper.setTo(email);
mimeMessageHelper.setBcc(mailPropertie... | 379 | 152 | 531 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-mongodb/src/main/java/cn/javastack/mongodb/MongoController.java | MongoController | repoInsert | class MongoController {
public static final String COLLECTION_NAME = "javastack";
private final MongoTemplate mongoTemplate;
private final UserRepository userRepository;
@RequestMapping("/mongo/insert")
public User insert(@RequestParam("name") String name, @RequestParam("sex") int sex) {
... |
// 新增
User user = new User(RandomUtils.nextInt(), name, sex);
userRepository.save(user);
// 查询
return userRepository.findByName(name).get(0);
| 225 | 58 | 283 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-mybatis-plus/src/main/java/cn/javastack/springboot/mybatisplus/config/CustomMetaObjectHandler.java | CustomMetaObjectHandler | insertFill | class CustomMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {<FILL_FUNCTION_BODY>}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);... |
this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class);
this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
| 94 | 59 | 153 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-mybatis-plus/src/main/java/cn/javastack/springboot/mybatisplus/service/UserServiceImpl.java | UserServiceImpl | getByUsername | class UserServiceImpl
extends ServiceImpl<UserMapper, UserDO> implements UserService {
private final UserMapper userMapper;
@Override
public UserDO getByUsername(String username, int type) {<FILL_FUNCTION_BODY>}
} |
if (type == 0) {
// xml
log.info("query from xml");
return userMapper.selectByUsername(username);
} else {
// QueryWrapper
log.info("query from wrapper");
LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper();
... | 68 | 126 | 194 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-mybatis/src/main/java/cn/javastack/springboot/mybatis/controller/UserController.java | UserController | getUserInfo | class UserController {
private final UserMapper userMapper;
@GetMapping("/user/info/{id}")
public UserDO getUserInfo(@PathVariable("id") long id) {<FILL_FUNCTION_BODY>}
} |
UserDO userDO = userMapper.findById(id);
log.info("userDO: {}", userDO);
return userDO;
| 62 | 38 | 100 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-properties/src/main/java/cn/javastack/springboot/properties/Application.java | Application | commandLineRunner | class Application {
private final DbProperties dbProperties;
private final JavastackProperties javastackProperties;
private final MemberProperties memberProperties;
private final OtherMember otherMember;
@Value("${server.port}")
private int serverPort;
public static void main(String[] ... |
return (args) -> {
log.info("db properties: {}", dbProperties);
log.info("javastack properties: {}", javastackProperties);
log.info("member properties: {}", memberProperties);
log.info("other member: {}", otherMember);
log.info("server.port: {}", serv... | 157 | 90 | 247 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-quartz/src/main/java/cn/javastack/springboot/quartz/TaskConfig.java | TaskConfig | init | class TaskConfig {
public static final String SIMPLE_TASK = "simple-task";
private final SchedulerFactoryBean schedulerFactoryBean;
/**
* 动态添加任务
* @throws SchedulerException
*/
@PostConstruct
public void init() throws SchedulerException {<FILL_FUNCTION_BODY>}
// @Bean
pu... |
Scheduler scheduler = schedulerFactoryBean.getScheduler();
boolean exists = scheduler.checkExists(JobKey.jobKey(SIMPLE_TASK));
if (!exists) {
scheduler.scheduleJob(simpleTask(), simpleTaskTrigger());
}
| 265 | 71 | 336 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-redis/src/main/java/cn/javastack/springboot/redis/RedisController.java | RedisController | setObject | class RedisController {
private final StringRedisTemplate stringRedisTemplate;
@Resource(name = "stringRedisTemplate")
private ValueOperations<String, String> valueOperations;
private final RedisOptService redisOptService;
private final RedisLockService redisLockService;
@RequestMapping("/re... |
User user = new User();
user.setId(RandomUtils.nextInt());
user.setName(name);
user.setBirthday(new Date());
List<String> list = new ArrayList<>();
list.add("sing");
list.add("run");
user.setInteresting(list);
Map<String, Object> map = new HashM... | 416 | 194 | 610 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-redis/src/main/java/cn/javastack/springboot/redis/config/RedisConfig.java | RedisConfig | redisTemplate | class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {<FILL_FUNCTION_BODY>}
private RedisSerializer getJacksonSerializer() {
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
... |
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
StringRedisSerializer stringSerializer = new StringRedisSerializer();
RedisSerializer jacksonSerializer = getJacksonSerializer();
template.setKeySerializer(stringSerializer)... | 449 | 135 | 584 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-redis/src/main/java/cn/javastack/springboot/redis/service/RedisLockService.java | RedisLockService | unlock | class RedisLockService {
private Logger logger = LoggerFactory.getLogger(RedisLockService.class);
private static final long DEFAULT_EXPIRE_UNUSED = 60000L;
private final RedisLockRegistry redisLockRegistry;
public void lock(String lockKey) {
Lock lock = obtainLock(lockKey);
lock.lock... |
try {
Lock lock = obtainLock(lockKey);
lock.unlock();
redisLockRegistry.expireUnusedOlderThan(DEFAULT_EXPIRE_UNUSED);
} catch (Exception e) {
logger.error("分布式锁 [{}] 释放异常", lockKey, e);
}
| 261 | 83 | 344 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-redis/src/main/java/cn/javastack/springboot/redis/service/RedisOptService.java | RedisOptService | deleteKey | class RedisOptService {
private final RedisTemplate<String, Object> redisTemplate;
private final ValueOperations valueOperations;
private final HashOperations hashOperations;
private final ListOperations listOperations;
private final SetOperations setOperations;
private final ZSetOperations zS... |
if (key != null) {
int length = key.length;
if (length > 0) {
if (length == 1) {
return redisTemplate.delete(key[0]);
} else {
return redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)) == le... | 1,418 | 98 | 1,516 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-session/src/main/java/cn/javastack/springboot/session/IndexController.java | IndexController | loginSubmit | class IndexController {
private final HttpSession httpSession;
/**
* 登录页面
* @return
*/
@ResponseBody
@RequestMapping("/login")
public String login() {
return "login page.";
}
/**
* 登录请求
* @param username
* @return
*/
@RequestMapping("/login/s... |
if (StringUtils.isNotBlank(username)) {
httpSession.setAttribute("username", username);
return "/index";
}
return "/login";
| 252 | 45 | 297 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-session/src/main/java/cn/javastack/springboot/session/LoginInterceptor.java | LoginInterceptor | preHandle | class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {<FILL_FUNCTION_BODY>}
} |
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if (StringUtils.isBlank(username)) {
response.sendRedirect("/login");
return false;
}
return true;
| 60 | 66 | 126 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/config/SecurityConfig.java | SecurityConfig | securityFilterChain | class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>}
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.w... |
return http.authorizeHttpRequests((authorize) -> {
authorize.requestMatchers("/test/**").hasRole("TEST")
.requestMatchers("/**").permitAll();
})
.logout().logoutSuccessUrl("/")
.and().formLogin(withDefaults())
... | 153 | 82 | 235 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/config/WebConfig.java | WebConfig | mappingJackson2HttpMessageConverter | class WebConfig implements WebMvcConfigurer {
/**
* Locale 默认设置为英文
*
* @return
*/
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.US);
return s... |
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
SimpleModule module = new SimpleModule();
module.addDeserializer(Stri... | 777 | 127 | 904 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/controller/ResponseBodyController.java | ResponseBodyController | getXmlUserInfo | class ResponseBodyController {
@CrossOrigin
@GetMapping(value = "/user/json/{userId}", produces = MediaType.APPLICATION_JSON_VALUE)
public User getJsonUserInfo(@PathVariable("userId") @Size(min = 5, max = 8) String userId) {
User user = new User("Java技术栈", 18);
user.setId(Long.valueOf(userI... |
UserXml user = new UserXml();
user.setName("栈长");
user.setId(userId);
List<OrderInfo> orderList = new ArrayList<>();
OrderInfo orderInfo1 = new OrderInfo("123456001", 999, new Date());
OrderInfo orderInfo2 = new OrderInfo("123456002", 777, new Date());
OrderInfo... | 280 | 189 | 469 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/handler/CustomConverter.java | CustomConverter | convert | class CustomConverter implements Converter<String, String> {
@Override
public String convert(String source) {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isNotEmpty(source)) {
source = source.trim();
}
return source;
| 43 | 33 | 76 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/handler/CustomRestTemplateCustomizer.java | CustomRestTemplateCustomizer | customize | class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {<FILL_FUNCTION_BODY>}
static class CustomRoutePlanner extends DefaultProxyRoutePlanner {
CustomRoutePlanner(HttpHost proxy) {
super(proxy);
}
... |
HttpRoutePlanner routePlanner = new CustomRoutePlanner(new HttpHost("proxy.javastack.cn"));
RequestConfig requestConfig = RequestConfig.custom().build();
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setRoutePlanner(r... | 168 | 104 | 272 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/handler/ErrorRegister.java | ErrorRegister | registerErrorPages | class ErrorRegister implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {<FILL_FUNCTION_BODY>}
} |
ErrorPage err400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error");
ErrorPage err404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error");
ErrorPage err500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error");
registry.addErrorPages(err400, err404, err500);
| 45 | 101 | 146 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/handler/GlobalExceptionHandler.java | GlobalExceptionHandler | handleMethodArgumentNotValidException | class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(value = { Exception.class })
public ResponseEntity<?> handleException(HttpServletRequest request, Throwable ex) {
log.error("global exception:", ex);
return new ResponseEntity<>("global exception", HttpStatus.OK);
}
@Re... |
BindingResult bindingResult = ex.getBindingResult();
StringBuilder sb = new StringBuilder("参数校验失败:");
for (FieldError fieldError : bindingResult.getFieldErrors()) {
sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(", ");
}
St... | 136 | 106 | 242 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/servlet/InitServlet.java | InitServlet | service | class InitServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {<FILL_FUNCTION_BODY>}
} |
String name = getServletConfig().getInitParameter("name");
String sex = getServletConfig().getInitParameter("sex");
resp.getOutputStream().println("name is " + name);
resp.getOutputStream().println("sex is " + sex);
| 47 | 65 | 112 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/servlet/JavaFilter.java | JavaFilter | init | class JavaFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {<FILL_FUNCTION_BODY>}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.i... |
log.info("java filter init.");
String name = filterConfig.getInitParameter("name");
String code = filterConfig.getInitParameter("code");
log.info("name is " + name);
log.info("code is " + code);
| 126 | 65 | 191 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/servlet/JavaServlet.java | JavaServlet | service | class JavaServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {<FILL_FUNCTION_BODY>}
} |
String name = getServletConfig().getInitParameter("name");
String sex = getServletConfig().getInitParameter("sex");
resp.getOutputStream().println("name is " + name);
resp.getOutputStream().println("sex is " + sex);
| 47 | 65 | 112 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-web/src/main/java/cn/javastack/springboot/web/servlet/RegisterServlet.java | RegisterServlet | service | class RegisterServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {<FILL_FUNCTION_BODY>}
} |
String name = getServletConfig().getInitParameter("name");
String sex = getServletConfig().getInitParameter("sex");
resp.getOutputStream().println("name is " + name);
resp.getOutputStream().println("sex is " + sex);
| 47 | 64 | 111 | <no_super_class> |
javastacks_spring-boot-best-practice | spring-boot-best-practice/spring-boot-webflux/src/main/java/cn/javastack/springboot/webflux/config/WebConfig.java | WebConfig | webClient | class WebConfig {
@Bean
public WebClient webClient(WebClient.Builder webClientBuilder) {<FILL_FUNCTION_BODY>}
} |
HttpClient httpClient = HttpClient.create()
.tcpConfiguration(client ->
client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3)
.doOnConnected(conn -> {
conn.addHandlerLast(new ReadTimeoutHandler(3000));
... | 42 | 138 | 180 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/SpringBootPlusApplication.java | SpringBootPlusApplication | main | class SpringBootPlusApplication {
private static final String BACKSLASH = "/";
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 打印项目信息
*
* @param context
*/
private static void printlnProjectInfo(ConfigurableApplicationContext context) {
... |
ConfigurableApplicationContext context = SpringApplication.run(SpringBootPlusApplication.class, args);
System.out.println(" _____ _______ _____ _______ _____ _ _ _____ _____ ______ _____ _____ \n" +
" / ____|__ __|/\\ | __ \\__ __| / ____| | | |/ ____/ ____| ___... | 451 | 314 | 765 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/aop/AppDataRangeAop.java | AppDataRangeAop | doAround | class AppDataRangeAop {
@Around(AopConstant.APP_POINTCUT)
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {<FILL_FUNCTION_BODY>}
} |
Object[] args = joinPoint.getArgs();
if (ArrayUtils.isEmpty(args)) {
return joinPoint.proceed();
}
for (Object arg : args) {
if (arg instanceof DataRangeQuery) {
DataRangeQuery dataRangeQuery = (DataRangeQuery) arg;
DataRangeUtil.h... | 62 | 109 | 171 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/aop/CommonDataRangeAop.java | CommonDataRangeAop | doAround | class CommonDataRangeAop {
@Around(AopConstant.COMMON_POINTCUT)
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {<FILL_FUNCTION_BODY>}
} |
Object[] args = joinPoint.getArgs();
if (ArrayUtils.isEmpty(args)) {
return joinPoint.proceed();
}
for (Object arg : args) {
if (arg instanceof DataRangeQuery) {
DataRangeQuery dataRangeQuery = (DataRangeQuery) arg;
DataRangeUtil.h... | 64 | 109 | 173 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/aop/DataRangeAop.java | DataRangeAop | doAround | class DataRangeAop {
@Around(AopConstant.ADMIN_POINTCUT)
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {<FILL_FUNCTION_BODY>}
} |
Object[] args = joinPoint.getArgs();
if (ArrayUtils.isEmpty(args)) {
return joinPoint.proceed();
}
for (Object arg : args) {
if (arg instanceof DataRangeQuery) {
DataRangeQuery dataRangeQuery = (DataRangeQuery) arg;
DataRangeUtil.h... | 63 | 109 | 172 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/controller/AppLoginController.java | AppLoginController | login | class AppLoginController {
@Autowired
private AppLoginService appLoginService;
/**
* APP小程序登录
*
* @param appLoginDto
* @param response
* @return
* @throws Exception
*/
@PostMapping("/login")
@Operation(summary = "APP小程序登录")
public ApiResult<LoginTokenVo> logi... |
LoginTokenVo loginTokenVo = appLoginService.login(appLoginDto);
// 输出token到cookie
addCookie(loginTokenVo.getToken(), request, response);
return ApiResult.success(loginTokenVo);
| 699 | 66 | 765 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/controller/LoginController.java | LoginController | login | class LoginController {
@Autowired
private LoginService loginService;
/**
* 管理后台登录
*
* @param loginDto
* @param request
* @param response
* @return
* @throws Exception
*/
@PostMapping("/login")
@Operation(summary = "管理后台登录")
public ApiResult<LoginTokenVo... |
LoginTokenVo loginTokenVo = loginService.login(loginDto);
// 输出token到cookie
CookieUtil.addCookie(LoginConstant.ADMIN_COOKIE_TOKEN_NAME, loginTokenVo.getToken(), request, response);
return ApiResult.success(loginTokenVo);
| 399 | 84 | 483 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/interceptor/AppLoginInterceptor.java | AppLoginInterceptor | preHandleMethod | class AppLoginInterceptor extends BaseExcludeMethodInterceptor {
@Autowired
private LoginAppProperties loginAppProperties;
@Override
protected boolean preHandleMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {<FILL_FUNCTION_BODY>}
@Ov... |
// 获取token
String token = TokenUtil.getToken();
AppLoginVo appLoginVo = null;
if (StringUtils.isNotBlank(token)) {
// 获取登录用户信息
appLoginVo = AppLoginUtil.getLoginVo(token);
if (appLoginVo != null) {
// 将APP移动端的登录信息保存到当前线程中
... | 123 | 725 | 848 | <methods>public non-sealed void <init>() ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/interceptor/CommonLoginInterceptor.java | CommonLoginInterceptor | preHandleMethod | class CommonLoginInterceptor extends BaseExcludeMethodInterceptor {
@Override
protected boolean preHandleMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void afterCompletion(HttpServletRequest reques... |
// 获取token
String token = TokenUtil.getToken();
SystemType systemType = null;
if (StringUtils.isNotBlank(token)) {
systemType = SystemTypeUtil.getSystemTypeByToken(token);
if (SystemType.ADMIN == systemType) {
// 获取管理后台登录用户信息
Login... | 112 | 475 | 587 | <methods>public non-sealed void <init>() ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/interceptor/ExcludePathInterceptor.java | ExcludePathInterceptor | preHandleMethod | class ExcludePathInterceptor extends BaseMethodInterceptor {
@Autowired
private BootProperties bootProperties;
@Override
protected boolean preHandleMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {<FILL_FUNCTION_BODY>}
} |
String servletPath = request.getServletPath();
List<String> excludePaths = bootProperties.getExcludePaths();
if (CollectionUtils.isNotEmpty(excludePaths)) {
for (String excludePath : excludePaths) {
AntPathMatcher antPathMatcher = new AntPathMatcher();
... | 77 | 150 | 227 | <methods>public non-sealed void <init>() ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/interceptor/LoginInterceptor.java | LoginInterceptor | preHandleMethod | class LoginInterceptor extends BaseExcludeMethodInterceptor {
@Autowired
private LoginAdminProperties loginAdminProperties;
@Override
protected boolean preHandleMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {<FILL_FUNCTION_BODY>}
@O... |
// 如果token
String token = TokenUtil.getToken();
LoginVo loginVo = null;
if (StringUtils.isNotBlank(token)) {
// 获取登录用户信息
loginVo = LoginUtil.getLoginVo(token);
if (loginVo != null) {
// 将管理后台的登录信息保存到当前线程中
LoginCache.set... | 121 | 555 | 676 | <methods>public non-sealed void <init>() ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/interceptor/RefreshTokenInterceptor.java | RefreshTokenInterceptor | preHandleMethod | class RefreshTokenInterceptor extends BaseExcludeMethodInterceptor {
@Autowired
private LoginRedisService loginRedisService;
@Autowired
private AppLoginRedisService appLoginRedisService;
@Override
protected boolean preHandleMethod(HttpServletRequest request, HttpServletResponse response, Hand... |
SystemType systemType = SystemTypeUtil.getSystemTypeByPath(request);
if (SystemType.ADMIN == systemType) {
loginRedisService.refreshToken();
} else if (SystemType.APP == systemType) {
appLoginRedisService.refreshToken();
}
return true;
| 104 | 82 | 186 | <methods>public non-sealed void <init>() ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/interceptor/TokenInterceptor.java | TokenInterceptor | preHandleMethod | class TokenInterceptor extends BaseExcludeMethodInterceptor {
@Override
protected boolean preHandleMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void afterCompletion(HttpServletRequest request, Htt... |
// 获取token
String token = TokenUtil.getToken(request);
if (StringUtils.isBlank(token)) {
return true;
}
// 设置token值到当前线程中,避免重复获取
TokenCache.set(token);
return true;
| 106 | 77 | 183 | <methods>public non-sealed void <init>() ,public boolean preHandle(HttpServletRequest, HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/service/impl/AppLoginRedisServiceImpl.java | AppLoginRedisServiceImpl | refreshToken | class AppLoginRedisServiceImpl implements AppLoginRedisService {
private static final TimeUnit TOKEN_TIME_UNIT = TimeUnit.DAYS;
@Autowired
private LoginAppProperties loginAppProperties;
@Autowired
private RedisTemplate redisTemplate;
private Integer tokenExpireDays;
@PostConstruct
p... |
// 刷新token
String token = TokenUtil.getToken();
if (StringUtils.isBlank(token)) {
return;
}
// 刷新key的过期时间
String loginTokenRedisKey = getLoginRedisKey(token);
redisTemplate.expire(loginTokenRedisKey, tokenExpireDays, TOKEN_TIME_UNIT);
| 782 | 101 | 883 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/service/impl/AppLoginServiceImpl.java | AppLoginServiceImpl | getLoginUserInfo | class AppLoginServiceImpl implements AppLoginService {
@Autowired
private UserService userService;
@Autowired
private AppLoginRedisService appLoginRedisService;
@Autowired
private UserRoleService userRoleService;
@Override
public LoginTokenVo login(AppLoginDto dto) {
String c... |
AppLoginVo appLoginVo = AppLoginUtil.getLoginVo();
if (appLoginVo == null) {
throw new LoginException("请先登录");
}
Long userId = appLoginVo.getUserId();
User user = userService.getById(userId);
// 刷新用户登录信息
String token = TokenUtil.getToken();
Da... | 1,356 | 145 | 1,501 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/service/impl/LoginRedisServiceImpl.java | LoginRedisServiceImpl | deleteLoginVo | class LoginRedisServiceImpl implements LoginRedisService {
private static final TimeUnit TOKEN_TIME_UNIT = TimeUnit.MINUTES;
@Autowired
private LoginAdminProperties loginAdminProperties;
@Autowired
private RedisTemplate redisTemplate;
private Integer tokenExpireMinutes;
@PostConstruct
... |
if (StringUtils.isBlank(token)) {
throw new LoginTokenException("token不能为空");
}
String loginTokenRedisKey = getLoginRedisKey(token);
redisTemplate.delete(loginTokenRedisKey);
| 809 | 64 | 873 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/service/impl/LoginServiceImpl.java | LoginServiceImpl | refreshLoginInfo | class LoginServiceImpl implements LoginService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysRoleMapper sysRoleMapper;
@Autowired
private SysMenuMapper sysMenuMapper;
@Autowired
private LoginRedisService loginRedisService;
@Override
public LoginTok... |
// 用户ID
Long userId = sysUser.getId();
// 校验用户状态
Boolean status = sysUser.getStatus();
if (status == false) {
throw new BusinessException("用户已禁用");
}
// 查询用户角色
Long roleId = sysUser.getRoleId();
SysRole sysRole = sysRoleMapper.selectBy... | 690 | 367 | 1,057 | <no_super_class> |
geekidea_spring-boot-plus | spring-boot-plus/src/main/java/io/geekidea/boot/auth/util/AppLoginUtil.java | AppLoginUtil | getUserId | class AppLoginUtil {
private static AppLoginRedisService appLoginRedisService;
public AppLoginUtil(AppLoginRedisService appLoginRedisService) {
AppLoginUtil.appLoginRedisService = appLoginRedisService;
}
/**
* 根据token从redis中获取登录用户信息
*
* @param token
* @return
* @
... |
AppLoginVo appLoginVo = getLoginVo();
if (appLoginVo != null) {
return appLoginVo.getUserId();
}
return null;
| 623 | 52 | 675 | <no_super_class> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.