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-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springboot/PaketoBuilderKotlinDslGradleBuildCustomizer.java
PaketoBuilderKotlinDslGradleBuildCustomizer
customize
class PaketoBuilderKotlinDslGradleBuildCustomizer extends PaketoBuilderBuildCustomizer<GradleBuild> { @Override protected void customize(GradleBuild build, String imageBuilder) {<FILL_FUNCTION_BODY>} }
build.tasks().customize("bootBuildImage", (task) -> task.invoke("builder.set", "\"" + imageBuilder + "\""));
63
40
103
<methods>public void customize(GradleBuild) <variables>static final java.lang.String BASE_IMAGE_BUILDER,static final java.lang.String TINY_IMAGE_BUILDER
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springboot/PaketoBuilderMavenBuildCustomizer.java
PaketoBuilderMavenBuildCustomizer
customize
class PaketoBuilderMavenBuildCustomizer extends PaketoBuilderBuildCustomizer<MavenBuild> { @Override protected void customize(MavenBuild build, String imageBuilder) {<FILL_FUNCTION_BODY>} }
build.plugins() .add("org.springframework.boot", "spring-boot-maven-plugin", (plugin) -> plugin.configuration((configuration) -> configuration.add("image", (imageConfiguration) -> imageConfiguration.add("builder", imageBuilder))));
58
70
128
<methods>public void customize(MavenBuild) <variables>static final java.lang.String BASE_IMAGE_BUILDER,static final java.lang.String TINY_IMAGE_BUILDER
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudCircuitBreakerBuildCustomizer.java
SpringCloudCircuitBreakerBuildCustomizer
resolveBom
class SpringCloudCircuitBreakerBuildCustomizer implements BuildCustomizer<Build> { private final BuildMetadataResolver buildResolver; private final InitializrMetadata metadata; private final ProjectDescription description; public SpringCloudCircuitBreakerBuildCustomizer(InitializrMetadata metadata, ProjectDescription description) { this.buildResolver = new BuildMetadataResolver(metadata); this.metadata = metadata; this.description = description; } @Override public void customize(Build build) { DependencyContainer dependencies = build.dependencies(); if (dependencies.has("cloud-resilience4j") && this.buildResolver.hasFacet(build, "reactive")) { build.dependencies() .add("cloud-resilience4j-reactive", "org.springframework.cloud", "spring-cloud-starter-circuitbreaker-reactor-resilience4j", DependencyScope.COMPILE); removeBlockingCloudResilience4j(build); } } private void removeBlockingCloudResilience4j(Build build) { Dependency cloudResilience4j = this.metadata.getDependencies().get("cloud-resilience4j"); if (cloudResilience4j.getBom() != null) { BillOfMaterials bom = resolveBom(cloudResilience4j.getBom()); if (bom != null) { build.boms().add(cloudResilience4j.getBom()); if (bom.getVersionProperty() != null) { build.properties().version(bom.getVersionProperty(), bom.getVersion()); } if (!ObjectUtils.isEmpty(bom.getRepositories())) { bom.getRepositories().forEach((repository) -> build.repositories().add(repository)); } } } if (cloudResilience4j.getRepository() != null) { build.repositories().add(cloudResilience4j.getRepository()); } build.dependencies().remove("cloud-resilience4j"); } private BillOfMaterials resolveBom(String id) {<FILL_FUNCTION_BODY>} }
BillOfMaterials bom = this.metadata.getConfiguration().getEnv().getBoms().get(id); if (bom != null) { return bom.resolve(this.description.getPlatformVersion()); } return null;
559
65
624
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudContractGradleBuildCustomizer.java
SpringCloudContractGradleBuildCustomizer
configurePluginRepositories
class SpringCloudContractGradleBuildCustomizer implements BuildCustomizer<GradleBuild> { private static final Log logger = LogFactory.getLog(SpringCloudContractGradleBuildCustomizer.class); private static final MavenRepository SPRING_MILESTONES = MavenRepository .withIdAndUrl("spring-milestones", "https://repo.spring.io/milestone") .name("Spring Milestones") .build(); private static final MavenRepository SPRING_SNAPSHOTS = MavenRepository .withIdAndUrl("spring-snapshots", "https://repo.spring.io/snapshot") .name("Spring Snapshots") .snapshotsEnabled(true) .build(); private final ProjectDescription description; private final SpringCloudProjectVersionResolver projectsVersionResolver; protected SpringCloudContractGradleBuildCustomizer(ProjectDescription description, SpringCloudProjectVersionResolver projectsVersionResolver) { this.description = description; this.projectsVersionResolver = projectsVersionResolver; } @Override public void customize(GradleBuild build) { Version platformVersion = this.description.getPlatformVersion(); String sccPluginVersion = this.projectsVersionResolver.resolveVersion(platformVersion, "org.springframework.cloud:spring-cloud-contract-verifier"); if (sccPluginVersion == null) { logger.warn( "Spring Cloud Contract Verifier Gradle plugin version could not be resolved for Spring Boot version: " + platformVersion.toString()); return; } build.plugins().add("org.springframework.cloud.contract", (plugin) -> plugin.setVersion(sccPluginVersion)); configureContractsDsl(build); if (build.dependencies().has("webflux")) { build.dependencies() .add("rest-assured-spring-web-test-client", Dependency.withCoordinates("io.rest-assured", "spring-web-test-client") .scope(DependencyScope.TEST_COMPILE)); } build.tasks().customize("contractTest", (task) -> task.invoke("useJUnitPlatform")); configurePluginRepositories(build, sccPluginVersion); } protected abstract void configureContractsDsl(GradleBuild build); private void configurePluginRepositories(GradleBuild mavenBuild, String sccPluginVersion) {<FILL_FUNCTION_BODY>} }
Version pluginVersion = Version.parse(sccPluginVersion); if (pluginVersion.getQualifier() != null) { String qualifier = pluginVersion.getQualifier().getId(); if (!qualifier.equals("RELEASE")) { mavenBuild.pluginRepositories().add(SPRING_MILESTONES); if (qualifier.contains("SNAPSHOT")) { mavenBuild.pluginRepositories().add(SPRING_SNAPSHOTS); } } }
614
137
751
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudContractGroovyDslGradleBuildCustomizer.java
SpringCloudContractGroovyDslGradleBuildCustomizer
configureContractsDsl
class SpringCloudContractGroovyDslGradleBuildCustomizer extends SpringCloudContractGradleBuildCustomizer { SpringCloudContractGroovyDslGradleBuildCustomizer(ProjectDescription description, SpringCloudProjectVersionResolver projectsVersionResolver) { super(description, projectsVersionResolver); } @Override protected void configureContractsDsl(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.snippets().add((indentingWriter) -> { indentingWriter.println("contracts {"); indentingWriter.indented(() -> { if (build.dependencies().has("webflux")) { indentingWriter.println("testMode = 'WebTestClient'"); } }); indentingWriter.println("}"); });
111
102
213
<methods>public void customize(GradleBuild) <variables>private static final MavenRepository SPRING_MILESTONES,private static final MavenRepository SPRING_SNAPSHOTS,private final non-sealed ProjectDescription description,private static final Log logger,private final non-sealed io.spring.start.site.extension.dependency.springcloud.SpringCloudProjectVersionResolver projectsVersionResolver
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudContractKotlinDslGradleBuildCustomizer.java
SpringCloudContractKotlinDslGradleBuildCustomizer
configureContractsDsl
class SpringCloudContractKotlinDslGradleBuildCustomizer extends SpringCloudContractGradleBuildCustomizer { SpringCloudContractKotlinDslGradleBuildCustomizer(ProjectDescription description, SpringCloudProjectVersionResolver projectsVersionResolver) { super(description, projectsVersionResolver); } @Override protected void configureContractsDsl(GradleBuild build) {<FILL_FUNCTION_BODY>} }
boolean hasWebflux = build.dependencies().has("webflux"); Set<String> imports = new LinkedHashSet<>(); if (hasWebflux) { imports.add("org.springframework.cloud.contract.verifier.config.TestMode"); } build.snippets().add(imports, (indentingWriter) -> { indentingWriter.println("contracts {"); indentingWriter.indented(() -> { if (hasWebflux) { indentingWriter.println("testMode.set(TestMode.WEBTESTCLIENT)"); } }); indentingWriter.println("}"); });
109
180
289
<methods>public void customize(GradleBuild) <variables>private static final MavenRepository SPRING_MILESTONES,private static final MavenRepository SPRING_SNAPSHOTS,private final non-sealed ProjectDescription description,private static final Log logger,private final non-sealed io.spring.start.site.extension.dependency.springcloud.SpringCloudProjectVersionResolver projectsVersionResolver
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudContractMavenBuildCustomizer.java
SpringCloudContractMavenBuildCustomizer
customize
class SpringCloudContractMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { private static final Log logger = LogFactory.getLog(SpringCloudContractMavenBuildCustomizer.class); private static final MavenRepository SPRING_MILESTONES = MavenRepository .withIdAndUrl("spring-milestones", "https://repo.spring.io/milestone") .name("Spring Milestones") .build(); private static final MavenRepository SPRING_SNAPSHOTS = MavenRepository .withIdAndUrl("spring-snapshots", "https://repo.spring.io/snapshot") .name("Spring Snapshots") .snapshotsEnabled(true) .build(); private final ProjectDescription description; private final SpringCloudProjectVersionResolver projectsVersionResolver; SpringCloudContractMavenBuildCustomizer(ProjectDescription description, SpringCloudProjectVersionResolver projectsVersionResolver) { this.description = description; this.projectsVersionResolver = projectsVersionResolver; } @Override public void customize(MavenBuild mavenBuild) {<FILL_FUNCTION_BODY>} private void configurePluginRepositories(MavenBuild mavenBuild, String sccPluginVersion) { Version pluginVersion = Version.parse(sccPluginVersion); if (pluginVersion.getQualifier() != null) { String qualifier = pluginVersion.getQualifier().getId(); if (!qualifier.equals("RELEASE")) { mavenBuild.pluginRepositories().add(SPRING_MILESTONES); if (qualifier.contains("SNAPSHOT")) { mavenBuild.pluginRepositories().add(SPRING_SNAPSHOTS); } } } } }
Version platformVersion = this.description.getPlatformVersion(); String sccPluginVersion = this.projectsVersionResolver.resolveVersion(platformVersion, "org.springframework.cloud:spring-cloud-contract-verifier"); if (sccPluginVersion == null) { logger.warn( "Spring Cloud Contract Verifier Maven plugin version could not be resolved for Spring Boot version: " + platformVersion.toString()); return; } mavenBuild.plugins().add("org.springframework.cloud", "spring-cloud-contract-maven-plugin", (plugin) -> { plugin.extensions(true).version(sccPluginVersion); plugin.configuration((builder) -> builder.add("testFramework", "JUNIT5")); if (mavenBuild.dependencies().has("webflux")) { plugin.configuration((builder) -> builder.add("testMode", "WEBTESTCLIENT")); mavenBuild.dependencies() .add("rest-assured-spring-web-test-client", Dependency.withCoordinates("io.rest-assured", "spring-web-test-client") .scope(DependencyScope.TEST_COMPILE)); } }); configurePluginRepositories(mavenBuild, sccPluginVersion);
447
321
768
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudFunctionBuildCustomizer.java
SpringCloudFunctionBuildCustomizer
removeCloudFunction
class SpringCloudFunctionBuildCustomizer implements BuildCustomizer<Build> { private final InitializrMetadata metadata; private final ProjectDescription description; SpringCloudFunctionBuildCustomizer(InitializrMetadata metadata, ProjectDescription description) { this.metadata = metadata; this.description = description; } @Override public void customize(Build build) { DependencyContainer dependencies = build.dependencies(); if (dependencies.has("cloud-function")) { if (dependencies.has("web")) { dependencies.add("cloud-function-web", "org.springframework.cloud", "spring-cloud-function-web", DependencyScope.COMPILE); removeCloudFunction(build); } if (dependencies.has("webflux")) { dependencies.add("cloud-function-web", "org.springframework.cloud", "spring-cloud-function-web", DependencyScope.COMPILE); removeCloudFunction(build); } } } /* * Remove the Spring Cloud Function artifact, making sure that any metadata * information is kept. */ private void removeCloudFunction(Build build) {<FILL_FUNCTION_BODY>} private BillOfMaterials resolveBom(String id) { BillOfMaterials bom = this.metadata.getConfiguration().getEnv().getBoms().get(id); if (bom != null) { return bom.resolve(this.description.getPlatformVersion()); } return null; } }
Dependency cloudFunction = this.metadata.getDependencies().get("cloud-function"); // We should make sure whatever metadata this entry convey isn't lost // This is a workaround until we provide a feature to deal with this automatically if (cloudFunction.getBom() != null) { BillOfMaterials bom = resolveBom(cloudFunction.getBom()); if (bom != null) { build.boms().add(cloudFunction.getBom()); if (bom.getVersionProperty() != null) { build.properties().version(bom.getVersionProperty(), bom.getVersion()); } if (!ObjectUtils.isEmpty(bom.getRepositories())) { bom.getRepositories().forEach((repository) -> build.repositories().add(repository)); } } } if (cloudFunction.getRepository() != null) { build.repositories().add(cloudFunction.getRepository()); } build.dependencies().remove("cloud-function");
381
267
648
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudFunctionHelpDocumentCustomizer.java
SpringCloudFunctionHelpDocumentCustomizer
addBuildSetupInfo
class SpringCloudFunctionHelpDocumentCustomizer implements HelpDocumentCustomizer { private static final Log logger = LogFactory.getLog(SpringCloudFunctionHelpDocumentCustomizer.class); private final Set<String> buildDependencies; private final MustacheTemplateRenderer templateRenderer; private final SpringCloudProjectVersionResolver projectVersionResolver; private final ProjectDescription description; SpringCloudFunctionHelpDocumentCustomizer(Build build, ProjectDescription description, MustacheTemplateRenderer templateRenderer, SpringCloudProjectVersionResolver projectVersionResolver) { this.buildDependencies = build.dependencies().ids().collect(Collectors.toSet()); this.description = description; this.templateRenderer = templateRenderer; this.projectVersionResolver = projectVersionResolver; } @Override public void customize(HelpDocument helpDocument) { this.buildDependencies.stream() .filter((dependencyId) -> dependencyId.equals("cloud-function")) .findAny() .ifPresent((dependency) -> addBuildSetupInfo(helpDocument)); } private void addBuildSetupInfo(HelpDocument helpDocument) {<FILL_FUNCTION_BODY>} private boolean isSnapshot(String springCloudFunctionVersion) { return springCloudFunctionVersion.toUpperCase().contains("SNAPSHOT"); } private Set<CloudPlatform> cloudPlatformsFromDependencies() { return new HashSet<>(Arrays.stream(CloudPlatform.values()) .collect(Collectors .partitioningBy((cloudPlatform) -> this.buildDependencies.contains(cloudPlatform.getDependencyId()))) .get(true)); } private MustacheSection getSection(String version, String buildSystemId, CloudPlatform cloudPlatform, String templateName) { return new MustacheSection(this.templateRenderer, templateName, getModel(cloudPlatform, buildSystemId, version)); } private Map<String, Object> getModel(CloudPlatform cloudPlatform, String buildSystemId, String version) { Map<String, Object> model = new LinkedHashMap<>(); model.put("platform", cloudPlatform.getName()); model.put("buildTool", buildSystemId); model.put("version", version); return model; } private String getTemplateName(CloudPlatform cloudPlatform) { return "spring-cloud-function-build-setup-" + cloudPlatform.toString().toLowerCase(); } /** * Represents Cloud Platforms that provide build plugins that can be used for * deploying Spring Cloud Function applications. */ enum CloudPlatform { AZURE("Microsoft Azure", "azure-support", Collections.singletonList(MavenBuildSystem.ID)); private final String name; private final String dependencyId; private List<String> supportedBuildSystems = Arrays.asList(MavenBuildSystem.ID, GradleBuildSystem.ID); CloudPlatform(String name, String dependencyId, List<String> supportedBuildSystems) { this(name, dependencyId); this.supportedBuildSystems = supportedBuildSystems; } CloudPlatform(String name, String dependencyId) { this.name = name; this.dependencyId = dependencyId; } String getName() { return this.name; } String getDependencyId() { return this.dependencyId; } List<String> getSupportedBuildSystems() { return Collections.unmodifiableList(this.supportedBuildSystems); } } }
Version bootVersion = this.description.getPlatformVersion(); String springCloudFunctionVersion = this.projectVersionResolver.resolveVersion(bootVersion, "org.springframework.cloud:spring-cloud-function-core"); if (springCloudFunctionVersion == null) { logger.warn("Spring Cloud Function version could not be resolved for Spring Boot version: " + bootVersion.toString()); return; } if (isSnapshot(springCloudFunctionVersion)) { logger.debug("Spring Cloud Function version " + springCloudFunctionVersion + " is a snapshot. No documents are present for this version to link to."); return; } String buildSystemId = this.description.getBuildSystem().id(); Map<Boolean, List<CloudPlatform>> platformsByBuildSystemSupport = cloudPlatformsFromDependencies().stream() .collect(Collectors .partitioningBy((cloudPlatform) -> cloudPlatform.getSupportedBuildSystems().contains(buildSystemId))); platformsByBuildSystemSupport.get(true) .forEach((cloudPlatform) -> helpDocument.nextSteps() .addSection(getSection(springCloudFunctionVersion, buildSystemId, cloudPlatform, getTemplateName(cloudPlatform)))); platformsByBuildSystemSupport.get(false) .forEach((cloudPlatform) -> helpDocument.nextSteps() .addSection(getSection(springCloudFunctionVersion, buildSystemId, cloudPlatform, "spring-cloud-function-build-setup-missing")));
867
372
1,239
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudProjectGenerationConfiguration.java
SpringCloudContractConfiguration
springCloudContractDirectoryProjectContributor
class SpringCloudContractConfiguration { @Bean ProjectContributor springCloudContractDirectoryProjectContributor(Build build) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) SpringCloudContractMavenBuildCustomizer springCloudContractMavenBuildCustomizer(ProjectDescription description, SpringCloudProjectVersionResolver versionResolver) { return new SpringCloudContractMavenBuildCustomizer(description, versionResolver); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) SpringCloudContractGroovyDslGradleBuildCustomizer springCloudContractGroovyDslGradleBuildCustomizer( ProjectDescription description, SpringCloudProjectVersionResolver versionResolver) { return new SpringCloudContractGroovyDslGradleBuildCustomizer(description, versionResolver); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) SpringCloudContractKotlinDslGradleBuildCustomizer springCloudContractKotlinDslGradleBuildCustomizer( ProjectDescription description, SpringCloudProjectVersionResolver versionResolver) { return new SpringCloudContractKotlinDslGradleBuildCustomizer(description, versionResolver); } }
String contractDirectory = (build instanceof MavenBuild) ? "src/test/resources/contracts" : "src/contractTest/resources/contracts"; return (projectRoot) -> { Path migrationDirectory = projectRoot.resolve(contractDirectory); Files.createDirectories(migrationDirectory); };
354
87
441
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudProjectVersionResolver.java
SpringCloudProjectVersionResolver
resolveVersion
class SpringCloudProjectVersionResolver { private static final Log logger = LogFactory.getLog(SpringCloudProjectVersionResolver.class); private final InitializrMetadata metadata; private final MavenVersionResolver versionResolver; SpringCloudProjectVersionResolver(InitializrMetadata metadata, MavenVersionResolver versionResolver) { this.metadata = metadata; this.versionResolver = versionResolver; } /** * Resolve the version of a specified artifact that matches the provided Spring Boot * version. * @param platformVersion the Spring Boot version to check the Spring Cloud Release * train version against * @param dependencyId the dependency id of the Spring Cloud artifact in the form of * {@code groupId:artifactId} * @return the appropriate project version or {@code null} if the resolution failed */ String resolveVersion(Version platformVersion, String dependencyId) {<FILL_FUNCTION_BODY>} }
BillOfMaterials bom = this.metadata.getConfiguration().getEnv().getBoms().get("spring-cloud"); if (bom == null) { return null; } String releaseTrainVersion = bom.resolve(platformVersion).getVersion(); logger.info("Retrieving version for artifact: " + dependencyId + " and release train version: " + releaseTrainVersion); return this.versionResolver .resolveDependencies("org.springframework.cloud", "spring-cloud-dependencies", releaseTrainVersion) .get(dependencyId);
224
144
368
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springcloud/SpringCloudStreamBuildCustomizer.java
SpringCloudStreamBuildCustomizer
customize
class SpringCloudStreamBuildCustomizer implements BuildCustomizer<Build> { private final ProjectDescription description; SpringCloudStreamBuildCustomizer(ProjectDescription description) { this.description = description; } @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} protected boolean hasDependency(String id, Build build) { return build.dependencies().has(id); } protected boolean hasPulsarSupport() { Version platformVersion = this.description.getPlatformVersion(); return platformVersion.compareTo(Version.parse("3.2.0-M3")) >= 0; } }
if (hasDependency("cloud-stream", build) || hasDependency("cloud-bus", build)) { if (hasDependency("amqp", build)) { build.dependencies() .add("cloud-stream-binder-rabbit", "org.springframework.cloud", "spring-cloud-stream-binder-rabbit", DependencyScope.COMPILE); } if (hasDependency("kafka", build)) { build.dependencies() .add("cloud-stream-binder-kafka", "org.springframework.cloud", "spring-cloud-stream-binder-kafka", DependencyScope.COMPILE); } if (hasPulsarSupport() && hasDependency("pulsar", build)) { build.dependencies() .add("cloud-stream-binder-pulsar", "org.springframework.cloud", "spring-cloud-stream-binder-pulsar", DependencyScope.COMPILE); } } // Spring Cloud Stream specific if (hasDependency("cloud-stream", build)) { if (hasDependency("kafka-streams", build)) { build.dependencies() .add("cloud-stream-binder-kafka-streams", "org.springframework.cloud", "spring-cloud-stream-binder-kafka-streams", DependencyScope.COMPILE); } build.dependencies() .add("cloud-stream-test", Dependency.withCoordinates("org.springframework.cloud", "spring-cloud-stream-test-binder") .scope(DependencyScope.TEST_COMPILE)); }
161
417
578
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springdata/R2dbcBuildCustomizer.java
R2dbcBuildCustomizer
addSpringJdbcIfNecessary
class R2dbcBuildCustomizer implements BuildCustomizer<Build> { private static final List<String> JDBC_DEPENDENCY_IDS = Arrays.asList("jdbc", "data-jdbc", "data-jpa"); @Override public void customize(Build build) { if (build.dependencies().has("h2")) { addManagedDriver(build.dependencies(), "io.r2dbc", "r2dbc-h2"); } if (build.dependencies().has("mariadb")) { addManagedDriver(build.dependencies(), "org.mariadb", "r2dbc-mariadb", "1.1.3"); } if (build.dependencies().has("mysql")) { addManagedDriver(build.dependencies(), "io.asyncer", "r2dbc-mysql"); } if (build.dependencies().has("postgresql")) { addManagedDriver(build.dependencies(), "org.postgresql", "r2dbc-postgresql"); } if (build.dependencies().has("sqlserver")) { addManagedDriver(build.dependencies(), "io.r2dbc", "r2dbc-mssql", "1.0.0.RELEASE"); } if (build.dependencies().has("oracle")) { addManagedDriver(build.dependencies(), "com.oracle.database.r2dbc", "oracle-r2dbc"); } if (build.dependencies().has("flyway") || build.dependencies().has("liquibase")) { addSpringJdbcIfNecessary(build); } } private void addManagedDriver(DependencyContainer dependencies, String groupId, String artifactId) { dependencies.add(artifactId, Dependency.withCoordinates(groupId, artifactId).scope(DependencyScope.RUNTIME)); } private void addManagedDriver(DependencyContainer dependencies, String groupId, String artifactId, String version) { Builder<?> builder = Dependency.withCoordinates(groupId, artifactId).scope(DependencyScope.RUNTIME); if (version != null) { builder.version(VersionReference.ofValue(version)); } dependencies.add(artifactId, builder); } private void addSpringJdbcIfNecessary(Build build) {<FILL_FUNCTION_BODY>} }
boolean hasSpringJdbc = build.dependencies().ids().anyMatch(JDBC_DEPENDENCY_IDS::contains); if (!hasSpringJdbc) { build.dependencies().add("spring-jdbc", Dependency.withCoordinates("org.springframework", "spring-jdbc")); }
606
84
690
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springdata/R2dbcHelpDocumentCustomizer.java
R2dbcHelpDocumentCustomizer
customize
class R2dbcHelpDocumentCustomizer implements HelpDocumentCustomizer { private static final List<String> DRIVERS = List.of("h2", "mariadb", "mysql", "postgresql", "sqlserver", "oracle"); private final Build build; public R2dbcHelpDocumentCustomizer(Build build) { this.build = build; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
if (this.build.dependencies().ids().noneMatch(DRIVERS::contains)) { document.addSection((writer) -> { writer.println("## Missing R2DBC Driver"); writer.println(); writer.println( "Make sure to include a [R2DBC Driver](https://r2dbc.io/drivers/) to connect to your database."); }); }
117
106
223
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springintegration/SpringIntegrationModuleRegistry.java
SpringIntegrationModuleRegistry
create
class SpringIntegrationModuleRegistry { static Iterable<ImplicitDependency> create() {<FILL_FUNCTION_BODY>} private static Iterable<ImplicitDependency> create(ImplicitDependency.Builder... dependencies) { return Arrays.stream(dependencies).map(Builder::build).collect(Collectors.toList()); } private static ImplicitDependency.Builder onDependencies(String... dependencyIds) { return new Builder().matchAnyDependencyIds(dependencyIds); } private static Consumer<Build> addDependency(String id) { return addDependency(id, DependencyScope.COMPILE); } private static Consumer<Build> addDependency(String id, DependencyScope scope) { return (build) -> build.dependencies() .add("integration-" + id, Dependency.withCoordinates("org.springframework.integration", "spring-integration-" + id) .scope(scope)); } private static Consumer<HelpDocument> addReferenceLink(String name, String id) { return (helpDocument) -> { String href = String.format("https://docs.spring.io/spring-integration/reference/html/%s.html", id); String description = String.format("Spring Integration %s Reference Guide", name); helpDocument.gettingStarted().addReferenceDocLink(href, description); }; } }
return create( onDependencies("activemq", "artemis").customizeBuild(addDependency("jms")) .customizeHelpDocument(addReferenceLink("JMS Module", "jms")), onDependencies("amqp", "amqp-streams").customizeBuild(addDependency("amqp")) .customizeHelpDocument(addReferenceLink("AMQP Module", "amqp")), onDependencies("data-jdbc", "jdbc").customizeBuild(addDependency("jdbc")) .customizeHelpDocument(addReferenceLink("JDBC Module", "jdbc")), onDependencies("data-jpa").customizeBuild(addDependency("jpa")) .customizeHelpDocument(addReferenceLink("JPA Module", "jpa")), onDependencies("data-mongodb", "data-mongodb-reactive").customizeBuild(addDependency("mongodb")) .customizeHelpDocument(addReferenceLink("MongoDB Module", "mongodb")), onDependencies("data-r2dbc").customizeBuild(addDependency("r2dbc")) .customizeHelpDocument(addReferenceLink("R2DBC Module", "r2dbc")), onDependencies("data-redis", "data-redis-reactive").customizeBuild(addDependency("redis")) .customizeHelpDocument(addReferenceLink("Redis Module", "redis")), onDependencies("integration").customizeBuild(addDependency("test", DependencyScope.TEST_COMPILE)) .customizeHelpDocument(addReferenceLink("Test Module", "testing")), onDependencies("kafka", "kafka-streams").customizeBuild(addDependency("kafka")) .customizeHelpDocument(addReferenceLink("Apache Kafka Module", "kafka")), onDependencies("mail").customizeBuild(addDependency("mail")) .customizeHelpDocument(addReferenceLink("Mail Module", "mail")), onDependencies("rsocket").customizeBuild(addDependency("rsocket")) .customizeHelpDocument(addReferenceLink("RSocket Module", "rsocket")), onDependencies("security").customizeBuild(addDependency("security")) .customizeHelpDocument(addReferenceLink("Security Module", "security")), onDependencies("web").customizeBuild(addDependency("http")) .customizeHelpDocument(addReferenceLink("HTTP Module", "http")), onDependencies("webflux").customizeBuild(addDependency("webflux")) .customizeHelpDocument(addReferenceLink("WebFlux Module", "webflux")), onDependencies("websocket").customizeBuild(addDependency("stomp").andThen(addDependency("websocket"))) .customizeHelpDocument(addReferenceLink("STOMP Module", "stomp") .andThen(addReferenceLink("WebSocket Module", "web-sockets"))), onDependencies("web-services").customizeBuild(addDependency("ws")) .customizeHelpDocument(addReferenceLink("Web Services Module", "ws")));
345
767
1,112
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springkafka/SpringKafkaProjectGenerationConfiguration.java
SpringKafkaProjectGenerationConfiguration
kafkaServiceConnectionsCustomizer
class SpringKafkaProjectGenerationConfiguration { @Bean SpringKafkaBuildCustomizer springKafkaBuildCustomizer() { return new SpringKafkaBuildCustomizer(); } @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer kafkaServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (serviceConnections) -> serviceResolver.doWith("kafka", (service) -> serviceConnections.addServiceConnection(ServiceConnection.ofContainer("kafka", service, "org.testcontainers.containers.KafkaContainer", false)));
104
69
173
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springmodulith/SpringModulithBuildCustomizer.java
SpringModulithBuildCustomizer
customize
class SpringModulithBuildCustomizer implements BuildCustomizer<Build> { private static final Collection<String> OBSERVABILITY_DEPENDENCIES = List.of("actuator", "datadog", "graphite", "influx", "new-relic", "prometheus", "wavefront", "zipkin"); @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} private void addEventPublicationRegistryBackend(Build build) { DependencyContainer dependencies = build.dependencies(); if (dependencies.has("data-mongodb")) { dependencies.add("modulith-starter-mongodb", modulithDependency("starter-mongodb")); } if (dependencies.has("data-jdbc")) { dependencies.add("modulith-starter-jdbc", modulithDependency("starter-jdbc")); } if (dependencies.has("data-jpa")) { dependencies.add("modulith-starter-jpa", modulithDependency("starter-jpa")); } } private Builder<?> modulithDependency(String name) { return Dependency.withCoordinates("org.springframework.modulith", "spring-modulith-" + name); } }
DependencyContainer dependencies = build.dependencies(); if (dependencies.has("actuator")) { dependencies.add("modulith-actuator", modulithDependency("actuator").scope(DependencyScope.RUNTIME)); } if (OBSERVABILITY_DEPENDENCIES.stream().anyMatch(dependencies::has)) { dependencies.add("modulith-observability", modulithDependency("observability").scope(DependencyScope.RUNTIME)); } addEventPublicationRegistryBackend(build); dependencies.add("modulith-starter-test", modulithDependency("starter-test").scope(DependencyScope.TEST_COMPILE));
328
187
515
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springpulsar/SpringPulsarProjectGenerationConfiguration.java
OnPulsarDependencyCondition
matches
class OnPulsarDependencyCondition extends ProjectGenerationCondition { @Override protected boolean matches(ProjectDescription description, ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
Map<String, Dependency> requestedDependencies = description.getRequestedDependencies(); return requestedDependencies.containsKey("pulsar") || requestedDependencies.containsKey("pulsar-reactive");
60
55
115
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springrestdocs/SpringRestDocsBuildCustomizer.java
SpringRestDocsBuildCustomizer
customize
class SpringRestDocsBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} private boolean switchToWebTestClient(Build build) { if (build.dependencies().has("web")) { return false; } if (build.dependencies().has("webflux") || build.dependencies().has("jersey")) { return true; } return false; } }
if (switchToWebTestClient(build)) { build.dependencies().remove("restdocs"); build.dependencies() .add("restdocs-webtestclient", "org.springframework.restdocs", "spring-restdocs-webtestclient", DependencyScope.TEST_COMPILE); }
124
84
208
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springrestdocs/SpringRestDocsGradleGroovyBuildCustomizer.java
SpringRestDocsGradleGroovyBuildCustomizer
customizeForDialect
class SpringRestDocsGradleGroovyBuildCustomizer extends AbstractSpringRestDocsGradleBuildCustomizer { @Override void customizeForDialect(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.tasks().customize("test", (task) -> task.invoke("outputs.dir", "snippetsDir")); build.tasks().customize("asciidoctor", (task) -> { task.invoke("inputs.dir", "snippetsDir"); task.invoke("dependsOn", "test"); });
61
93
154
<methods>public void customize(GradleBuild) <variables>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springrestdocs/SpringRestDocsGradleKotlinBuildCustomizer.java
SpringRestDocsGradleKotlinBuildCustomizer
customizeForDialect
class SpringRestDocsGradleKotlinBuildCustomizer extends AbstractSpringRestDocsGradleBuildCustomizer { @Override void customizeForDialect(GradleBuild build) {<FILL_FUNCTION_BODY>} }
build.tasks().customize("test", (task) -> task.invoke("outputs.dir", "project.extra[\"snippetsDir\"]!!")); build.tasks().customize("asciidoctor", (task) -> { task.invoke("inputs.dir", "project.extra[\"snippetsDir\"]!!"); task.invoke("dependsOn", "tasks.test"); });
60
113
173
<methods>public void customize(GradleBuild) <variables>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springrestdocs/SpringRestDocsMavenBuildCustomizer.java
SpringRestDocsMavenBuildCustomizer
customize
class SpringRestDocsMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.plugins().add("org.asciidoctor", "asciidoctor-maven-plugin", (plugin) -> { plugin.version("2.2.1"); plugin.execution("generate-docs", (execution) -> { execution.phase("prepare-package"); execution.goal("process-asciidoc"); execution.configuration((configuration) -> { configuration.add("backend", "html"); configuration.add("doctype", "book"); }); }); plugin.dependency("org.springframework.restdocs", "spring-restdocs-asciidoctor", "${spring-restdocs.version}"); });
51
177
228
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springsecurity/SpringSecurityRSocketBuildCustomizer.java
SpringSecurityRSocketBuildCustomizer
customize
class SpringSecurityRSocketBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
if (build.dependencies().has("rsocket")) { build.dependencies() .add("security-rsocket", Dependency.withCoordinates("org.springframework.security", "spring-security-rsocket")); build.dependencies() .add("security-messaging", Dependency.withCoordinates("org.springframework.security", "spring-security-messaging")); }
45
105
150
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/springsession/SpringSessionBuildCustomizer.java
SpringSessionBuildCustomizer
customize
class SpringSessionBuildCustomizer implements BuildCustomizer<Build> { @Override public void customize(Build build) {<FILL_FUNCTION_BODY>} }
DependencyContainer dependencies = build.dependencies(); if (dependencies.has("data-redis") || dependencies.has("data-redis-reactive")) { dependencies.add("session-data-redis", "org.springframework.session", "spring-session-data-redis", DependencyScope.COMPILE); dependencies.remove("session"); } if (dependencies.has("jdbc")) { dependencies.add("session-jdbc", "org.springframework.session", "spring-session-jdbc", DependencyScope.COMPILE); dependencies.remove("session"); }
43
163
206
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/sqlserver/SqlServerProjectGenerationConfiguration.java
SqlServerProjectGenerationConfiguration
sqlServerComposeFileCustomizer
class SqlServerProjectGenerationConfiguration { private static String TESTCONTAINERS_CLASS_NAME = "org.testcontainers.containers.MSSQLServerContainer"; @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer sqlServerServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) { return (serviceConnections) -> serviceResolver.doWith("sqlServer", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofContainer("sqlServer", service, TESTCONTAINERS_CLASS_NAME))); } @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer sqlServerComposeFileCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} }
return (composeFile) -> serviceResolver.doWith("sqlServer", (service) -> composeFile.services() .add("sqlserver", service.andThen((builder) -> builder.environment("MSSQL_PID", "express") .environment("MSSQL_SA_PASSWORD", "verYs3cret") .environment("ACCEPT_EULA", "yes"))));
195
106
301
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/vaadin/VaadinMavenBuildCustomizer.java
VaadinMavenBuildCustomizer
customize
class VaadinMavenBuildCustomizer implements BuildCustomizer<MavenBuild> { @Override public void customize(MavenBuild build) {<FILL_FUNCTION_BODY>} }
build.profiles() .id("production") .plugins() .add("com.vaadin", "vaadin-maven-plugin", (plugin) -> plugin.version("${vaadin.version}") .execution("frontend", (execution) -> execution.goal("prepare-frontend").goal("build-frontend").phase("compile")));
50
99
149
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/dependency/zipkin/ZipkinProjectGenerationConfiguration.java
ZipkinProjectGenerationConfiguration
zipkinServiceConnectionsCustomizer
class ZipkinProjectGenerationConfiguration { @Bean @ConditionalOnRequestedDependency("testcontainers") ServiceConnectionsCustomizer zipkinServiceConnectionsCustomizer(DockerServiceResolver serviceResolver) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnRequestedDependency("docker-compose") ComposeFileCustomizer zipkinComposeFileCustomizer(DockerServiceResolver serviceResolver) { return (composeFile) -> serviceResolver.doWith("zipkin", (service) -> composeFile.services().add("zipkin", service)); } }
return (serviceConnections) -> serviceResolver.doWith("zipkin", (service) -> serviceConnections .addServiceConnection(ServiceConnection.ofGenericContainer("zipkin", service, "openzipkin/zipkin")));
147
58
205
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/description/InvalidJvmVersionHelpDocumentCustomizer.java
InvalidJvmVersionHelpDocumentCustomizer
processJvmVersionDiff
class InvalidJvmVersionHelpDocumentCustomizer implements HelpDocumentCustomizer { private final ProjectDescriptionDiff diff; private final ProjectDescription description; public InvalidJvmVersionHelpDocumentCustomizer(ProjectDescriptionDiff diff, ProjectDescription description) { this.diff = diff; this.description = description; } @Override public void customize(HelpDocument document) { this.diff.ifLanguageChanged(this.description, (original, current) -> { String originalJvmVersion = original.jvmVersion(); String actualJvmVersion = current.jvmVersion(); if (!Objects.equals(originalJvmVersion, actualJvmVersion)) { processJvmVersionDiff(originalJvmVersion, actualJvmVersion).accept(document); } }); } protected Consumer<HelpDocument> processJvmVersionDiff(String originalJvmVersion, String actualJvmVersion) {<FILL_FUNCTION_BODY>} }
return (document) -> { if (this.description.getLanguage() instanceof KotlinLanguage) { document.getWarnings() .addItem( "The JVM level was changed from '%s' to '%s' as the Kotlin version does not support Java %s yet." .formatted(originalJvmVersion, actualJvmVersion, originalJvmVersion)); } else { document.getWarnings() .addItem( "The JVM level was changed from '%s' to '%s', review the [JDK Version Range](%s) on the wiki for more details." .formatted(originalJvmVersion, actualJvmVersion, "https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Versions#jdk-version-range")); } };
231
214
445
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/description/InvalidPackageNameHelpDocumentCustomizer.java
InvalidPackageNameHelpDocumentCustomizer
customize
class InvalidPackageNameHelpDocumentCustomizer implements HelpDocumentCustomizer { private final ProjectDescriptionDiff diff; private final ProjectDescription description; public InvalidPackageNameHelpDocumentCustomizer(ProjectDescriptionDiff diff, ProjectDescription description) { this.diff = diff; this.description = description; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
this.diff.ifPackageNameChanged(this.description, (original, current) -> document.getWarnings() .addItem(String.format( "The original package name '%s' is invalid and this project uses '%s' instead.", original, current)));
100
73
173
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/extension/properties/DefaultApplicationPropertiesCustomizer.java
DefaultApplicationPropertiesCustomizer
customize
class DefaultApplicationPropertiesCustomizer implements ApplicationPropertiesCustomizer { private final ProjectDescription projectDescription; DefaultApplicationPropertiesCustomizer(ProjectDescription projectDescription) { this.projectDescription = projectDescription; } @Override public void customize(ApplicationProperties properties) {<FILL_FUNCTION_BODY>} }
String name = this.projectDescription.getName(); if (StringUtils.hasLength(name)) { properties.add("spring.application.name", name); }
78
46
124
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/project/JavaVersionProjectDescriptionCustomizer.java
JavaVersionProjectDescriptionCustomizer
determineJavaGeneration
class JavaVersionProjectDescriptionCustomizer implements ProjectDescriptionCustomizer { private static final VersionRange KOTLIN_1_9_20_OR_LATER = VersionParser.DEFAULT.parseRange("3.2.0-RC2"); private static final VersionRange SPRING_BOOT_3_2_4_OR_LATER = VersionParser.DEFAULT.parseRange("3.2.4"); private static final List<String> UNSUPPORTED_VERSIONS = Arrays.asList("1.6", "1.7", "1.8"); @Override public void customize(MutableProjectDescription description) { Version platformVersion = description.getPlatformVersion(); String javaVersion = description.getLanguage().jvmVersion(); if (UNSUPPORTED_VERSIONS.contains(javaVersion)) { updateTo(description, "17"); return; } Integer javaGeneration = determineJavaGeneration(javaVersion); if (javaGeneration == null) { return; } if (javaGeneration < 17) { updateTo(description, "17"); } if (javaGeneration == 21) { // Kotlin 1.9.20 is required if (description.getLanguage() instanceof KotlinLanguage && !KOTLIN_1_9_20_OR_LATER.match(platformVersion)) { updateTo(description, "17"); } } if (javaGeneration == 22) { // Java 21 support as of Spring Boot 3.2.4 if (!SPRING_BOOT_3_2_4_OR_LATER.match(platformVersion)) { updateTo(description, "21"); } } } private void updateTo(MutableProjectDescription description, String jvmVersion) { Language language = Language.forId(description.getLanguage().id(), jvmVersion); description.setLanguage(language); } private Integer determineJavaGeneration(String javaVersion) {<FILL_FUNCTION_BODY>} }
try { int generation = Integer.parseInt(javaVersion); return ((generation > 9 && generation <= 22) ? generation : null); } catch (NumberFormatException ex) { return null; }
519
62
581
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/project/dependency/springcloud/SpringCloudResilience4JProjectDescriptionCustomizer.java
SpringCloudResilience4JProjectDescriptionCustomizer
customize
class SpringCloudResilience4JProjectDescriptionCustomizer implements ProjectDescriptionCustomizer { @Override public void customize(MutableProjectDescription description) {<FILL_FUNCTION_BODY>} }
Collection<String> dependencyIds = description.getRequestedDependencies().keySet(); if (!dependencyIds.contains("cloud-resilience4j")) { return; } if (dependencyIds.contains("webflux")) { description.addDependency("cloud-resilience4j", Dependency.from(description.getRequestedDependencies().get("cloud-resilience4j")) .artifactId("spring-cloud-starter-circuitbreaker-reactor-resilience4j")); }
50
133
183
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/support/CacheableMavenVersionResolver.java
CacheableMavenVersionResolver
generate
class CacheableMavenVersionResolver implements MavenVersionResolver, KeyGenerator { private final MavenVersionResolver delegate; public CacheableMavenVersionResolver(MavenVersionResolver delegate) { this.delegate = delegate; } @Override @Cacheable public Map<String, String> resolveDependencies(String groupId, String artifactId, String version) { return this.delegate.resolveDependencies(groupId, artifactId, version); } @Override @Cacheable public Map<String, String> resolvePlugins(String groupId, String artifactId, String version) { return this.delegate.resolvePlugins(groupId, artifactId, version); } @Override public Object generate(Object target, Method method, Object... params) {<FILL_FUNCTION_BODY>} }
String prefix = (method.getName().equals("resolveDependencies")) ? "dependencies" : "plugins"; return "%s-%s:%s:%s".formatted(prefix, params[0], params[1], params[2]);
201
60
261
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/support/StartInitializrMetadataUpdateStrategy.java
StartInitializrMetadataUpdateStrategy
isCompatibleVersion
class StartInitializrMetadataUpdateStrategy extends SpringIoInitializrMetadataUpdateStrategy { public StartInitializrMetadataUpdateStrategy(RestTemplate restTemplate, ObjectMapper objectMapper) { super(restTemplate, objectMapper); } @Override protected List<DefaultMetadataElement> fetchSpringBootVersions(String url) { List<DefaultMetadataElement> versions = super.fetchSpringBootVersions(url); return (versions != null) ? versions.stream().filter(this::isCompatibleVersion).collect(Collectors.toList()) : null; } private boolean isCompatibleVersion(DefaultMetadataElement versionMetadata) {<FILL_FUNCTION_BODY>} }
Version version = Version.parse(versionMetadata.getId()); return (version.getMajor() >= 3 && version.getMinor() >= 1);
171
40
211
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/support/implicit/ImplicitDependency.java
Builder
matchAll
class Builder { private Predicate<Build> buildPredicate = (build) -> true; private Consumer<Build> buildCustomizer; private Consumer<HelpDocument> helpDocumentCustomizer; /** * For the implicit dependency created by this builder to be enabled, any of the * specified {@code dependencies} must be present in the build. May be combined * with other matches. * @param dependencies the dependencies to match * @return this for method chaining * @see #match(Predicate) */ public Builder matchAnyDependencyIds(String... dependencies) { return match((build) -> matchAny(build, dependencies)); } /** * For the implicit dependency created by this builder to be enabled, all of the * specified {@code dependencies} must be present in the build. May be combined * with other matches. * @param dependencies the dependencies to match * @return this for method chaining * @see #match(Predicate) */ public Builder matchAllDependencyIds(String... dependencies) { return match((build) -> matchAll(build, dependencies)); } /** * For the implicit dependency created by this builder to be enabled, the * specified {@link Predicate} must pass. May be combined with other matches. * @param buildPredicate the predicate to use to enable the dependency * @return this for method chaining */ public Builder match(Predicate<Build> buildPredicate) { this.buildPredicate = this.buildPredicate.and(buildPredicate); return this; } /** * Set the {@link Build} customizer to use. * @param buildCustomizer the build customizer to use * @return this for method chaining */ public Builder customizeBuild(Consumer<Build> buildCustomizer) { this.buildCustomizer = buildCustomizer; return this; } /** * Set the {@link HelpDocument} customizer to use. * @param helpDocumentCustomizer the help document customizer to use * @return this for method chaining */ public Builder customizeHelpDocument(Consumer<HelpDocument> helpDocumentCustomizer) { this.helpDocumentCustomizer = helpDocumentCustomizer; return this; } /** * Create an {@link ImplicitDependency} based on the state of this builder. * @return an implicit dependency */ public ImplicitDependency build() { return new ImplicitDependency(this); } private static boolean matchAny(Build build, String... dependencies) { for (String dependency : dependencies) { if (build.dependencies().has(dependency)) { return true; } } return false; } private static boolean matchAll(Build build, String... dependencies) {<FILL_FUNCTION_BODY>} }
for (String dependency : dependencies) { if (!build.dependencies().has(dependency)) { return false; } } return true;
710
43
753
<no_super_class>
spring-io_start.spring.io
start.spring.io/start-site/src/main/java/io/spring/start/site/support/implicit/ImplicitDependencyHelpDocumentCustomizer.java
ImplicitDependencyHelpDocumentCustomizer
customize
class ImplicitDependencyHelpDocumentCustomizer implements HelpDocumentCustomizer { private final Iterable<ImplicitDependency> dependencies; private final Build build; public ImplicitDependencyHelpDocumentCustomizer(Iterable<ImplicitDependency> dependencies, Build build) { this.dependencies = dependencies; this.build = build; } @Override public void customize(HelpDocument document) {<FILL_FUNCTION_BODY>} }
for (ImplicitDependency dependency : this.dependencies) { dependency.customize(document, this.build); }
107
35
142
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/BaseStreamEx.java
BaseStreamEx
spliterator
class BaseStreamEx<T, S extends BaseStream<T, S>, SPLTR extends Spliterator<T>, B extends BaseStreamEx<T, S, SPLTR, B>> implements BaseStream<T, S> { static final String CONSUMED_MESSAGE = "Stream is already consumed"; private S stream; SPLTR spliterator; StreamContext context; BaseStreamEx(S stream, StreamContext context) { this.stream = stream; this.context = context; } BaseStreamEx(SPLTR spliterator, StreamContext context) { this.spliterator = spliterator; this.context = context; } abstract S createStream(); final S stream() { if (stream != null) return stream; if (spliterator == null) throw new IllegalStateException(CONSUMED_MESSAGE); stream = createStream(); spliterator = null; return stream; } @SuppressWarnings("unchecked") @Override public SPLTR spliterator() {<FILL_FUNCTION_BODY>} @Override public boolean isParallel() { return context.parallel; } @SuppressWarnings("unchecked") @Override public S sequential() { context = context.sequential(); if (stream != null) stream = stream.sequential(); return (S) this; } /** * {@inheritDoc} * * <p> * If this stream was created using {@link #parallel(ForkJoinPool)}, the new * stream forgets about supplied custom {@link ForkJoinPool} and its * terminal operation will be executed in common pool. */ @SuppressWarnings("unchecked") @Override public S parallel() { context = context.parallel(); if (stream != null) stream = stream.parallel(); return (S) this; } /** * Returns an equivalent stream that is parallel and bound to the supplied * {@link ForkJoinPool}. * * <p> * This is an <a href="package-summary.html#StreamOps">intermediate</a> * operation. * * <p> * The terminal operation of this stream or any derived stream (except the * streams created via {@link #parallel()} or {@link #sequential()} methods) * will be executed inside the supplied {@code ForkJoinPool}. If current * thread does not belong to that pool, it will wait till calculation * finishes. * * @param fjp a {@code ForkJoinPool} to submit the stream operation to. * @return a parallel stream bound to the supplied {@code ForkJoinPool} * @since 0.2.0 */ @SuppressWarnings("unchecked") public S parallel(ForkJoinPool fjp) { context = context.parallel(fjp); if (stream != null) stream = stream.parallel(); return (S) this; } @SuppressWarnings("unchecked") @Override public S unordered() { stream = stream().unordered(); return (S) this; } @SuppressWarnings("unchecked") @Override public S onClose(Runnable closeHandler) { context = context.onClose(closeHandler); return (S) this; } @Override public void close() { context.close(); } /** * Applies the supplied function to this stream and returns the result of * the function. * * <p> * This method can be used to add more functionality in the fluent style. * For example, consider user-defined static method * {@code batches(stream, n)} which breaks the stream into batches of given * length. Normally you would write * {@code batches(StreamEx.of(input).map(...), 10).filter(...)}. Using the * {@code chain()} method you can write in more fluent manner: * {@code StreamEx.of(input).map(...).chain(s -> batches(s, 10)).filter(...)}. * * <p> * You could even go further and define a method which returns a function * like {@code <T> UnaryOperator<StreamEx<T>> batches(int n)} and use it * like this: * {@code StreamEx.of(input).map(...).chain(batches(10)).filter(...)}. * * @param <U> the type of the function result. * @param mapper function to invoke. * @return the result of the function invocation. * @since 0.5.4 */ public abstract <U> U chain(Function<? super B, U> mapper); }
if (stream != null) return (SPLTR) stream.spliterator(); if (spliterator != null) { SPLTR s = spliterator; spliterator = null; return s; } throw new IllegalStateException(CONSUMED_MESSAGE);
1,389
87
1,476
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/CharSpliterator.java
CharSpliterator
trySplit
class CharSpliterator implements Spliterator<String> { private final CharSequence source; private final char delimiter; private int pos; private final int fence; private int nEmpty; private String next; private final boolean trimEmpty; CharSpliterator(CharSequence source, char delimiter, boolean trimEmpty) { this.source = source; this.delimiter = delimiter; this.fence = source.length(); this.trimEmpty = trimEmpty; } // Create prefix spliterator and update suffix fields private CharSpliterator(CharSpliterator suffix, int fence, boolean trimEmpty, int suffixNEmpty, int suffixPos) { this.source = suffix.source; this.delimiter = suffix.delimiter; this.fence = fence; this.trimEmpty = trimEmpty; this.pos = suffix.pos; suffix.pos = suffixPos; this.nEmpty = suffix.nEmpty; suffix.nEmpty = suffixNEmpty; this.next = suffix.next; suffix.next = null; } private int next(int pos) { if (pos == fence) return pos; if (source instanceof String) { int nextPos = ((String) source).indexOf(delimiter, pos); return nextPos == -1 ? fence : nextPos; } while (pos < fence) { if (source.charAt(pos) == delimiter) return pos; pos++; } return fence; } @Override public boolean tryAdvance(Consumer<? super String> action) { if (nEmpty > 0) { nEmpty--; action.accept(""); return true; } if (next != null) { action.accept(next); next = null; return true; } if (pos > fence) { return false; } int nextPos = next(pos); if (trimEmpty) { while (nextPos == pos && nextPos != fence) { nEmpty++; nextPos = next(++pos); } } String str = source.subSequence(pos, nextPos).toString(); pos = nextPos + 1; if (trimEmpty && nextPos == fence && str.isEmpty()) { nEmpty = 0; // discard empty strings at the end return false; } if (nEmpty > 0) { next = str; nEmpty--; action.accept(""); } else action.accept(str); return true; } @Override public Spliterator<String> trySplit() {<FILL_FUNCTION_BODY>} @Override public long estimateSize() { return pos > fence ? 0 : fence - pos; } @Override public int characteristics() { return NONNULL | ORDERED; } }
int mid = (pos + fence) >>> 1; int nextPos = next(mid); if (nextPos == fence) return null; if (trimEmpty && nextPos == mid) { while (nextPos < fence && source.charAt(nextPos) == delimiter) nextPos++; return nextPos == fence ? new CharSpliterator(this, mid, true, 0, nextPos + 1) : new CharSpliterator(this, mid, false, nextPos - mid - 1, nextPos); } return new CharSpliterator(this, nextPos, false, 0, nextPos + 1);
852
181
1,033
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/CollapseSpliterator.java
Connector
handleLeft
class Connector<T, R> { CollapseSpliterator<T, R> lhs, rhs; T left = none(), right = none(); R acc; Connector(CollapseSpliterator<T, R> lhs, R acc, CollapseSpliterator<T, R> rhs) { this.lhs = lhs; this.rhs = rhs; this.acc = acc; } R drain() { if (lhs != null) lhs.right = null; if (rhs != null) rhs.left = null; return acc; } R drainLeft() { return left == NONE ? drain() : none(); } R drainRight() { return right == NONE ? drain() : none(); } } CollapseSpliterator(BiPredicate<? super T, ? super T> mergeable, Function<T, R> mapper, BiFunction<R, T, R> accumulator, BinaryOperator<R> combiner, Spliterator<T> source) { super(none()); this.source = source; this.mergeable = mergeable; this.mapper = mapper; this.accumulator = accumulator; this.combiner = combiner; this.root = this; } private CollapseSpliterator(CollapseSpliterator<T, R> root, Spliterator<T> source, Connector<T, R> left, Connector<T, R> right) { super(none()); this.source = source; this.root = root; this.mergeable = root.mergeable; this.mapper = root.mapper; this.accumulator = root.accumulator; this.combiner = root.combiner; this.left = left; this.right = right; if (left != null) left.rhs = this; right.lhs = this; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (left != null) { if (accept(handleLeft(), action)) { return true; } } if (a == NONE) { // start if (!source.tryAdvance(this)) { return accept(pushRight(none(), none()), action); } } T first = a; R acc = mapper.apply(a); T last = first; while (source.tryAdvance(this)) { if (!this.mergeable.test(last, a)) { action.accept(acc); return true; } last = a; acc = this.accumulator.apply(acc, last); } return accept(pushRight(acc, last), action); } @Override public void forEachRemaining(Consumer<? super R> action) { while (left != null) { accept(handleLeft(), action); } if (a != NONE) { acc = mapper.apply(a); } source.forEachRemaining(next -> { if (a == NONE) { acc = mapper.apply(next); } else if (!this.mergeable.test(a, next)) { action.accept(acc); acc = mapper.apply(next); } else { acc = accumulator.apply(acc, next); } a = next; }); if (a == NONE) { accept(pushRight(none(), none()), action); } else if (accept(pushRight(acc, a), action)) { if (right != null) { action.accept(right.acc); right = null; } } } private boolean accept(R acc, Consumer<? super R> action) { if (acc != NONE) { action.accept(acc); return true; } return false; } private R handleLeft() {<FILL_FUNCTION_BODY>
synchronized (root) { Connector<T, R> l = left; if (l == null) { return none(); } if (l.left == NONE && l.right == NONE && l.acc != NONE) { return l.drain(); } } if (source.tryAdvance(this)) { T first = this.a; T last = first; R acc = this.mapper.apply(first); while (source.tryAdvance(this)) { if (!this.mergeable.test(last, a)) return pushLeft(first, acc); last = a; acc = this.accumulator.apply(acc, last); } a = none(); return connectOne(first, acc, last); } return connectEmpty();
1,170
239
1,409
<methods>public void accept(T) <variables>T a
amaembo_streamex
streamex/src/main/java/one/util/streamex/CombinationSpliterator.java
CombinationSpliterator
characteristics
class CombinationSpliterator implements Spliterator<int[]> { private long pos; private int[] value; private final long fence; private final int n; public CombinationSpliterator(int n, long pos, long fence, int[] value) { this.n = n; this.pos = pos; this.fence = fence; this.value = value; } @Override public void forEachRemaining(Consumer<? super int[]> action) { long rest = pos - fence; pos = fence; while (rest > 0) { action.accept(value.clone()); if (--rest > 0) { step(value, n); } } } @Override public Spliterator<int[]> trySplit() { if (pos - fence < 2) return null; long newPos = (fence + pos) >>> 1; CombinationSpliterator result = new CombinationSpliterator(n, pos, newPos, value); value = jump(newPos - 1, value.length, n); pos = newPos; return result; } @Override public long estimateSize() { return pos - fence; } @Override public int characteristics() {<FILL_FUNCTION_BODY>} static void step(int[] value, int n) { int i, k = value.length; for (i = k; --i >= 0 && ++value[i] >= n; ) { n--; } while (++i < k) { value[i] = value[i - 1] + 1; } } static int[] jump(long newPos, int k, int n) { int[] newValue = new int[k]; int curK = k - 1; long bound = 0; for (int i = 0; i < k; i++) { long cnk = 1; int curN = curK; while (newPos >= bound + cnk) { bound += cnk; curN++; cnk = cnk * curN / (curN - curK); } curK--; newValue[i] = n - curN - 1; } return newValue; } static long gcd(long a, long b) { while (b != 0) { long t = a % b; a = b; b = t; } return a; } /** * @param n n > k * @param k k > 0 * @return CNK(n, k) */ static long cnk(int n, int k) { long size = 1; int rest = n; for (long div = 1; div <= k; ++div, --rest) { long gcd = gcd(size, div); size /= gcd; long t = rest / (div / gcd); if (size > Long.MAX_VALUE / t) { throw new UnsupportedOperationException("Number of combinations exceed Long.MAX_VALUE: unsupported"); } size *= t; } return size; } @Override public boolean tryAdvance(Consumer<? super int[]> action) { if (pos <= fence) { return false; } action.accept(value.clone()); if (--pos > fence) { step(value, n); } return true; } }
return DISTINCT | IMMUTABLE | NONNULL | ORDERED | SIZED | SUBSIZED;
924
33
957
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/ConstSpliterator.java
OfLong
forEachRemaining
class OfLong extends ConstSpliterator<Long, OfLong> implements Spliterator.OfLong { private final long value; OfLong(long value, long count, boolean ordered) { super(count, ordered); this.value = value; } @Override public boolean tryAdvance(LongConsumer action) { if (remaining <= 0) return false; action.accept(value); remaining--; return true; } @Override public void forEachRemaining(LongConsumer action) {<FILL_FUNCTION_BODY>} }
for (long r = remaining; r > 0; r--) { action.accept(value); } remaining = 0;
171
42
213
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/CrossSpliterator.java
ToList
trySplit
class ToList<T> extends CrossSpliterator<T, List<T>> { private List<T> elements; @SuppressWarnings("unchecked") ToList(Collection<? extends Collection<T>> source) { super(source); this.elements = (List<T>) Arrays.asList(new Object[collections.length]); } private ToList(long est, int splitPos, Spliterator<T>[] spliterators, Collection<T>[] collections, List<T> elements) { super(est, splitPos, spliterators, collections); this.elements = elements; } @Override public boolean tryAdvance(Consumer<? super List<T>> action) { if (elements == null) return false; if (est < Long.MAX_VALUE && est > 0) est--; if (advance(collections.length - 1)) { action.accept(new ArrayList<>(elements)); return true; } elements = null; est = 0; return false; } @Override public void forEachRemaining(Consumer<? super List<T>> action) { if (elements == null) return; List<T> e = elements; int l = collections.length - 1; while (advance(l)) { action.accept(new ArrayList<>(e)); } elements = null; est = 0; } @Override Spliterator<List<T>> doSplit(long prefixEst, Spliterator<T>[] prefixSpliterators, Collection<T>[] prefixCollections) { @SuppressWarnings("unchecked") List<T> prefixElements = (List<T>) Arrays.asList(elements.toArray()); return new ToList<>(prefixEst, splitPos, prefixSpliterators, prefixCollections, prefixElements); } @Override void accumulate(int pos, T t) { elements.set(pos, t); } } boolean advance(int i) { if (spliterators[i] == null) { if (i > 0 && collections[i - 1] != null && !advance(i - 1)) return false; spliterators[i] = collections[i].spliterator(); } Consumer<? super T> action = t -> accumulate(i, t); if (!spliterators[i].tryAdvance(action)) { if (i == 0 || collections[i - 1] == null || !advance(i - 1)) return false; spliterators[i] = collections[i].spliterator(); return spliterators[i].tryAdvance(action); } return true; } @Override public Spliterator<A> trySplit() {<FILL_FUNCTION_BODY>
if (spliterators[splitPos] == null) spliterators[splitPos] = collections[splitPos].spliterator(); Spliterator<T> res = spliterators[splitPos].trySplit(); if (res == null) { if (splitPos == spliterators.length - 1) return null; @SuppressWarnings("unchecked") T[] arr = (T[]) StreamSupport.stream(spliterators[splitPos], false).toArray(); if (arr.length == 0) return null; if (arr.length == 1) { accumulate(splitPos, arr[0]); splitPos++; return trySplit(); } spliterators[splitPos] = Spliterators.spliterator(arr, Spliterator.ORDERED); return trySplit(); } long prefixEst = Long.MAX_VALUE; long newEst = spliterators[splitPos].getExactSizeIfKnown(); if (newEst == -1) { newEst = Long.MAX_VALUE; } else { try { for (int i = splitPos + 1; i < collections.length; i++) { long size = collections[i].size(); newEst = StrictMath.multiplyExact(newEst, size); } if (est != Long.MAX_VALUE) prefixEst = est - newEst; } catch (ArithmeticException e) { newEst = Long.MAX_VALUE; } } Spliterator<T>[] prefixSpliterators = spliterators.clone(); Collection<T>[] prefixCollections = collections.clone(); prefixSpliterators[splitPos] = res; this.est = newEst; Arrays.fill(spliterators, splitPos + 1, spliterators.length, null); return doSplit(prefixEst, prefixSpliterators, prefixCollections);
811
525
1,336
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/DistinctSpliterator.java
DistinctSpliterator
trySplit
class DistinctSpliterator<T> extends Box<T> implements Spliterator<T> { private final Spliterator<T> source; private AtomicLong nullCounter; private Map<T, Long> counts; private final long atLeast; DistinctSpliterator(Spliterator<T> source, long atLeast, AtomicLong nullCounter, Map<T, Long> counts) { this.source = source; this.atLeast = atLeast; this.nullCounter = nullCounter; this.counts = counts; } DistinctSpliterator(Spliterator<T> source, long atLeast) { this(source, atLeast, null, new HashMap<>()); } @Override public boolean tryAdvance(Consumer<? super T> action) { if (nullCounter == null) { while (source.tryAdvance(this)) { if (counts.merge(a, 1L, Long::sum) == atLeast) { action.accept(a); return true; } } } else { while (source.tryAdvance(this)) { long count = a == null ? nullCounter.incrementAndGet() : counts.merge(a, 1L, Long::sum); if (count == atLeast) { action.accept(a); return true; } } } return false; } @Override public void forEachRemaining(Consumer<? super T> action) { if (nullCounter == null) { source.forEachRemaining(e -> { if (counts.merge(e, 1L, Long::sum) == atLeast) { action.accept(e); } }); } else { source.forEachRemaining(e -> { long count = e == null ? nullCounter.incrementAndGet() : counts.merge(e, 1L, Long::sum); if (count == atLeast) { action.accept(e); } }); } } @Override public Spliterator<T> trySplit() {<FILL_FUNCTION_BODY>} @Override public long estimateSize() { return source.estimateSize(); } @Override public int characteristics() { return DISTINCT | (source.characteristics() & (NONNULL | CONCURRENT | IMMUTABLE | ORDERED | SORTED)); } @Override public Comparator<? super T> getComparator() { return source.getComparator(); } }
Spliterator<T> split = source.trySplit(); if (split == null) return null; if (counts.getClass() == HashMap.class) { if (!source.hasCharacteristics(NONNULL)) { Long current = counts.remove(null); nullCounter = new AtomicLong(current == null ? 0 : current); } counts = new ConcurrentHashMap<>(counts); } return new DistinctSpliterator<>(split, atLeast, nullCounter, counts);
746
147
893
<methods>public void accept(T) <variables>T a
amaembo_streamex
streamex/src/main/java/one/util/streamex/EmitterSpliterator.java
OfDouble
accept
class OfDouble extends Spliterators.AbstractDoubleSpliterator implements DoubleConsumer { DoubleStreamEx.DoubleEmitter e; Spliterator.OfDouble buf; int vals; DoubleConsumer cons; OfDouble(DoubleStreamEx.DoubleEmitter e) { super(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL); this.e = e; } @Override public boolean tryAdvance(DoubleConsumer action) { if (buf != null) { if (buf.tryAdvance(action)) return true; buf = null; } cons = action; for (vals = 0; vals == 0; e = e.next(this)) { if (e == null) return false; } if (vals > 1) { buf = ((DoubleStream.Builder) cons).build().spliterator(); } cons = null; return true; } @Override public void forEachRemaining(DoubleConsumer action) { if (buf != null) { buf.forEachRemaining(action); buf = null; } DoubleStreamEx.DoubleEmitter e = this.e; this.e = null; while (e != null) e = e.next(action); } @Override public void accept(double t) {<FILL_FUNCTION_BODY>} }
if ((vals += vals < 3 ? 1 : 0) == 2) { cons = DoubleStream.builder(); } cons.accept(t);
424
49
473
<methods>public int characteristics() ,public long estimateSize() ,public Spliterator<T> trySplit() <variables>static final int BATCH_UNIT,static final int MAX_BATCH,private int batch,private final int characteristics,private long est
amaembo_streamex
streamex/src/main/java/one/util/streamex/HeadTailSpliterator.java
HeadTailSpliterator
tryAdvanceOrTail
class HeadTailSpliterator<T, U> extends AbstractSpliterator<U> implements TailSpliterator<U> { private Spliterator<T> source; private BiFunction<? super T, ? super StreamEx<T>, ? extends Stream<U>> mapper; private Supplier<? extends Stream<U>> emptyMapper; private Spliterator<U> target; StreamContext context; HeadTailSpliterator(Spliterator<T> source, BiFunction<? super T, ? super StreamEx<T>, ? extends Stream<U>> mapper, Supplier<? extends Stream<U>> emptyMapper) { super(Long.MAX_VALUE, ORDERED); this.source = source; this.mapper = mapper; this.emptyMapper = emptyMapper; } @Override public boolean tryAdvance(Consumer<? super U> action) { if (!init()) return false; target = TailSpliterator.tryAdvanceWithTail(target, action); if (target == null) { context = null; return false; } return true; } @Override public Spliterator<U> tryAdvanceOrTail(Consumer<? super U> action) {<FILL_FUNCTION_BODY>} @Override public void forEachRemaining(Consumer<? super U> action) { if (!init()) return; TailSpliterator.forEachWithTail(target, action); target = null; context = null; } @Override public Spliterator<U> forEachOrTail(Consumer<? super U> action) { return tryAdvanceOrTail(action); } private boolean init() { if (context == null) return false; if (target == null) { Box<T> first = new Box<>(); source = TailSpliterator.tryAdvanceWithTail(source, first); Stream<U> stream = source == null ? emptyMapper.get() : mapper.apply(first.a, StreamEx.of(source)); source = null; mapper = null; emptyMapper = null; if (stream == null) { target = Spliterators.emptySpliterator(); } else { StreamContext ctx = StreamContext.of(stream); if (ctx.closeHandler != null) context.onClose(ctx.closeHandler); target = stream.spliterator(); } } return true; } @Override public long estimateSize() { if (context == null) return 0; return (target == null ? source : target).estimateSize(); } }
if (!init()) return null; Spliterator<U> tail = target; target = null; context = null; return tail;
766
50
816
<methods>public int characteristics() ,public long estimateSize() ,public Spliterator<U> trySplit() <variables>static final int BATCH_UNIT,static final int MAX_BATCH,private int batch,private final int characteristics,private long est
amaembo_streamex
streamex/src/main/java/one/util/streamex/IfEmptySpliterator.java
IfEmptySpliterator
tryAdvance
class IfEmptySpliterator<T> extends Internals.CloneableSpliterator<T, IfEmptySpliterator<T>> { // alt == null --> decision is made private Spliterator<? extends T> spltr, alt; // positive = number of non-exhausted spliterators; negative = surely non-empty private final AtomicInteger state = new AtomicInteger(1); public IfEmptySpliterator(Spliterator<? extends T> spltr, Spliterator<? extends T> alt) { this.spltr = spltr; this.alt = alt; } void tryInit() { if (alt != null && spltr.hasCharacteristics(SIZED)) { if (spltr.estimateSize() == 0) { spltr = alt; } alt = null; } } @Override public boolean tryAdvance(Consumer<? super T> action) {<FILL_FUNCTION_BODY>} @Override public void forEachRemaining(Consumer<? super T> action) { tryInit(); if (alt == null) { spltr.forEachRemaining(action); } else { boolean[] empty = {true}; spltr.forEachRemaining(e -> { empty[0] = false; action.accept(e); }); if (empty[0]) { if (drawState()) { (spltr = alt).forEachRemaining(action); } } else { state.set(-1); } alt = null; } } boolean drawState() { return state.updateAndGet(x -> x > 0 ? x - 1 : x) == 0; } @Override public Spliterator<T> trySplit() { Spliterator<? extends T> prefix = spltr.trySplit(); if (prefix == null) { return null; } tryInit(); if (alt != null) { state.updateAndGet(x -> x > 0 ? x + 1 : x); } IfEmptySpliterator<T> clone = doClone(); clone.spltr = prefix; return clone; } @Override public long estimateSize() { tryInit(); long size = spltr.estimateSize(); return alt != null && size == 0 ? alt.estimateSize() : size; } @Override public int characteristics() { if (alt == null) { return spltr.characteristics() & (~SORTED); } return (spltr.characteristics() & alt.characteristics() & (~SORTED)) | ((spltr.characteristics() | alt.characteristics()) & (ORDERED)); } }
if (alt != null) { if (spltr.tryAdvance(action)) { state.set(-1); alt = null; return true; } if (drawState()) { spltr = alt; } alt = null; } return spltr.tryAdvance(action);
712
88
800
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/Joining.java
Accumulator
finisherNoOverflow
class Accumulator { final List<CharSequence> data = new ArrayList<>(); int chars = 0, count = 0; } private static final int CUT_ANYWHERE = 0; private static final int CUT_CODEPOINT = 1; private static final int CUT_GRAPHEME = 2; private static final int CUT_WORD = 3; private static final int CUT_BEFORE_DELIMITER = 4; private static final int CUT_AFTER_DELIMITER = 5; private static final int LENGTH_CHARS = 0; private static final int LENGTH_CODEPOINTS = 1; private static final int LENGTH_GRAPHEMES = 2; private static final int LENGTH_ELEMENTS = 3; private final String delimiter, ellipsis, prefix, suffix; private final int cutStrategy, lenStrategy, maxLength; private int limit, delimCount = -1; private Joining(String delimiter, String ellipsis, String prefix, String suffix, int cutStrategy, int lenStrategy, int maxLength) { this.delimiter = delimiter; this.ellipsis = ellipsis; this.prefix = prefix; this.suffix = suffix; this.cutStrategy = cutStrategy; this.lenStrategy = lenStrategy; this.maxLength = maxLength; } private void init() { if (delimCount == -1) { limit = maxLength - length(prefix, false) - length(suffix, false); delimCount = length(delimiter, false); } } private int length(CharSequence s, boolean content) { switch (lenStrategy) { case LENGTH_CHARS: return s.length(); case LENGTH_CODEPOINTS: if (s instanceof String) return ((String) s).codePointCount(0, s.length()); return (int) s.codePoints().count(); case LENGTH_GRAPHEMES: BreakIterator bi = BreakIterator.getCharacterInstance(); bi.setText(s.toString()); int count = 0; for (int end = bi.next(); end != BreakIterator.DONE; end = bi.next()) count++; return count; case LENGTH_ELEMENTS: return content ? 1 : 0; default: throw new InternalError(); } } private static int copy(char[] buf, int pos, String str) { str.getChars(0, str.length(), buf, pos); return pos + str.length(); } private int copyCut(char[] buf, int pos, String str, int limit, int cutStrategy) { if (limit <= 0) return pos; int endPos = str.length(); switch (lenStrategy) { case LENGTH_CHARS: if (limit < str.length()) endPos = limit; break; case LENGTH_CODEPOINTS: if (limit < str.codePointCount(0, str.length())) endPos = str.offsetByCodePoints(0, limit); break; case LENGTH_GRAPHEMES: BreakIterator bi = BreakIterator.getCharacterInstance(); bi.setText(str); int count = limit, end; while (true) { end = bi.next(); if (end == BreakIterator.DONE) break; if (--count == 0) { endPos = end; break; } } break; case LENGTH_ELEMENTS: break; default: throw new InternalError(); } if (endPos < str.length()) { BreakIterator bi; switch (cutStrategy) { case CUT_BEFORE_DELIMITER: case CUT_AFTER_DELIMITER: endPos = 0; break; case CUT_WORD: bi = BreakIterator.getWordInstance(); bi.setText(str); endPos = bi.preceding(endPos + 1); break; case CUT_GRAPHEME: bi = BreakIterator.getCharacterInstance(); bi.setText(str); endPos = bi.preceding(endPos + 1); break; case CUT_ANYWHERE: break; case CUT_CODEPOINT: if (Character.isHighSurrogate(str.charAt(endPos - 1)) && Character.isLowSurrogate(str.charAt(endPos))) endPos--; break; default: throw new InternalError(); } } str.getChars(0, endPos, buf, pos); return pos + endPos; } private String finisherNoOverflow(Accumulator acc) {<FILL_FUNCTION_BODY>
char[] buf = new char[acc.chars + prefix.length() + suffix.length()]; int size = acc.data.size(); int pos = copy(buf, 0, prefix); for (int i = 0; i < size; i++) { if (i > 0) { pos = copy(buf, pos, delimiter); } pos = copy(buf, pos, acc.data.get(i).toString()); } copy(buf, pos, suffix); return new String(buf);
1,399
148
1,547
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/Limiter.java
Limiter
sortTail
class Limiter<T> extends AbstractCollection<T> { private T[] data; private final int limit; private final Comparator<? super T> comparator; private int size; private boolean initial = true; @SuppressWarnings("unchecked") public Limiter(int limit, Comparator<? super T> comparator) { this.limit = limit; this.comparator = comparator; this.data = (T[]) new Object[Math.min(1000, limit) * 2]; } /** * Accumulate new element * * @param t element to accumulate * * @return false if the element is definitely not included into result, so * any bigger element could be skipped as well, or true if element * will probably be included into result. */ public boolean put(T t) { if (initial) { if (size == data.length) { if (size < limit * 2) { @SuppressWarnings("unchecked") T[] newData = (T[]) new Object[Math.min(limit, size) * 2]; System.arraycopy(data, 0, newData, 0, size); data = newData; } else { Arrays.sort(data, comparator); initial = false; size = limit; } put(t); } else { data[size++] = t; } return true; } if (size == data.length) { sortTail(); } if (comparator.compare(t, data[limit - 1]) < 0) { data[size++] = t; return true; } return false; } /** * Merge other {@code Limiter} object into this (other object becomes unusable after that). * * @param ls other object to merge * @return this object */ public Limiter<T> putAll(Limiter<T> ls) { if (initial && (size + ls.size <= data.length)){ System.arraycopy(ls.data, 0, data, size, ls.size); size += ls.size; return this; } int i = 0; if (!ls.initial) { // sorted part for (; i < limit; i++) { if (!put(ls.data[i])) break; } i = limit; } for (; i < ls.size; i++) { put(ls.data[i]); } return this; } private void sortTail() {<FILL_FUNCTION_BODY>} /** * Must be called after accumulation is finished. After calling * {@code sort()} this Limiter represents the resulting collection. */ public void sort() { if (initial) Arrays.sort(data, 0, size, comparator); else if (size > limit) sortTail(); } @Override public Object[] toArray() { return Arrays.copyOfRange(data, 0, size()); } @Override public Iterator<T> iterator() { return Arrays.asList(data).subList(0, size()).iterator(); } @Override public int size() { return initial && size < limit ? size : limit; } }
// size > limit here T[] d = data; int l = limit, s = size; Comparator<? super T> cmp = comparator; Arrays.sort(d, l, s, cmp); if (cmp.compare(d[s - 1], d[0]) < 0) { // Common case: descending sequence // Assume size - limit <= limit here System.arraycopy(d, 0, d, s - l, 2 * l - s); System.arraycopy(d, l, d, 0, s - l); } else { // Merge presorted 0..limit-1 and limit..size-1 @SuppressWarnings("unchecked") T[] buf = (T[]) new Object[l]; int i = 0, j = l, k = 0; // d[l-1] is guaranteed to be the worst element, thus no need to // check it while (i < l - 1 && k < l && j < s) { if (cmp.compare(d[i], d[j]) <= 0) { buf[k++] = d[i++]; } else { buf[k++] = d[j++]; } } if (k < l) { System.arraycopy(d, i < l - 1 ? i : j, d, k, l - k); } System.arraycopy(buf, 0, d, 0, k); } size = l;
997
418
1,415
<methods>public boolean add(T) ,public boolean addAll(Collection<? extends T>) ,public void clear() ,public boolean contains(java.lang.Object) ,public boolean containsAll(Collection<?>) ,public boolean isEmpty() ,public abstract Iterator<T> iterator() ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean retainAll(Collection<?>) ,public abstract int size() ,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/OrderedCancellableSpliterator.java
OrderedCancellableSpliterator
trySplit
class OrderedCancellableSpliterator<T, A> extends CloneableSpliterator<A, OrderedCancellableSpliterator<T, A>> { private Spliterator<T> source; private final Object lock = new Object(); private final BiConsumer<A, ? super T> accumulator; private final Predicate<A> cancelPredicate; private final BinaryOperator<A> combiner; private final Supplier<A> supplier; private volatile boolean localCancelled; private volatile OrderedCancellableSpliterator<T, A> prefix; private volatile OrderedCancellableSpliterator<T, A> suffix; private A payload; OrderedCancellableSpliterator(Spliterator<T> source, Supplier<A> supplier, BiConsumer<A, ? super T> accumulator, BinaryOperator<A> combiner, Predicate<A> cancelPredicate) { this.source = source; this.supplier = supplier; this.accumulator = accumulator; this.combiner = combiner; this.cancelPredicate = cancelPredicate; } @Override public boolean tryAdvance(Consumer<? super A> action) { Spliterator<T> source = this.source; if (source == null || localCancelled) { this.source = null; return false; } A acc = supplier.get(); try { source.forEachRemaining(t -> { accumulator.accept(acc, t); if (cancelPredicate.test(acc)) { cancelSuffix(); throw new CancelException(); } if (localCancelled) { throw new CancelException(); } }); } catch (CancelException ex) { if (localCancelled) { return false; } } this.source = null; A result = acc; while (true) { if (prefix == null && suffix == null) { action.accept(result); return true; } ArrayDeque<A> res = new ArrayDeque<>(); res.offer(result); synchronized (lock) { if (localCancelled) return false; OrderedCancellableSpliterator<T, A> s = prefix; while (s != null) { if (s.payload == null) break; res.offerFirst(s.payload); s = s.prefix; } prefix = s; if (s != null) { s.suffix = this; } s = suffix; while (s != null) { if (s.payload == null) break; res.offerLast(s.payload); s = s.suffix; } suffix = s; if (s != null) { s.prefix = this; } if (res.size() == 1) { if (prefix == null && suffix == null) { action.accept(result); return true; } this.payload = result; break; } } result = res.pollFirst(); while (!res.isEmpty()) { result = combiner.apply(result, res.pollFirst()); if (cancelPredicate.test(result)) { cancelSuffix(); } } } return false; } private void cancelSuffix() { if (this.suffix == null) return; synchronized (lock) { OrderedCancellableSpliterator<T, A> suffix = this.suffix; while (suffix != null && !suffix.localCancelled) { suffix.prefix = null; suffix.localCancelled = true; suffix = suffix.suffix; } this.suffix = null; } } @Override public void forEachRemaining(Consumer<? super A> action) { tryAdvance(action); } @Override public Spliterator<A> trySplit() {<FILL_FUNCTION_BODY>} @Override public long estimateSize() { return source == null ? 0 : source.estimateSize(); } @Override public int characteristics() { return source == null ? SIZED : ORDERED; } }
if (source == null || localCancelled) { source = null; return null; } Spliterator<T> prefix = source.trySplit(); if (prefix == null) { return null; } synchronized (lock) { OrderedCancellableSpliterator<T, A> result = doClone(); result.source = prefix; this.prefix = result; result.suffix = this; OrderedCancellableSpliterator<T, A> prefixPrefix = result.prefix; if (prefixPrefix != null) prefixPrefix.suffix = result; return result; }
1,260
186
1,446
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/PairPermutationSpliterator.java
PairPermutationSpliterator
isqrt
class PairPermutationSpliterator<T, R> extends CloneableSpliterator<R, PairPermutationSpliterator<T, R>> { private long cur; private long limit; private final int size; private int idx1; private int idx2; private final List<T> list; private final BiFunction<? super T, ? super T, ? extends R> mapper; public PairPermutationSpliterator(List<T> list, BiFunction<? super T, ? super T, ? extends R> mapper) { this.list = list; this.size = list.size(); this.idx2 = 1; this.limit = size * (size - 1L) / 2; this.mapper = mapper; } @Override public long estimateSize() { return limit - cur; } @Override public int characteristics() { return ORDERED | SIZED | SUBSIZED; } /* * Calculates (int) (Math.sqrt(8 * n + 1)-1)/2 Produces exact result for any * long input from 0 to 0x1FFFFFFFC0000000L (2^61-2^30). */ static int isqrt(long n) {<FILL_FUNCTION_BODY>} @Override public Spliterator<R> trySplit() { long size = limit - cur; if (size >= 2) { PairPermutationSpliterator<T, R> clone = doClone(); clone.limit = this.cur = this.cur + size / 2; int s = this.size; long rev = s * (s - 1L) / 2 - this.cur - 1; int row = isqrt(rev); int col = (int) (rev - (row) * (row + 1L) / 2); this.idx1 = s - row - 2; this.idx2 = s - col - 1; return clone; } return null; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (cur == limit) return false; action.accept(mapper.apply(list.get(idx1), list.get(idx2))); cur++; if (++idx2 == size) { idx2 = ++idx1 + 1; } return true; } @Override public void forEachRemaining(Consumer<? super R> action) { int idx1 = this.idx1; int idx2 = this.idx2; int size = this.size; long cur = this.cur; long limit = this.limit; while (cur < limit) { T item1 = list.get(idx1++); while (cur < limit && idx2 < size) { T item2 = list.get(idx2++); action.accept(mapper.apply(item1, item2)); cur++; } idx2 = idx1 + 1; } this.cur = this.limit; } }
int x = (int) ((Math.sqrt(8.0 * n + 1.0) - 1.0) / 2.0); if (x * (x + 1L) / 2 > n) x--; return x;
893
71
964
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/PairSpliterator.java
PSOfInt
forEachRemaining
class PSOfInt extends PairSpliterator<Integer, Spliterator.OfInt, Integer, PSOfInt> implements Spliterator.OfInt, IntConsumer { private final IntBinaryOperator mapper; private final IntUnaryOperator unaryMapper; private int cur; PSOfInt(IntBinaryOperator mapper, IntUnaryOperator unaryMapper, Spliterator.OfInt source, int mode) { super(source, mode, null); this.mapper = mapper; this.unaryMapper = unaryMapper; } @Override public void accept(int t) { cur = t; } private BiConsumer<Integer, Integer> fn(IntConsumer action) { switch (mode) { case MODE_MAP_FIRST: return (a, b) -> action.accept(a == null ? unaryMapper.applyAsInt(b) : b); case MODE_MAP_LAST: return (a, b) -> action.accept(b == null ? unaryMapper.applyAsInt(a) : a); default: return (a, b) -> action.accept(mapper.applyAsInt(a, b)); } } @Override public boolean tryAdvance(IntConsumer action) { Sink<Integer> l = left, r = right; if (l != null) { left = null; if (!source.tryAdvance(this)) { right = null; return l.connect(r, fn(action)); } if (l.push(cur, fn(action), false)) return true; } int prev = cur; if (!source.tryAdvance(this)) { right = null; return r != null && r.push(prev, fn(action), true); } action.accept(mapper.applyAsInt(prev, cur)); return true; } @Override public void forEachRemaining(IntConsumer action) {<FILL_FUNCTION_BODY>} }
BiConsumer<Integer, Integer> fn = fn(action); source.forEachRemaining((int next) -> { if (left != null) { left.push(cur = next, fn, false); left = null; } else { action.accept(mapper.applyAsInt(cur, cur = next)); } }); finish(fn, cur);
572
111
683
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/PermutationSpliterator.java
PermutationSpliterator
step
class PermutationSpliterator implements Spliterator<int[]> { private static final long[] factorials = { 1L, 1L, 2L, 6L, 24L, 120L, 720L, 5040L, 40320L, 362880L, 3628800L, 39916800L, 479001600L, 6227020800L, 87178291200L, 1307674368000L, 20922789888000L, 355687428096000L, 6402373705728000L, 121645100408832000L, 2432902008176640000L }; private final int[] value; private long remainingSize; private final long fence; public PermutationSpliterator(int length) { Internals.checkNonNegative("Length", length); if (length >= factorials.length) throw new IllegalArgumentException("Length " + length + " is bigger than " + factorials.length + ": not supported"); this.value = new int[length]; for (int i = 0; i < length; i++) this.value[i] = i; this.fence = this.remainingSize = factorials[length]; } private PermutationSpliterator(int[] startValue, long fence, long remainingSize) { this.value = startValue; this.fence = fence; this.remainingSize = remainingSize; } @Override public boolean tryAdvance(Consumer<? super int[]> action) { if (remainingSize == 0) return false; int[] value = this.value; action.accept(value.clone()); if (--remainingSize > 0) { step(value); } return true; } @Override public void forEachRemaining(Consumer<? super int[]> action) { long rs = remainingSize; if (rs == 0) return; remainingSize = 0; int[] value = this.value; action.accept(value.clone()); while (--rs > 0) { step(value); action.accept(value.clone()); } } private static void step(int[] value) {<FILL_FUNCTION_BODY>} @Override public Spliterator<int[]> trySplit() { if (remainingSize <= 1) return null; int[] newValue = value.clone(); int used = -1; // clear bit = used position long newRemainingSize = remainingSize / 2; long newPos = fence - (remainingSize -= newRemainingSize); long s = newPos; for (int i = 0; i < value.length; i++) { long f = factorials[value.length - i - 1]; int rem = (int) (s / f); s %= f; int idx = -1; while (rem >= 0) { idx = Integer.numberOfTrailingZeros(used >> (idx + 1)) + idx + 1; rem--; } used &= ~(1 << idx); value[i] = idx; } return new PermutationSpliterator(newValue, newPos, newRemainingSize); } @Override public long estimateSize() { return remainingSize; } @Override public int characteristics() { return ORDERED | DISTINCT | NONNULL | IMMUTABLE | SIZED | SUBSIZED; } }
int r = value.length - 1, k = r - 1; while (value[k] > value[k + 1]) k--; int vk = value[k], l = r; while (vk > value[l]) l--; value[k] = value[l]; value[l] = vk; for (k++; k < r; k++, r--) { int tmp = value[k]; value[k] = value[r]; value[r] = tmp; }
1,096
157
1,253
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/PrefixOps.java
IntPrefixBuffer
drainOne
class IntPrefixBuffer extends PrefixBuffer implements IntConsumer { private final int[] buf = new int[BUF_SIZE]; private int prevBufferLast; boolean init(Spliterator.OfInt source) { if (idx == 0) { int i = 0; while (i < BUF_SIZE && source.tryAdvance(this)) { i++; } if (idx == 0) { return false; } int last = buf[idx - 1]; isFirst = isFirst || accRef.compareAndSet(Long.MAX_VALUE, last); if (!isFirst) { prevBufferLast = (int) accRef.getAndAccumulate(last, op); } } return true; } void drainOne(IntConsumer action) {<FILL_FUNCTION_BODY>} void drainAll(IntConsumer action) { if (!isInit()) return; if (isFirst) { for (int i = 0; i < idx; i++) { action.accept(buf[i]); } isFirst = false; } else { for (int i = 0; i < idx; i++) { action.accept(localOp.applyAsInt(buf[i], prevBufferLast)); } } idx = 0; } @Override public void accept(int value) { if (idx == 0) { buf[idx++] = value; } else { int prev = buf[idx - 1]; buf[idx++] = localOp.applyAsInt(prev, value); } } }
int value = buf[--idx]; if (isFirst) { action.accept(value); if (idx == 0) { isFirst = false; } } else { action.accept(localOp.applyAsInt(value, prevBufferLast)); }
477
85
562
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/PrependSpliterator.java
PrependSpliterator
estimateSize
class PrependSpliterator<T> implements TailSpliterator<T> { private Spliterator<T> source; private T element; private int mode; public PrependSpliterator(Spliterator<T> source, T element) { this.source = source; this.element = element; this.mode = source.estimateSize() < Long.MAX_VALUE - 1 ? 1 : 2; } @Override public boolean tryAdvance(Consumer<? super T> action) { if (mode == 0) return source.tryAdvance(action); action.accept(element); element = null; mode = 0; return true; } @Override public Spliterator<T> tryAdvanceOrTail(Consumer<? super T> action) { if (mode == 0) { Spliterator<T> s = source; source = null; return s; } action.accept(element); element = null; mode = 0; return this; } @Override public void forEachRemaining(Consumer<? super T> action) { if (mode != 0) action.accept(element); element = null; mode = 0; source.forEachRemaining(action); } @Override public Spliterator<T> forEachOrTail(Consumer<? super T> action) { if (mode != 0) { action.accept(element); } Spliterator<T> s = source; element = null; mode = 0; source = null; return s; } @Override public Spliterator<T> trySplit() { if (mode == 0) return source.trySplit(); mode = 0; return new ConstSpliterator.OfRef<>(element, 1, true); } @Override public long estimateSize() {<FILL_FUNCTION_BODY>} @Override public int characteristics() { switch (mode) { case 1: return source.characteristics() & (ORDERED | SIZED | SUBSIZED); case 2: return source.characteristics() & ORDERED; default: return source.characteristics(); } } }
long size = source.estimateSize(); return mode == 0 || size == Long.MAX_VALUE ? size : size + 1;
678
38
716
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/RangeBasedSpliterator.java
OfSubLists
forEachRemaining
class OfSubLists<T> extends RangeBasedSpliterator<List<T>, OfSubLists<T>> { private final List<T> source; private final int length; private final int shift; private final int listSize; public OfSubLists(List<T> source, int length, int shift) { super(0, Math.max(0, source.size() - Math.max(length - shift, 0) - 1) / shift + 1); this.source = source; this.listSize = source.size(); this.shift = shift; this.length = length; } @Override public boolean tryAdvance(Consumer<? super List<T>> action) { if (cur < limit) { int start = cur * shift; int stop = listSize - length > start ? start + length : listSize; action.accept(source.subList(start, stop)); cur++; return true; } return false; } @Override public void forEachRemaining(Consumer<? super List<T>> action) {<FILL_FUNCTION_BODY>} }
int l = limit, c = cur, ll = length, sf = shift, ls = listSize; int start = cur * sf; while (c < l) { int stop = ls - ll > start ? start + ll : ls; action.accept(source.subList(start, stop)); start += sf; c++; } cur = limit;
323
110
433
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/StreamContext.java
StreamContext
sequential
class StreamContext { static final StreamContext SEQUENTIAL = new StreamContext(false); static final StreamContext PARALLEL = new StreamContext(true); boolean parallel; ForkJoinPool fjp; Runnable closeHandler; private StreamContext(boolean parallel) { this.parallel = parallel; } <T> T terminate(Supplier<T> terminalOperation) { return fjp.submit(terminalOperation::get).join(); } <T, U> T terminate(U value, Function<U, T> terminalOperation) { return fjp.submit(() -> terminalOperation.apply(value)).join(); } StreamContext parallel() { if (this == SEQUENTIAL) return PARALLEL; this.parallel = true; this.fjp = null; return this; } StreamContext sequential() {<FILL_FUNCTION_BODY>} StreamContext parallel(ForkJoinPool fjp) { StreamContext context = detach(); context.parallel = true; context.fjp = fjp; return context; } StreamContext detach() { if (this == PARALLEL || this == SEQUENTIAL) return new StreamContext(parallel); return this; } StreamContext onClose(Runnable r) { StreamContext context = detach(); context.closeHandler = compose(context.closeHandler, r); return context; } void close() { if (closeHandler != null) { Runnable r = closeHandler; closeHandler = null; r.run(); } } static Runnable compose(Runnable r1, Runnable r2) { if (r1 == null) return r2; return () -> { try { r1.run(); } catch (Throwable t1) { try { r2.run(); } catch (Throwable t2) { t1.addSuppressed(t2); } throw t1; } r2.run(); }; } StreamContext combine(BaseStream<?, ?> other) { if (other == null) return this; StreamContext otherStrategy = of(other); StreamContext result = this; if (other.isParallel() && !parallel) result = parallel(); if (otherStrategy.closeHandler != null) result = result.onClose(otherStrategy.closeHandler); return result; } static StreamContext of(BaseStream<?, ?> stream) { if (stream instanceof BaseStreamEx) return ((BaseStreamEx<?, ?, ?, ?>) stream).context; return new StreamContext(stream.isParallel()).onClose(stream::close); } }
if (this == PARALLEL) return SEQUENTIAL; this.parallel = false; this.fjp = null; return this;
829
51
880
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/TailConcatSpliterator.java
TailConcatSpliterator
tryAdvance
class TailConcatSpliterator<T> implements TailSpliterator<T> { private Spliterator<T> left, right; private int characteristics; private long size; @SuppressWarnings("unchecked") public TailConcatSpliterator(Spliterator<? extends T> left, Spliterator<? extends T> right) { this.left = (Spliterator<T>) left; this.right = (Spliterator<T>) right; this.characteristics = left.characteristics() & right.characteristics() & (ORDERED | SIZED | SUBSIZED); this.size = left.estimateSize() + right.estimateSize(); if (this.size < 0) { this.size = Long.MAX_VALUE; this.characteristics &= (~SIZED) & (~SUBSIZED); } } @Override public boolean tryAdvance(Consumer<? super T> action) {<FILL_FUNCTION_BODY>} @Override public Spliterator<T> tryAdvanceOrTail(Consumer<? super T> action) { if (left == null || !left.tryAdvance(action)) { Spliterator<T> s = right; right = null; return s; } if (size > 0 && size != Long.MAX_VALUE) size--; return this; } @Override public void forEachRemaining(Consumer<? super T> action) { if (left != null) left.forEachRemaining(action); if (right != null) TailSpliterator.forEachWithTail(right, action); } @Override public Spliterator<T> forEachOrTail(Consumer<? super T> action) { if (left != null) left.forEachRemaining(action); Spliterator<T> s = right; right = null; return s; } @Override public Spliterator<T> trySplit() { if (left == null) return right.trySplit(); Spliterator<T> s = left; left = null; return s; } @Override public long estimateSize() { if (left == null) return right == null ? 0 : right.estimateSize(); return size; } @Override public int characteristics() { return characteristics; } }
if (left != null) { if (left.tryAdvance(action)) { if (size > 0 && size != Long.MAX_VALUE) size--; return true; } left = null; } if (right != null) right = TailSpliterator.tryAdvanceWithTail(right, action); return right != null;
706
115
821
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/UnknownSizeSpliterator.java
USOfRef
forEachRemaining
class USOfRef<T> extends UnknownSizeSpliterator<T, USOfRef<T>, Iterator<? extends T>> { Object[] array; USOfRef(Iterator<? extends T> iterator) { super(iterator); } USOfRef(Object[] array, int index, int fence) { super(index, fence); this.array = array; } @Override public Spliterator<T> trySplit() { Iterator<? extends T> i = it; if (i != null) { int n = getN(); Object[] a = new Object[n]; int j = 0; while (i.hasNext() && j < n) { a[j++] = i.next(); } fence = j; if (i.hasNext()) { return correctSize(new USOfRef<>(a, 0, j)); } it = null; array = a; } int lo = index, mid = (lo + fence) >>> 1; return (lo >= mid) ? null : correctSize(new USOfRef<>(array, lo, index = mid)); } @Override public void forEachRemaining(Consumer<? super T> action) {<FILL_FUNCTION_BODY>} @Override public boolean tryAdvance(Consumer<? super T> action) { if (it != null) { if (it.hasNext()) { action.accept(it.next()); return true; } it = null; index = fence; } else if (index < fence) { @SuppressWarnings("unchecked") T t = (T) array[index++]; action.accept(t); return true; } est = 0; return false; } }
if (it != null) it.forEachRemaining(action); else { Object[] a = array; int i = index, hi = fence; while (i < hi) { @SuppressWarnings("unchecked") T t = (T) a[i++]; action.accept(t); } } index = fence; est = 0;
531
119
650
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/UnorderedCancellableSpliterator.java
UnorderedCancellableSpliterator
handleCancel
class UnorderedCancellableSpliterator<T, A> extends CloneableSpliterator<A, UnorderedCancellableSpliterator<T, A>> { private volatile Spliterator<T> source; private final BiConsumer<A, ? super T> accumulator; private final Predicate<A> cancelPredicate; private final Supplier<A> supplier; private final ConcurrentLinkedQueue<A> partialResults = new ConcurrentLinkedQueue<>(); private final AtomicBoolean cancelled = new AtomicBoolean(false); private final AtomicInteger nPeers = new AtomicInteger(1); private final BinaryOperator<A> combiner; private boolean flag; UnorderedCancellableSpliterator(Spliterator<T> source, Supplier<A> supplier, BiConsumer<A, ? super T> accumulator, BinaryOperator<A> combiner, Predicate<A> cancelPredicate) { this.source = source; this.supplier = supplier; this.accumulator = accumulator; this.combiner = combiner; this.cancelPredicate = cancelPredicate; } private boolean checkCancel(A acc) { if (cancelPredicate.test(acc)) { if (cancelled.compareAndSet(false, true)) { flag = true; return true; } } if (cancelled.get()) { flag = false; return true; } return false; } private boolean handleCancel(Consumer<? super A> action, A acc) {<FILL_FUNCTION_BODY>} @Override public boolean tryAdvance(Consumer<? super A> action) { Spliterator<T> source = this.source; if (source == null || cancelled.get()) { this.source = null; return false; } A acc = supplier.get(); if (checkCancel(acc)) return handleCancel(action, acc); try { source.forEachRemaining(t -> { accumulator.accept(acc, t); if (checkCancel(acc)) throw new CancelException(); }); } catch (CancelException ex) { return handleCancel(action, acc); } A result = acc; while (true) { A acc2 = partialResults.poll(); if (acc2 == null) break; result = combiner.apply(result, acc2); if (checkCancel(result)) return handleCancel(action, result); } partialResults.offer(result); this.source = null; if (nPeers.decrementAndGet() == 0) { result = partialResults.poll(); // non-cancelled finish while (true) { A acc2 = partialResults.poll(); if (acc2 == null) break; result = combiner.apply(result, acc2); if (cancelPredicate.test(result)) break; } this.source = null; action.accept(result); return true; } return false; } @Override public void forEachRemaining(Consumer<? super A> action) { tryAdvance(action); } @Override public Spliterator<A> trySplit() { if (source == null || cancelled.get()) { source = null; return null; } Spliterator<T> prefix = source.trySplit(); if (prefix == null) { return null; } UnorderedCancellableSpliterator<T, A> result = doClone(); result.source = prefix; nPeers.incrementAndGet(); return result; } @Override public long estimateSize() { return source == null ? 0 : source.estimateSize(); } @Override public int characteristics() { return source == null ? SIZED : 0; } }
source = null; if (flag) { action.accept(acc); return true; } return false;
1,134
44
1,178
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/VersionSpecific.java
VersionSpecific
callMapMultiToInt
class VersionSpecific { <T, S extends AbstractStreamEx<T, S>> S callWhile(AbstractStreamEx<T, S> stream, Predicate<? super T> predicate, boolean drop) { Spliterator<T> spltr = stream.spliterator(); return stream.supply( spltr.hasCharacteristics(Spliterator.ORDERED) ? new TakeDrop.TDOfRef<>(spltr, drop, false, predicate) : new TakeDrop.UnorderedTDOfRef<T>(spltr, drop, false, predicate)); } IntStreamEx callWhile(IntStreamEx stream, IntPredicate predicate, boolean drop) { return stream.delegate(new TakeDrop.TDOfInt(stream.spliterator(), drop, false, predicate)); } LongStreamEx callWhile(LongStreamEx stream, LongPredicate predicate, boolean drop) { return stream.delegate(new TakeDrop.TDOfLong(stream.spliterator(), drop, false, predicate)); } DoubleStreamEx callWhile(DoubleStreamEx stream, DoublePredicate predicate, boolean drop) { return stream.delegate(new TakeDrop.TDOfDouble(stream.spliterator(), drop, false, predicate)); } <T, R> StreamEx<R> callMapMulti(AbstractStreamEx<T, ?> s, BiConsumer<? super T, ? super Consumer<R>> mapper) { return s.flatCollection(e -> { List<R> result = new ArrayList<>(); mapper.accept(e, (Consumer<R>) result::add); return result; }); } <T> IntStreamEx callMapMultiToInt(AbstractStreamEx<T, ?> s, BiConsumer<? super T, ? super IntConsumer> mapper) {<FILL_FUNCTION_BODY>} <T> LongStreamEx callMapMultiToLong(AbstractStreamEx<T, ?> s, BiConsumer<? super T, ? super LongConsumer> mapper) { return s.flatMapToLong(e -> { Internals.LongBuffer result = new Internals.LongBuffer(); mapper.accept(e, (LongConsumer) result::add); return result.stream(); }); } <T> DoubleStreamEx callMapMultiToDouble(AbstractStreamEx<T, ?> s, BiConsumer<? super T, ? super DoubleConsumer> mapper) { return s.flatMapToDouble(e -> { Internals.DoubleBuffer result = new Internals.DoubleBuffer(); mapper.accept(e, (DoubleConsumer) result::add); return result.stream(); }); } IntStream ofChars(CharSequence seq) { // In JDK 8 there's only default chars() method which uses // IteratorSpliterator // In JDK 9 chars() method for most of implementations is much better return CharBuffer.wrap(seq).chars(); } }
return s.flatMapToInt(e -> { Internals.IntBuffer result = new Internals.IntBuffer(); mapper.accept(e, (IntConsumer) result::add); return result.stream(); });
729
60
789
<no_super_class>
amaembo_streamex
streamex/src/main/java/one/util/streamex/WithFirstSpliterator.java
WithFirstSpliterator
forEachRemaining
class WithFirstSpliterator<T, R> extends CloneableSpliterator<R, WithFirstSpliterator<T, R>> implements Consumer<T> { private static final int STATE_NONE = 0; private static final int STATE_FIRST_READ = 1; private static final int STATE_INIT = 2; private static final int STATE_EMPTY = 3; private ReentrantLock lock; private Spliterator<T> source; private WithFirstSpliterator<T, R> prefix; private volatile T first; private volatile int state = STATE_NONE; private final BiFunction<? super T, ? super T, ? extends R> mapper; private Consumer<? super R> action; WithFirstSpliterator(Spliterator<T> source, BiFunction<? super T, ? super T, ? extends R> mapper) { this.source = source; this.mapper = mapper; } private void acquire() { if (lock != null && state == STATE_NONE) { lock.lock(); } } private void release() { if (lock != null && lock.isHeldByCurrentThread()) { lock.unlock(); } } @Override public boolean tryAdvance(Consumer<? super R> action) { if (state == STATE_NONE) { acquire(); try { doInit(); } finally { release(); } } if (state == STATE_FIRST_READ) { state = STATE_INIT; action.accept(mapper.apply(first, first)); return true; } if (state != STATE_INIT) return false; this.action = action; boolean hasNext = source.tryAdvance(this); this.action = null; return hasNext; } private void doInit() { int prefixState = state; if (prefixState != STATE_NONE) return; if (prefix != null) { prefix.doInit(); prefixState = prefix.state; } if (prefixState == STATE_FIRST_READ || prefixState == STATE_INIT) { first = prefix.first; state = STATE_INIT; return; } state = source.tryAdvance(x -> first = x) ? STATE_FIRST_READ : STATE_EMPTY; } @Override public void forEachRemaining(Consumer<? super R> action) {<FILL_FUNCTION_BODY>} @Override public Spliterator<R> trySplit() { if (state != STATE_NONE) return null; Spliterator<T> prefix; if (lock == null) lock = new ReentrantLock(); acquire(); try { if (state != STATE_NONE) return null; prefix = source.trySplit(); if (prefix == null) return null; WithFirstSpliterator<T, R> result = doClone(); result.source = prefix; return this.prefix = result; } finally { release(); } } @Override public long estimateSize() { return source.estimateSize(); } @Override public int characteristics() { return NONNULL | (source.characteristics() & (DISTINCT | IMMUTABLE | CONCURRENT | ORDERED | (lock == null ? SIZED : 0))); } @Override public void accept(T x) { action.accept(mapper.apply(first, x)); } }
acquire(); int myState = state; this.action = action; if (myState == STATE_FIRST_READ || myState == STATE_INIT) { release(); if (myState == STATE_FIRST_READ) { state = STATE_INIT; accept(first); } source.forEachRemaining(this); this.action = null; return; } try { Consumer<T> init = x -> { if (state == STATE_NONE) { if (prefix != null) { prefix.doInit(); } this.first = (prefix == null || prefix.state == STATE_EMPTY) ? x : prefix.first; state = STATE_INIT; } release(); }; source.forEachRemaining(init.andThen(this)); this.action = null; } finally { release(); }
1,071
276
1,347
<methods>public non-sealed void <init>() <variables>
amaembo_streamex
streamex/src/main/java/one/util/streamex/ZipSpliterator.java
ZipSpliterator
arraySplit
class ZipSpliterator<U, V, R> implements Spliterator<R> { private Spliterator<U> left; private Spliterator<V> right; private final BiFunction<? super U, ? super V, ? extends R> mapper; private boolean trySplit; private int batch = 0; private final Box<U> l = new Box<>(); private final Box<V> r = new Box<>(); ZipSpliterator(Spliterator<U> left, Spliterator<V> right, BiFunction<? super U, ? super V, ? extends R> mapper, boolean trySplit) { this.left = left; this.right = right; this.mapper = mapper; this.trySplit = trySplit; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (left.tryAdvance(l) && right.tryAdvance(r)) { action.accept(mapper.apply(l.a, r.a)); return true; } return false; } @Override public void forEachRemaining(Consumer<? super R> action) { if (!hasCharacteristics(SIZED)) { Spliterator.super.forEachRemaining(action); return; } long leftSize = left.getExactSizeIfKnown(); long rightSize = right.getExactSizeIfKnown(); if (leftSize <= rightSize) { left.forEachRemaining(u -> { if (right.tryAdvance(r)) { action.accept(mapper.apply(u, r.a)); } }); } else { right.forEachRemaining(v -> { if (left.tryAdvance(l)) { action.accept(mapper.apply(l.a, v)); } }); } } @Override public Spliterator<R> trySplit() { if (trySplit && hasCharacteristics(SIZED | SUBSIZED)) { Spliterator<U> leftPrefix = left.trySplit(); if (leftPrefix == null) return arraySplit(); Spliterator<V> rightPrefix = right.trySplit(); if (rightPrefix == null) { left = new TailConcatSpliterator<>(leftPrefix, left); return arraySplit(); } long leftSize = leftPrefix.getExactSizeIfKnown(); long rightSize = rightPrefix.getExactSizeIfKnown(); if (leftSize >= 0 && rightSize >= 0) { if (leftSize == rightSize) { return new ZipSpliterator<>(leftPrefix, rightPrefix, mapper, true); } if (Math.abs(leftSize - rightSize) < Math.min(BATCH_UNIT, Math.max(leftSize, rightSize) / 8)) { if (leftSize < rightSize) { @SuppressWarnings("unchecked") U[] array = (U[]) new Object[(int) (rightSize - leftSize)]; drainTo(array, left); leftPrefix = new TailConcatSpliterator<>(leftPrefix, Spliterators.spliterator(array, characteristics())); } else { @SuppressWarnings("unchecked") V[] array = (V[]) new Object[(int) (leftSize - rightSize)]; drainTo(array, right); rightPrefix = new TailConcatSpliterator<>(rightPrefix, Spliterators.spliterator(array, characteristics())); } this.trySplit = false; return new ZipSpliterator<>(leftPrefix, rightPrefix, mapper, false); } } left = new TailConcatSpliterator<>(leftPrefix, left); right = new TailConcatSpliterator<>(rightPrefix, right); } return arraySplit(); } private Spliterator<R> arraySplit() {<FILL_FUNCTION_BODY>} @Override public long estimateSize() { return Math.min(left.estimateSize(), right.estimateSize()); } @Override public int characteristics() { // Remove SORTED, NONNULL, DISTINCT return left.characteristics() & right.characteristics() & (SIZED | SUBSIZED | ORDERED | IMMUTABLE | CONCURRENT); } }
long s = estimateSize(); if (s <= 1) return null; int n = batch + BATCH_UNIT; if (n > s) n = (int) s; if (n > MAX_BATCH) n = MAX_BATCH; @SuppressWarnings("unchecked") R[] array = (R[]) new Object[n]; int index = drainTo(array, this); if ((batch = index) == 0) return null; long s2 = estimateSize(); USOfRef<R> prefix = new UnknownSizeSpliterator.USOfRef<>(array, 0, index); if (hasCharacteristics(SUBSIZED)) prefix.est = index; else if (s == s2) prefix.est = Math.max(index, s / 2); else prefix.est = Math.max(index, s2 - s); return prefix;
1,218
260
1,478
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/cache/CommentCache.java
CommentCache
getComment
class CommentCache { /** * Comment cache. */ private static final Cache cache = CacheFactory.getCache(Comment.COMMENTS); /** * Gets a comment by the specified comment id. * * @param id the specified comment id * @return comment, returns {@code null} if not found */ public JSONObject getComment(final String id) {<FILL_FUNCTION_BODY>} /** * Adds or updates the specified comment. * * @param comment the specified comment */ public void putComment(final JSONObject comment) { cache.put(comment.optString(Keys.OBJECT_ID), JSONs.clone(comment)); } /** * Removes a comment by the specified comment id. * * @param id the specified comment id */ public void removeComment(final String id) { cache.remove(id); } }
final JSONObject comment = cache.get(id); if (null == comment) { return null; } return JSONs.clone(comment);
238
44
282
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/cache/DomainCache.java
DomainCache
loadDomains
class DomainCache { /** * Domains. */ private static final List<JSONObject> DOMAINS = new ArrayList<>(); /** * Lock. */ private static final ReadWriteLock LOCK = new ReentrantReadWriteLock(); /** * Domain query service. */ @Inject private DomainQueryService domainQueryService; /** * Gets domains with the specified fetch size. * * @param fetchSize the specified fetch size * @return domains */ public List<JSONObject> getDomains(final int fetchSize) { LOCK.readLock().lock(); try { if (DOMAINS.isEmpty()) { return Collections.emptyList(); } final int end = fetchSize >= DOMAINS.size() ? DOMAINS.size() : fetchSize; return JSONs.clone(DOMAINS.subList(0, end)); } finally { LOCK.readLock().unlock(); } } /** * Loads domains. */ public void loadDomains() {<FILL_FUNCTION_BODY>} }
LOCK.writeLock().lock(); try { DOMAINS.clear(); DOMAINS.addAll(domainQueryService.getMostTagNaviDomains(Integer.MAX_VALUE)); } finally { LOCK.writeLock().unlock(); }
297
70
367
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/cache/OptionCache.java
OptionCache
getOption
class OptionCache { /** * Option cache. */ private static final Cache CACHE = CacheFactory.getCache(Option.OPTIONS); /** * Gets an option by the specified option id. * * @param id the specified option id * @return option, returns {@code null} if not found */ public JSONObject getOption(final String id) {<FILL_FUNCTION_BODY>} /** * Adds or updates the specified option. * * @param option the specified option */ public void putOption(final JSONObject option) { CACHE.put(option.optString(Keys.OBJECT_ID), JSONs.clone(option)); } /** * Removes an option by the specified option id. * * @param id the specified option id */ public void removeOption(final String id) { CACHE.remove(id); } }
final JSONObject option = CACHE.get(id); if (null == option) { return null; } return JSONs.clone(option);
244
46
290
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/cache/UserCache.java
UserCache
getUserByName
class UserCache { /** * Id, User. */ private static final Map<String, JSONObject> ID_CACHE = new ConcurrentHashMap<>(); /** * Name, User. */ private static final Map<String, JSONObject> NAME_CACHE = new ConcurrentHashMap<>(); /** * Administrators cache. */ private static final List<JSONObject> ADMINS_CACHE = new CopyOnWriteArrayList<>(); /** * Gets admins. * * @return admins */ public List<JSONObject> getAdmins() { return ADMINS_CACHE; } /** * Puts the specified admins. * * @param admins the specified admins */ public void putAdmins(final List<JSONObject> admins) { ADMINS_CACHE.clear(); ADMINS_CACHE.addAll(admins); } /** * Gets a user by the specified user id. * * @param userId the specified user id * @return user, returns {@code null} if not found */ public JSONObject getUser(final String userId) { final JSONObject user = ID_CACHE.get(userId); if (null == user) { return null; } return JSONs.clone(user); } /** * Gets a user by the specified user name. * * @param userName the specified user name * @return user, returns {@code null} if not found */ public JSONObject getUserByName(final String userName) {<FILL_FUNCTION_BODY>} /** * Adds or updates the specified user. * * @param user the specified user */ public void putUser(final JSONObject user) { ID_CACHE.put(user.optString(Keys.OBJECT_ID), JSONs.clone(user)); NAME_CACHE.put(user.optString(User.USER_NAME), JSONs.clone(user)); Sessions.put(user.optString(Keys.OBJECT_ID), user); } /** * Removes the the specified user. * * @param user the specified user */ public void removeUser(final JSONObject user) { ID_CACHE.remove(user.optString(Keys.OBJECT_ID)); NAME_CACHE.remove(user.optString(User.USER_NAME)); } }
final JSONObject user = NAME_CACHE.get(userName); if (null == user) { return null; } return JSONs.clone(user);
657
49
706
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/ArticleAddAudioHandler.java
ArticleAddAudioHandler
action
class ArticleAddAudioHandler extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ArticleAddAudioHandler.class); /** * Article management service. */ @Inject private ArticleMgmtService articleMgmtService; /** * Gets the event type {@linkplain EventTypes#ADD_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.ADD_ARTICLE; } @Override public void action(final Event<JSONObject> event) {<FILL_FUNCTION_BODY>} }
final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); final JSONObject originalArticle = data.optJSONObject(Article.ARTICLE); articleMgmtService.genArticleAudio(originalArticle);
182
89
271
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/ArticleBaiduSender.java
ArticleBaiduSender
sendToBaidu
class ArticleBaiduSender extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ArticleBaiduSender.class); /** * Sends the specified URLs to Baidu. * * @param urls the specified URLs */ public static void sendToBaidu(final String... urls) {<FILL_FUNCTION_BODY>} @Override public void action(final Event<JSONObject> event) { final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); if (Latkes.RuntimeMode.PRODUCTION != Latkes.getRuntimeMode() || StringUtils.isBlank(Symphonys.BAIDU_DATA_TOKEN)) { return; } try { final JSONObject article = data.getJSONObject(Article.ARTICLE); final int articleType = article.optInt(Article.ARTICLE_TYPE); if (Article.ARTICLE_TYPE_C_DISCUSSION == articleType || Article.ARTICLE_TYPE_C_THOUGHT == articleType) { return; } final String tags = article.optString(Article.ARTICLE_TAGS); if (StringUtils.containsIgnoreCase(tags, Tag.TAG_TITLE_C_SANDBOX)) { return; } final String articlePermalink = Latkes.getServePath() + article.optString(Article.ARTICLE_PERMALINK); sendToBaidu(articlePermalink); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the article to Baidu failed", e); } } /** * Gets the event type {@linkplain EventTypes#ADD_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.ADD_ARTICLE; } }
if (Latkes.RuntimeMode.PRODUCTION != Latkes.getRuntimeMode() || StringUtils.isBlank(Symphonys.BAIDU_DATA_TOKEN)) { return; } if (ArrayUtils.isEmpty(urls)) { return; } Symphonys.EXECUTOR_SERVICE.submit(() -> { try { final String urlsStr = StringUtils.join(urls, "\n"); final HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/urls?site=" + Latkes.getServerHost() + "&token=" + Symphonys.BAIDU_DATA_TOKEN). header(Common.USER_AGENT, "curl/7.12.1"). header("Host", "data.zz.baidu.com"). header("Content-Type", "text/plain"). header("Connection", "close").body(urlsStr.getBytes(), MimeTypes.MIME_TEXT_PLAIN).timeout(30000).send(); response.charset("UTF-8"); LOGGER.info("Sent [" + urlsStr + "] to Baidu [response=" + response.bodyText() + "]"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Ping Baidu spider failed", e); } });
551
356
907
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/ArticleSearchAdder.java
ArticleSearchAdder
action
class ArticleSearchAdder extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ArticleSearchAdder.class); /** * Search management service. */ @Inject private SearchMgmtService searchMgmtService; @Override public void action(final Event<JSONObject> event) {<FILL_FUNCTION_BODY>} /** * Gets the event type {@linkplain EventTypes#ADD_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.ADD_ARTICLE; } }
final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); final JSONObject article = data.optJSONObject(Article.ARTICLE); if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) || Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE)) { return; } final String tags = article.optString(Article.ARTICLE_TAGS); if (StringUtils.containsIgnoreCase(tags, Tag.TAG_TITLE_C_SANDBOX)) { return; } if (Symphonys.ALGOLIA_ENABLED) { searchMgmtService.updateAlgoliaDocument(JSONs.clone(article)); } if (Symphonys.ES_ENABLED) { searchMgmtService.updateESDocument(JSONs.clone(article), Article.ARTICLE); }
182
290
472
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/ArticleSearchUpdater.java
ArticleSearchUpdater
action
class ArticleSearchUpdater extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ArticleSearchUpdater.class); /** * Search management service. */ @Inject private SearchMgmtService searchMgmtService; @Override public void action(final Event<JSONObject> event) {<FILL_FUNCTION_BODY>} /** * Gets the event type {@linkplain EventTypes#UPDATE_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.UPDATE_ARTICLE; } }
final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); final JSONObject article = data.optJSONObject(Article.ARTICLE); if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE) || Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE)) { return; } final String tags = article.optString(Article.ARTICLE_TAGS); if (StringUtils.containsIgnoreCase(tags, Tag.TAG_TITLE_C_SANDBOX)) { return; } if (Symphonys.ALGOLIA_ENABLED) { searchMgmtService.updateAlgoliaDocument(JSONs.clone(article)); } if (Symphonys.ES_ENABLED) { searchMgmtService.updateESDocument(JSONs.clone(article), Article.ARTICLE); }
184
290
474
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/ArticleUpdateAudioHandler.java
ArticleUpdateAudioHandler
action
class ArticleUpdateAudioHandler extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ArticleUpdateAudioHandler.class); /** * Article management service. */ @Inject private ArticleMgmtService articleMgmtService; /** * Gets the event type {@linkplain EventTypes#UPDATE_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.UPDATE_ARTICLE; } @Override public void action(final Event<JSONObject> event) {<FILL_FUNCTION_BODY>} }
final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); final JSONObject originalArticle = data.optJSONObject(Article.ARTICLE); articleMgmtService.genArticleAudio(originalArticle);
182
89
271
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/ArticleUpdateNotifier.java
ArticleUpdateNotifier
action
class ArticleUpdateNotifier extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ArticleUpdateNotifier.class); /** * Notification repository. */ @Inject private NotificationRepository notificationRepository; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Follow query service. */ @Inject private FollowQueryService followQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Role query service. */ @Inject private RoleQueryService roleQueryService; @Override public void action(final Event<JSONObject> event) {<FILL_FUNCTION_BODY>} /** * Gets the event type {@linkplain EventTypes#UPDATE_ARTICLE}. * * @return event type */ @Override public String getEventType() { return EventTypes.UPDATE_ARTICLE; } }
final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); try { final JSONObject articleUpdated = data.getJSONObject(Article.ARTICLE); final String articleId = articleUpdated.optString(Keys.OBJECT_ID); final String articleAuthorId = articleUpdated.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId); final String articleAuthorName = articleAuthor.optString(User.USER_NAME); final boolean isDiscussion = articleUpdated.optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION; final String articleContent = articleUpdated.optString(Article.ARTICLE_CONTENT); final Set<String> atUserNames = userQueryService.getUserNames(articleContent); atUserNames.remove(articleAuthorName); // Do not notify the author itself final Set<String> requisiteAtUserPermissions = new HashSet<>(); requisiteAtUserPermissions.add(Permission.PERMISSION_ID_C_COMMON_AT_USER); final boolean hasAtUserPerm = roleQueryService.userHasPermissions(articleAuthorId, requisiteAtUserPermissions); final Set<String> atedUserIds = new HashSet<>(); if (hasAtUserPerm) { // 'At' Notification for (final String userName : atUserNames) { final JSONObject user = userQueryService.getUserByName(userName); final JSONObject requestJSONObject = new JSONObject(); final String atedUserId = user.optString(Keys.OBJECT_ID); if (!notificationRepository.hasSentByDataIdAndType(atedUserId, articleId, Notification.DATA_TYPE_C_AT)) { requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atedUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addAtNotification(requestJSONObject); } atedUserIds.add(atedUserId); } } final JSONObject oldArticle = data.optJSONObject(Common.OLD_ARTICLE); if (!Article.isDifferent(oldArticle, articleUpdated)) { // 更新帖子通知改进 https://github.com/b3log/symphony/issues/872 LOGGER.log(Level.DEBUG, "The article [title=" + oldArticle.optString(Article.ARTICLE_TITLE) + "] has not changed, do not notify it's watchers"); return; } // 'following - article update' Notification final boolean articleNotifyFollowers = data.optBoolean(Article.ARTICLE_T_NOTIFY_FOLLOWERS); if (articleNotifyFollowers) { final JSONObject followerUsersResult = followQueryService.getArticleWatchers(UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL, articleId, 1, Integer.MAX_VALUE); final List<JSONObject> watcherUsers = (List<JSONObject>) followerUsersResult.opt(Keys.RESULTS); for (final JSONObject watcherUser : watcherUsers) { final String watcherName = watcherUser.optString(User.USER_NAME); if ((isDiscussion && !atUserNames.contains(watcherName)) || articleAuthorName.equals(watcherName)) { continue; } final JSONObject requestJSONObject = new JSONObject(); final String watcherUserId = watcherUser.optString(Keys.OBJECT_ID); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, watcherUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addFollowingArticleUpdateNotification(requestJSONObject); } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the article update notification failed", e); }
329
1,056
1,385
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/event/CommentUpdateNotifier.java
CommentUpdateNotifier
action
class CommentUpdateNotifier extends AbstractEventListener<JSONObject> { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(CommentUpdateNotifier.class); /** * Notification repository. */ @Inject private NotificationRepository notificationRepository; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Role query service. */ @Inject private RoleQueryService roleQueryService; @Override public void action(final Event<JSONObject> event) {<FILL_FUNCTION_BODY>} /** * Gets the event type {@linkplain EventTypes#UPDATE_COMMENT}. * * @return event type */ @Override public String getEventType() { return EventTypes.UPDATE_COMMENT; } }
final JSONObject data = event.getData(); LOGGER.log(Level.TRACE, "Processing an event [type={}, data={}]", event.getType(), data); try { final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE); final JSONObject originalComment = data.getJSONObject(Comment.COMMENT); final String commentId = originalComment.optString(Keys.OBJECT_ID); final String commenterId = originalComment.optString(Comment.COMMENT_AUTHOR_ID); final String commentContent = originalComment.optString(Comment.COMMENT_CONTENT); final JSONObject commenter = userQueryService.getUser(commenterId); final String commenterName = commenter.optString(User.USER_NAME); final Set<String> atUserNames = userQueryService.getUserNames(commentContent); atUserNames.remove(commenterName); final boolean isDiscussion = originalArticle.optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION; final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID); final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT); final Set<String> articleContentAtUserNames = userQueryService.getUserNames(articleContent); final Set<String> requisiteAtUserPermissions = new HashSet<>(); requisiteAtUserPermissions.add(Permission.PERMISSION_ID_C_COMMON_AT_USER); final boolean hasAtUserPerm = roleQueryService.userHasPermissions(commenterId, requisiteAtUserPermissions); final Set<String> atIds = new HashSet<>(); if (hasAtUserPerm) { // 'At' Notification for (final String userName : atUserNames) { if (isDiscussion && !articleContentAtUserNames.contains(userName)) { continue; } final JSONObject atUser = userQueryService.getUserByName(userName); if (atUser.optString(Keys.OBJECT_ID).equals(articleAuthorId)) { continue; // Has notified in step 2 } final String atUserId = atUser.optString(Keys.OBJECT_ID); if (!notificationRepository.hasSentByDataIdAndType(atUserId, commentId, Notification.DATA_TYPE_C_AT)) { final JSONObject requestJSONObject = new JSONObject(); requestJSONObject.put(Notification.NOTIFICATION_USER_ID, atUserId); requestJSONObject.put(Notification.NOTIFICATION_DATA_ID, commentId); notificationMgmtService.addAtNotification(requestJSONObject); } atIds.add(atUserId); } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends the comment update notification failed", e); }
269
749
1,018
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/model/Character.java
Character
createImage
class Character { /** * Character. */ public static final String CHARACTER = "character"; /** * Characters. */ public static final String CHARACTERS = "characters"; /** * Key of character user id. */ public static final String CHARACTER_USER_ID = "characterUserId"; /** * Key of character image. */ public static final String CHARACTER_IMG = "characterImg"; /** * Key of character content. */ public static final String CHARACTER_CONTENT = "characterContent"; /** * Character font. */ private static final Font FONT = new Font("宋体", Font.PLAIN, 40); /** * Gets a character by the specified character content in the specified characters. * * @param content the specified character content * @param characters the specified characters * @return character, returns {@code null} if not found */ public static JSONObject getCharacter(final String content, final Set<JSONObject> characters) { for (final JSONObject character : characters) { if (character.optString(CHARACTER_CONTENT).equals(content)) { return character; } } return null; } /** * Creates an image with the specified content (a character). * * @param content the specified content * @return image */ public static BufferedImage createImage(final String content) {<FILL_FUNCTION_BODY>} }
final BufferedImage ret = new BufferedImage(500, 500, Transparency.TRANSLUCENT); final Graphics g = ret.getGraphics(); g.setClip(0, 0, 50, 50); g.fillRect(0, 0, 50, 50); g.setFont(new Font(null, Font.PLAIN, 40)); g.setColor(Color.BLACK); g.drawString(content, 5, 40); g.dispose(); return ret;
399
149
548
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/model/Liveness.java
Liveness
calcPoint
class Liveness { /** * Liveness. */ public static final String LIVENESS = "liveness"; /** * Key of user id. */ public static final String LIVENESS_USER_ID = "livenessUserId"; /** * Key of liveness date. */ public static final String LIVENESS_DATE = "livenessDate"; /** * Key of liveness point. */ public static final String LIVENESS_POINT = "livenessPoint"; /** * Key of liveness article. */ public static final String LIVENESS_ARTICLE = "livenessArticle"; /** * Key of liveness comment. */ public static final String LIVENESS_COMMENT = "livenessComment"; /** * Key of liveness activity. */ public static final String LIVENESS_ACTIVITY = "livenessActivity"; /** * Key of liveness thank. */ public static final String LIVENESS_THANK = "livenessThank"; /** * Key of liveness vote. */ public static final String LIVENESS_VOTE = "livenessVote"; /** * Key of liveness reward. */ public static final String LIVENESS_REWARD = "livenessReward"; /** * Key of liveness PV. */ public static final String LIVENESS_PV = "livenessPV"; /** * Key of liveness accept answer. */ public static final String LIVENESS_ACCEPT_ANSWER = "livenessAcceptAnswer"; /** * Calculates point of the specified liveness. * * @param liveness the specified liveness * @return point */ public static int calcPoint(final JSONObject liveness) {<FILL_FUNCTION_BODY>} /** * Private constructor. */ private Liveness() { } }
final float activityPer = Symphonys.ACTIVITY_YESTERDAY_REWARD_ACTIVITY_PER; final float articlePer = Symphonys.ACTIVITY_YESTERDAY_REWARD_ARTICLE_PER; final float commentPer = Symphonys.ACTIVITY_YESTERDAY_REWARD_COMMENT_PER; final float pvPer = Symphonys.ACTIVITY_YESTERDAY_REWARD_PV_PER; final float rewardPer = Symphonys.ACTIVITY_YESTERDAY_REWARD_REWARD_PER; final float thankPer = Symphonys.ACTIVITY_YESTERDAY_REWARD_THANK_PER; final float votePer = Symphonys.ACTIVITY_YESTERDAY_REWARD_VOTE_PER; final float acceptAnswerPer = Symphonys.ACTIVITY_YESTERDAY_REWARD_ACCEPT_ANSWER_PER; final int activity = liveness.optInt(Liveness.LIVENESS_ACTIVITY); final int article = liveness.optInt(Liveness.LIVENESS_ARTICLE); final int comment = liveness.optInt(Liveness.LIVENESS_COMMENT); int pv = liveness.optInt(Liveness.LIVENESS_PV); if (pv > 50) { pv = 50; } final int reward = liveness.optInt(Liveness.LIVENESS_REWARD); final int thank = liveness.optInt(Liveness.LIVENESS_THANK); int vote = liveness.optInt(Liveness.LIVENESS_VOTE); if (vote > 10) { vote = 10; } final int acceptAnswer = liveness.optInt(Liveness.LIVENESS_ACCEPT_ANSWER); final int activityPoint = (int) (activity * activityPer); final int articlePoint = (int) (article * articlePer); final int commentPoint = (int) (comment * commentPer); final int pvPoint = (int) (pv * pvPer); final int rewardPoint = (int) (reward * rewardPer); final int thankPoint = (int) (thank * thankPer); final int votePoint = (int) (vote * votePer); final int acceptAnswerPoint = (int) (acceptAnswer * acceptAnswerPer); int ret = activityPoint + articlePoint + commentPoint + pvPoint + rewardPoint + thankPoint + votePoint + acceptAnswerPoint; final int max = Symphonys.ACTIVITY_YESTERDAY_REWARD_MAX; if (ret > max) { ret = max; } return ret;
538
735
1,273
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/model/feed/RSSChannel.java
RSSChannel
toString
class RSSChannel { /** * Start. */ private static final String START = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"2.0\" " + "xmlns:atom=\"http://www.w3.org/2005/Atom\"><channel>"; /** * End. */ private static final String END = "</channel></rss>"; /** * Start title element. */ private static final String START_TITLE_ELEMENT = "<title>"; /** * End title element. */ private static final String END_TITLE_ELEMENT = "</title>"; /** * Start link element. */ private static final String START_LINK_ELEMENT = "<link>"; /** * Atom link variable. */ private static final String ATOM_LINK_VARIABLE = "${atomLink}"; /** * End link element. */ private static final String END_LINK_ELEMENT = "</link>"; /** * Atom link element. */ private static final String ATOM_LINK_ELEMENT = "<atom:link href=\"" + ATOM_LINK_VARIABLE + "\" rel=\"self\" type=\"application/rss+xml\" />"; /** * Start description element. */ private static final String START_DESCRIPTION_ELEMENT = "<description>"; /** * End description element. */ private static final String END_DESCRIPTION_ELEMENT = "</description>"; /** * Start generator element. */ private static final String START_GENERATOR_ELEMENT = "<generator>"; /** * End generator element. */ private static final String END_GENERATOR_ELEMENT = "</generator>"; /** * Start language element. */ private static final String START_LANGUAGE_ELEMENT = "<language>"; /** * End language element. */ private static final String END_LANGUAGE_ELEMENT = "</language>"; /** * Start last build date element. */ private static final String START_LAST_BUILD_DATE_ELEMENT = "<lastBuildDate>"; /** * End last build date element. */ private static final String END_LAST_BUILD_DATE_ELEMENT = "</lastBuildDate>"; /** * Title. */ private String title; /** * Link. */ private String link; /** * Atom link. */ private String atomLink; /** * Description. */ private String description; /** * Generator. */ private String generator; /** * Last build date. */ private Date lastBuildDate; /** * Language. */ private String language; /** * Items. */ private final List<RSSItem> items = new ArrayList<>(); /** * Gets the atom link. * * @return atom link */ public String getAtomLink() { return atomLink; } /** * Sets the atom link with the specified atom link. * * @param atomLink the specified atom link */ public void setAtomLink(final String atomLink) { this.atomLink = atomLink; } /** * Gets the last build date. * * @return last build date */ public Date getLastBuildDate() { return lastBuildDate; } /** * Sets the last build date with the specified last build date. * * @param lastBuildDate the specified last build date */ public void setLastBuildDate(final Date lastBuildDate) { this.lastBuildDate = lastBuildDate; } /** * Gets generator. * * @return generator */ public String getGenerator() { return generator; } /** * Sets the generator with the specified generator. * * @param generator the specified generator */ public void setGenerator(final String generator) { this.generator = generator; } /** * Gets the link. * * @return link */ public String getLink() { return link; } /** * Sets the link with the specified link. * * @param link the specified link */ public void setLink(final String link) { this.link = link; } /** * Gets the title. * * @return title */ public String getTitle() { return title; } /** * Sets the title with the specified title. * * @param title the specified title */ public void setTitle(final String title) { this.title = title; } /** * Adds the specified item. * * @param item the specified item */ public void addItem(final RSSItem item) { items.add(item); } /** * Gets the description. * * @return description */ public String getDescription() { return description; } /** * Sets the description with the specified description. * * @param description the specified description */ public void setDescription(final String description) { this.description = description; } /** * Gets the language. * * @return language */ public String getLanguage() { return language; } /** * Sets the language with the specified language. * * @param language the specified language */ public void setLanguage(final String language) { this.language = language; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(START); stringBuilder.append(START_TITLE_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(title)); stringBuilder.append(END_TITLE_ELEMENT); stringBuilder.append(START_LINK_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(link)); stringBuilder.append(END_LINK_ELEMENT); stringBuilder.append(ATOM_LINK_ELEMENT.replace(ATOM_LINK_VARIABLE, atomLink)); stringBuilder.append(START_DESCRIPTION_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(description)); stringBuilder.append(END_DESCRIPTION_ELEMENT); stringBuilder.append(START_GENERATOR_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(generator)); stringBuilder.append(END_GENERATOR_ELEMENT); stringBuilder.append(START_LAST_BUILD_DATE_ELEMENT); stringBuilder.append(DateFormatUtils.SMTP_DATETIME_FORMAT.format(lastBuildDate)); stringBuilder.append(END_LAST_BUILD_DATE_ELEMENT); stringBuilder.append(START_LANGUAGE_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(language)); stringBuilder.append(END_LANGUAGE_ELEMENT); for (final RSSItem item : items) { stringBuilder.append(item.toString()); } stringBuilder.append(END); return XMLs.format(stringBuilder.toString());
1,581
427
2,008
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/model/feed/RSSItem.java
RSSItem
toString
class RSSItem { /** * Start title element. */ private static final String START_TITLE_ELEMENT = "<title>"; /** * End title element. */ private static final String END_TITLE_ELEMENT = "</title>"; /** * Start link element. */ private static final String START_LINK_ELEMENT = "<link>"; /** * End link element. */ private static final String END_LINK_ELEMENT = "</link>"; /** * Start description element. */ private static final String START_DESCRIPTION_ELEMENT = "<description>"; /** * End summary element. */ private static final String END_DESCRIPTION_ELEMENT = "</description>"; /** * Start author element. */ private static final String START_AUTHOR_ELEMENT = "<author>"; /** * End author element. */ private static final String END_AUTHOR_ELEMENT = "</author>"; /** * Categories. */ private final Set<RSSCategory> categories = new HashSet<>(); /** * Start guid element. */ private static final String START_GUID_ELEMENT = "<guid>"; /** * End guid element. */ private static final String END_GUID_ELEMENT = "</guid>"; /** * Start pubDate element. */ private static final String START_PUB_DATE_ELEMENT = "<pubDate>"; /** * End pubDate element. */ private static final String END_PUB_DATE_ELEMENT = "</pubDate>"; /** * Guid. */ private String guid; /** * Publish date. */ private Date pubDate; /** * Title. */ private String title; /** * Description. */ private String description; /** * Link. */ private String link; /** * Author. */ private String author; /** * Gets the GUID. * * @return GUID */ public String getGUID() { return guid; } /** * Sets the GUID with the specified GUID. * * @param guid the specified GUID */ public void setGUID(final String guid) { this.guid = guid; } /** * Gets the author. * * @return author */ public String getAuthor() { return author; } /** * Sets the author with the specified author. * * @param author the specified author */ public void setAuthor(final String author) { this.author = author; } /** * Gets the link. * * @return link */ public String getLink() { return link; } /** * Sets the link with the specified link. * * @param link the specified link */ public void setLink(final String link) { this.link = link; } /** * Gets the title. * * @return title */ public String getTitle() { return title; } /** * Sets the title with the specified title. * * @param title the specified title */ public void setTitle(final String title) { this.title = title; } /** * Gets publish date. * * @return publish date */ public Date getPubDate() { return pubDate; } /** * Sets the publish date with the specified publish date. * * @param pubDate the specified publish date */ public void setPubDate(final Date pubDate) { this.pubDate = pubDate; } /** * Gets the description. * * @return description */ public String getDescription() { return description; } /** * Sets the description with the specified description. * * @param description the specified description */ public void setDescription(final String description) { this.description = description; } /** * Adds the specified category. * * @param category the specified category */ public void addCatetory(final RSSCategory category) { categories.add(category); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<item>").append(START_TITLE_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(title)); stringBuilder.append(END_TITLE_ELEMENT); stringBuilder.append(START_LINK_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(link)); stringBuilder.append(END_LINK_ELEMENT); stringBuilder.append(START_DESCRIPTION_ELEMENT); stringBuilder.append("<![CDATA[" + description + "]]>"); stringBuilder.append(END_DESCRIPTION_ELEMENT); stringBuilder.append(START_AUTHOR_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(author)); stringBuilder.append(END_AUTHOR_ELEMENT); stringBuilder.append(START_GUID_ELEMENT); stringBuilder.append(StringEscapeUtils.escapeXml(guid)); stringBuilder.append(END_GUID_ELEMENT); for (final RSSCategory category : categories) { stringBuilder.append(category.toString()); } stringBuilder.append(START_PUB_DATE_ELEMENT); stringBuilder.append(DateFormatUtils.format(pubDate, "EEE, dd MMM yyyy HH:mm:ss Z", Locale.US)); stringBuilder.append(END_PUB_DATE_ELEMENT).append("</item>"); return stringBuilder.toString();
1,219
388
1,607
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/model/sitemap/Sitemap.java
URL
toString
class URL { /** * Start URL element. */ private static final String START_URL_ELEMENT = "<url>"; /** * End URL element. */ private static final String END_URL_ELEMENT = "</url>"; /** * Start location element. */ private static final String START_LOC_ELEMENT = "<loc>"; /** * End location element. */ private static final String END_LOC_ELEMENT = "</loc>"; /** * Start last modified element. */ private static final String START_LAST_MOD_ELEMENT = "<lastmod>"; /** * End last modified element. */ private static final String END_LAST_MOD_ELEMENT = "</lastmod>"; /** * Start change frequency element. */ private static final String START_CHANGE_REQ_ELEMENT = "<changefreq>"; /** * End change frequency element. */ private static final String END_CHANGE_REQ_ELEMENT = "</changefreq>"; /** * Start priority element. */ private static final String START_PRIORITY_ELEMENT = "<priority>"; /** * End priority element. */ private static final String END_PRIORITY_ELEMENT = "</priority>"; /** * Location. */ private String loc; /** * Last modified. */ private String lastMod; /** * Change frequency. */ private String changeFreq; /** * Priority. */ private String priority; /** * Gets the last modified. * * @return last modified */ public String getLastMod() { return lastMod; } /** * Sets the last modified with the specified last modified. * * @param lastMod the specified modified */ public void setLastMod(final String lastMod) { this.lastMod = lastMod; } /** * Gets the location. * * @return location */ public String getLoc() { return loc; } /** * Sets the location with the specified location. * * @param loc the specified location */ public void setLoc(final String loc) { this.loc = loc; } /** * Gets the change frequency. * * @return change frequency */ public String getChangeFreq() { return changeFreq; } /** * Sets the change frequency with the specified change frequency. * * @param changeFreq the specified change frequency */ public void setChangeFreq(final String changeFreq) { this.changeFreq = changeFreq; } /** * Gets the priority. * * @return priority */ public String getPriority() { return priority; } /** * Sets the priority with the specified priority. * * @param priority the specified priority */ public void setPriority(final String priority) { this.priority = priority; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(START_URL_ELEMENT); stringBuilder.append(START_LOC_ELEMENT); stringBuilder.append(loc); stringBuilder.append(END_LOC_ELEMENT); if (StringUtils.isNotBlank(lastMod)) { stringBuilder.append(START_LAST_MOD_ELEMENT); stringBuilder.append(lastMod); stringBuilder.append(END_LAST_MOD_ELEMENT); } if (StringUtils.isNotBlank(changeFreq)) { stringBuilder.append(START_CHANGE_REQ_ELEMENT); stringBuilder.append(changeFreq); stringBuilder.append(END_CHANGE_REQ_ELEMENT); } if (StringUtils.isNotBlank(priority)) { stringBuilder.append(START_PRIORITY_ELEMENT); stringBuilder.append(priority); stringBuilder.append(END_PRIORITY_ELEMENT); } stringBuilder.append(END_URL_ELEMENT); return stringBuilder.toString();
866
288
1,154
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/AfterRequestHandler.java
AfterRequestHandler
handle
class AfterRequestHandler implements Handler { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(AfterRequestHandler.class); @Override public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
Locales.setLocale(null); Sessions.clearThreadLocalData(); JdbcRepository.dispose(); Stopwatchs.end(); final Request request = context.getRequest(); final long elapsed = Stopwatchs.getElapsed("Request initialized [" + request.getRequestURI() + "]"); final Map<String, Object> dataModel = context.getDataModel(); if (null != dataModel) { dataModel.put(Common.ELAPSED, elapsed); } final int threshold = Symphonys.PERFORMANCE_THRESHOLD; if (0 < threshold) { if (elapsed >= threshold) { LOGGER.log(Level.INFO, "Stopwatch: {}{}", Strings.LINE_SEPARATOR, Stopwatchs.getTimingStat()); } } Stopwatchs.release();
77
219
296
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/BeforeRequestHandler.java
BeforeRequestHandler
fillBotAttrs
class BeforeRequestHandler implements Handler { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(BeforeRequestHandler.class); @Override public void handle(final RequestContext context) { Stopwatchs.start("Request initialized [" + context.requestURI() + "]"); Locales.setLocale(Latkes.getLocale()); Sessions.setTemplateDir(Symphonys.SKIN_DIR_NAME); Sessions.setMobile(false); Sessions.setAvatarViewMode(UserExt.USER_AVATAR_VIEW_MODE_C_ORIGINAL); fillBotAttrs(context); resolveSkinDir(context); } /** * Resolve skin (template) for the specified HTTP request. * * @param context the specified HTTP request context */ private void resolveSkinDir(final RequestContext context) { if (Sessions.isBot() || context.getRequest().isStaticResource()) { return; } Stopwatchs.start("Resolve skin"); final String templateDirName = Sessions.isMobile() ? "mobile" : "classic"; Sessions.setTemplateDir(templateDirName); final Request request = context.getRequest(); final Session httpSession = request.getSession(); httpSession.setAttribute(Keys.TEMPLATE_DIR_NAME, templateDirName); try { final BeanManager beanManager = BeanManager.getInstance(); final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class); final OptionRepository optionRepository = beanManager.getReference(OptionRepository.class); final JSONObject optionLang = optionRepository.get(Option.ID_C_MISC_LANGUAGE); final String optionLangValue = optionLang.optString(Option.OPTION_VALUE); if ("0".equals(optionLangValue)) { Locales.setLocale(Locales.getLocale(request)); } else { Locales.setLocale(Locales.getLocale(optionLangValue)); } JSONObject user = userQueryService.getCurrentUser(request); if (null == user) { return; } final String skin = Sessions.isMobile() ? user.optString(UserExt.USER_MOBILE_SKIN) : user.optString(UserExt.USER_SKIN); httpSession.setAttribute(Keys.TEMPLATE_DIR_NAME, skin); Sessions.setTemplateDir(skin); Sessions.setAvatarViewMode(user.optInt(UserExt.USER_AVATAR_VIEW_MODE)); Sessions.setUser(user); Sessions.setLoggedIn(true); final Locale locale = Locales.getLocale(user.optString(UserExt.USER_LANGUAGE)); Locales.setLocale(locale); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Resolves skin failed", e); } finally { Stopwatchs.end(); } } private static void fillBotAttrs(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final String userAgentStr = context.header(Common.USER_AGENT); final UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr); BrowserType browserType = userAgent.getBrowser().getBrowserType(); if (StringUtils.containsIgnoreCase(userAgentStr, "mobile") || StringUtils.containsIgnoreCase(userAgentStr, "MQQBrowser") || StringUtils.containsIgnoreCase(userAgentStr, "iphone") || StringUtils.containsIgnoreCase(userAgentStr, "MicroMessenger") || StringUtils.containsIgnoreCase(userAgentStr, "CFNetwork") || StringUtils.containsIgnoreCase(userAgentStr, "Android")) { browserType = BrowserType.MOBILE_BROWSER; } else if (StringUtils.containsIgnoreCase(userAgentStr, "Iframely") || StringUtils.containsIgnoreCase(userAgentStr, "Google") || StringUtils.containsIgnoreCase(userAgentStr, "BUbiNG") || StringUtils.containsIgnoreCase(userAgentStr, "ltx71")) { browserType = BrowserType.ROBOT; } else if (BrowserType.UNKNOWN == browserType) { if (!StringUtils.containsIgnoreCase(userAgentStr, "Java") && !StringUtils.containsIgnoreCase(userAgentStr, "MetaURI") && !StringUtils.containsIgnoreCase(userAgentStr, "Feed") && !StringUtils.containsIgnoreCase(userAgentStr, "okhttp") && !StringUtils.containsIgnoreCase(userAgentStr, "Sym")) { LOGGER.log(Level.WARN, "Unknown client [UA=" + userAgentStr + ", remoteAddr=" + Requests.getRemoteAddr(context.getRequest()) + ", URI=" + context.requestURI() + "]"); } } if (BrowserType.ROBOT == browserType) { LOGGER.log(Level.DEBUG, "Request made from a search engine [User-Agent={}]", context.header(Common.USER_AGENT)); Sessions.setBot(true); return; } Sessions.setBot(false); Sessions.setMobile(BrowserType.MOBILE_BROWSER == browserType);
820
562
1,382
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/CaptchaProcessor.java
CaptchaProcessor
getLoginCaptcha
class CaptchaProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(CaptchaProcessor.class); /** * Key of captcha. */ public static final String CAPTCHA = "captcha"; /** * Captchas. */ public static final Set<String> CAPTCHAS = new HashSet<>(); /** * Captcha length. */ private static final int CAPTCHA_LENGTH = 4; /** * Captcha chars. */ private static final String CHARS = "acdefhijklmnprstuvwxy234578"; /** * Register request handlers. */ public static void register() { final BeanManager beanManager = BeanManager.getInstance(); final CaptchaProcessor captchaProcessor = beanManager.getReference(CaptchaProcessor.class); Dispatcher.get("/captcha", captchaProcessor::get); Dispatcher.get("/captcha/login", captchaProcessor::getLoginCaptcha); } /** * Checks whether the specified captcha is invalid. * * @param captcha the specified captcha * @return {@code true} if it is invalid, returns {@code false} otherwise */ public static boolean invalidCaptcha(final String captcha) { if (StringUtils.isBlank(captcha) || captcha.length() != CAPTCHA_LENGTH) { return true; } boolean ret = !CaptchaProcessor.CAPTCHAS.contains(captcha); if (!ret) { CaptchaProcessor.CAPTCHAS.remove(captcha); } return ret; } /** * Gets captcha. * * @param context the specified context */ public void get(final RequestContext context) { final PngRenderer renderer = new PngRenderer(); context.setRenderer(renderer); try { final ConfigurableCaptchaService cs = new ConfigurableCaptchaService(); if (0.5 < Math.random()) { cs.setColorFactory(new GradientColorFactory()); } else { cs.setColorFactory(new RandomColorFactory()); } cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory())); final RandomWordFactory randomWordFactory = new RandomWordFactory(); randomWordFactory.setCharacters(CHARS); randomWordFactory.setMinLength(CAPTCHA_LENGTH); randomWordFactory.setMaxLength(CAPTCHA_LENGTH); cs.setWordFactory(randomWordFactory); cs.setFontFactory(new RandomFontFactory(getAvaialbeFonts())); final Captcha captcha = cs.getCaptcha(); final String challenge = captcha.getChallenge(); final BufferedImage bufferedImage = captcha.getImage(); if (CAPTCHAS.size() > 64) { CAPTCHAS.clear(); } CAPTCHAS.add(challenge); final Response response = context.getResponse(); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); renderImg(renderer, bufferedImage); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } } /** * Gets captcha for login. * * @param context the specified context */ public void getLoginCaptcha(final RequestContext context) {<FILL_FUNCTION_BODY>} private void renderImg(final PngRenderer renderer, final BufferedImage bufferedImage) throws IOException { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(bufferedImage, "png", baos); final byte[] data = baos.toByteArray(); renderer.setData(data); } } private static List<String> getAvaialbeFonts() { final List<String> ret = new ArrayList<>(); final GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); final Font[] fonts = e.getAllFonts(); for (final Font f : fonts) { if (Strings.contains(f.getFontName(), new String[]{"Verdana", "DejaVu Sans Mono", "Tahoma"})) { ret.add(f.getFontName()); } } final String defaultFontName = new JLabel().getFont().getFontName(); ret.add(defaultFontName); return ret; } }
try { final Response response = context.getResponse(); final String userId = context.param(Common.NEED_CAPTCHA); if (StringUtils.isBlank(userId)) { return; } final JSONObject wrong = LoginProcessor.WRONG_PWD_TRIES.get(userId); if (null == wrong) { return; } if (wrong.optInt(Common.WRON_COUNT) < 3) { return; } final PngRenderer renderer = new PngRenderer(); context.setRenderer(renderer); final ConfigurableCaptchaService cs = new ConfigurableCaptchaService(); if (0.5 < Math.random()) { cs.setColorFactory(new GradientColorFactory()); } else { cs.setColorFactory(new RandomColorFactory()); } cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory())); final RandomWordFactory randomWordFactory = new RandomWordFactory(); randomWordFactory.setCharacters(CHARS); randomWordFactory.setMinLength(CAPTCHA_LENGTH); randomWordFactory.setMaxLength(CAPTCHA_LENGTH); cs.setWordFactory(randomWordFactory); final Captcha captcha = cs.getCaptcha(); final String challenge = captcha.getChallenge(); final BufferedImage bufferedImage = captcha.getImage(); wrong.put(CAPTCHA, challenge); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); renderImg(renderer, bufferedImage); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); }
1,225
479
1,704
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/ChatroomProcessor.java
ChatroomProcessor
addChatRoomMsg
class ChatroomProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ChatroomProcessor.class); /** * Chat messages. */ public static LinkedList<JSONObject> messages = new LinkedList<>(); /** * Data model service. */ @Inject private DataModelService dataModelService; /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * Short link query service. */ @Inject private ShortLinkQueryService shortLinkQueryService; /** * Notification query service. */ @Inject private NotificationQueryService notificationQueryService; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Comment management service. */ @Inject private CommentMgmtService commentMgmtService; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Register request handlers. */ public static void register() { final BeanManager beanManager = BeanManager.getInstance(); final LoginCheckMidware loginCheck = beanManager.getReference(LoginCheckMidware.class); final AnonymousViewCheckMidware anonymousViewCheckMidware = beanManager.getReference(AnonymousViewCheckMidware.class); final ChatMsgAddValidationMidware chatMsgAddValidationMidware = beanManager.getReference(ChatMsgAddValidationMidware.class); final ChatroomProcessor chatroomProcessor = beanManager.getReference(ChatroomProcessor.class); Dispatcher.post("/chat-room/send", chatroomProcessor::addChatRoomMsg, loginCheck::handle, chatMsgAddValidationMidware::handle); Dispatcher.get("/cr", chatroomProcessor::showChatRoom, anonymousViewCheckMidware::handle); } /** * Adds a chat message. * <p> * The request json object (a chat message): * <pre> * { * "content": "" * } * </pre> * </p> * * @param context the specified context */ public synchronized void addChatRoomMsg(final RequestContext context) {<FILL_FUNCTION_BODY>} /** * Shows chatroom. * * @param context the specified context */ public void showChatRoom(final RequestContext context) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "chat-room.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> msgs = messages.stream(). map(msg -> JSONs.clone(msg).put(Common.TIME, Times.getTimeAgo(msg.optLong(Common.TIME), Locales.getLocale()))).collect(Collectors.toList()); dataModel.put(Common.MESSAGES, msgs); dataModel.put("chatRoomMsgCnt", Symphonys.CHATROOMMSGS_CNT); dataModel.put(Common.ONLINE_CHAT_CNT, SESSIONS.size()); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } }
final JSONObject requestJSONObject = (JSONObject) context.attr(Keys.REQUEST); String content = requestJSONObject.optString(Common.CONTENT); content = shortLinkQueryService.linkArticle(content); content = Emotions.convert(content); content = Markdowns.toHTML(content); content = Markdowns.clean(content, ""); final JSONObject currentUser = Sessions.getUser(); final String userName = currentUser.optString(User.USER_NAME); final JSONObject msg = new JSONObject(); msg.put(User.USER_NAME, userName); msg.put(UserExt.USER_AVATAR_URL, currentUser.optString(UserExt.USER_AVATAR_URL)); msg.put(Common.CONTENT, content); msg.put(Common.TIME, System.currentTimeMillis()); messages.addFirst(msg); final int maxCnt = Symphonys.CHATROOMMSGS_CNT; if (messages.size() > maxCnt) { messages.remove(maxCnt); } final JSONObject pushMsg = JSONs.clone(msg); pushMsg.put(Common.TIME, Times.getTimeAgo(msg.optLong(Common.TIME), Locales.getLocale())); ChatroomChannel.notifyChat(pushMsg); context.renderJSON(StatusCodes.SUCC); try { final String userId = currentUser.optString(Keys.OBJECT_ID); final JSONObject user = userQueryService.getUser(userId); user.put(UserExt.USER_LATEST_CMT_TIME, System.currentTimeMillis()); userMgmtService.updateUser(userId, user); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Update user latest comment time failed", e); }
989
477
1,466
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/DomainProcessor.java
DomainProcessor
showDomains
class DomainProcessor { /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Domain query service. */ @Inject private DomainQueryService domainQueryService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Shows domain articles. * * @param context the specified context */ public void showDomainArticles(final RequestContext context) { final String domainURI = context.pathVar("domainURI"); final Request request = context.getRequest(); final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "domain-articles.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final int pageNum = Paginator.getPage(request); int pageSize = Symphonys.ARTICLE_LIST_CNT; final JSONObject user = Sessions.getUser(); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); if (!UserExt.finishedGuide(user)) { context.sendRedirect(Latkes.getServePath() + "/guide"); return; } } final JSONObject domain = domainQueryService.getByURI(domainURI); if (null == domain) { context.sendError(404); return; } final List<JSONObject> tags = domainQueryService.getTags(domain.optString(Keys.OBJECT_ID)); domain.put(Domain.DOMAIN_T_TAGS, (Object) tags); dataModel.put(Domain.DOMAIN, domain); dataModel.put(Common.SELECTED, domain.optString(Domain.DOMAIN_URI)); final String domainId = domain.optString(Keys.OBJECT_ID); final JSONObject result = articleQueryService.getDomainArticles(domainId, pageNum, pageSize); final List<JSONObject> latestArticles = (List<JSONObject>) result.opt(Article.ARTICLES); dataModel.put(Common.LATEST_ARTICLES, latestArticles); final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION); final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT); final List<Integer> pageNums = (List<Integer>) pagination.opt(Pagination.PAGINATION_PAGE_NUMS); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows domains. * * @param context the specified context */ public void showDomains(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "domains.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final JSONObject statistic = optionQueryService.getStatistic(); final int tagCnt = statistic.optInt(Option.ID_C_STATISTIC_TAG_COUNT); dataModel.put(Tag.TAG_T_COUNT, tagCnt); final int domainCnt = statistic.optInt(Option.ID_C_STATISTIC_DOMAIN_COUNT); dataModel.put(Domain.DOMAIN_T_COUNT, domainCnt); final List<JSONObject> domains = domainQueryService.getAllDomains(); dataModel.put(Common.ALL_DOMAINS, domains); dataModelService.fillHeaderAndFooter(context, dataModel);
1,016
215
1,231
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/ErrorProcessor.java
ErrorProcessor
handle
class ErrorProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ErrorProcessor.class); /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Role query service. */ @Inject private RoleQueryService roleQueryService; /** * Handles the error. * * @param context the specified context */ public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final String statusCode = context.pathVar("statusCode"); if (StringUtils.equals("GET", context.method())) { final String requestURI = context.requestURI(); final String templateName = statusCode + ".ftl"; LOGGER.log(Level.TRACE, "Shows error page[requestURI={}, templateName={}]", requestURI, templateName); final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "error/" + templateName); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.putAll(langPropsService.getAll(Locales.getLocale())); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideTags(dataModel); final JSONObject user = Sessions.getUser(); final String roleId = null != user ? user.optString(User.USER_ROLE) : Role.ROLE_ID_C_VISITOR; final Map<String, JSONObject> permissionsGrant = roleQueryService.getPermissionsGrantMap(roleId); dataModel.put(Permission.PERMISSIONS, permissionsGrant); dataModel.put(Common.ELAPSED, 0); final Map<String, Object> contextDataModel = (Map<String, Object>) context.attr("dataModel"); if (null != contextDataModel) { dataModel.putAll(contextDataModel); } } else { context.renderJSON(StatusCodes.ERR).renderMsg(statusCode); }
180
420
600
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/FeedProcessor.java
FeedProcessor
genDomainRSS
class FeedProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(FeedProcessor.class); /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Domain query service. */ @Inject private DomainQueryService domainQueryService; /** * Short link query service. */ @Inject private ShortLinkQueryService shortLinkQueryService; /** * Generates recent articles' RSS. * * @param context the specified context */ public void genRecentRSS(final RequestContext context) { final RssRenderer renderer = new RssRenderer(); context.setRenderer(renderer); try { final RSSChannel channel = new RSSChannel(); final JSONObject result = articleQueryService.getRecentArticles(0, 1, Symphonys.ARTICLE_LIST_CNT); final List<JSONObject> articles = (List<JSONObject>) result.get(Article.ARTICLES); for (int i = 0; i < articles.size(); i++) { RSSItem item = getItem(articles, i); channel.addItem(item); } channel.setTitle(langPropsService.get("symphonyLabel")); channel.setLastBuildDate(new Date()); channel.setLink(Latkes.getServePath()); channel.setAtomLink(Latkes.getServePath() + "/rss/recent.xml"); channel.setGenerator("Symphony v" + Server.VERSION + ", https://b3log.org/sym"); final String localeString = optionQueryService.getOption("miscLanguage").optString(Option.OPTION_VALUE); final String country = Locales.getCountry(localeString).toLowerCase(); final String language = Locales.getLanguage(localeString).toLowerCase(); channel.setLanguage(language + '-' + country); channel.setDescription(langPropsService.get("symDescriptionLabel")); renderer.setContent(channel.toString()); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Generates recent articles' RSS failed", e); context.getResponse().sendError(500); } } /** * Generates domain articles' RSS. * * @param context the specified context */ public void genDomainRSS(final RequestContext context) {<FILL_FUNCTION_BODY>} private RSSItem getItem(final List<JSONObject> articles, int i) throws org.json.JSONException { final JSONObject article = articles.get(i); final RSSItem ret = new RSSItem(); String title = article.getString(Article.ARTICLE_TITLE); title = Emotions.toAliases(title); ret.setTitle(title); String description = article.getString(Article.ARTICLE_CONTENT); description = shortLinkQueryService.linkArticle(description); description = Emotions.toAliases(description); description = Emotions.convert(description); description = Markdowns.toHTML(description); ret.setDescription(description); final Date pubDate = (Date) article.get(Article.ARTICLE_UPDATE_TIME); ret.setPubDate(pubDate); final String link = Latkes.getServePath() + article.getString(Article.ARTICLE_PERMALINK); ret.setLink(link); ret.setGUID(link); ret.setAuthor(article.optString(Article.ARTICLE_T_AUTHOR_NAME)); final String tagsString = article.getString(Article.ARTICLE_TAGS); final String[] tagStrings = tagsString.split(","); for (final String tagString : tagStrings) { final RSSCategory catetory = new RSSCategory(); ret.addCatetory(catetory); catetory.setTerm(tagString); } return ret; } }
final String domainURI = context.pathVar("domainURI"); final RssRenderer renderer = new RssRenderer(); context.setRenderer(renderer); try { final JSONObject domain = domainQueryService.getByURI(domainURI); if (null == domain) { context.getResponse().sendError(404); return; } final RSSChannel channel = new RSSChannel(); final String domainId = domain.optString(Keys.OBJECT_ID); final JSONObject result = articleQueryService.getDomainArticles(domainId, 1, Symphonys.ARTICLE_LIST_CNT); final List<JSONObject> articles = (List<JSONObject>) result.get(Article.ARTICLES); for (int i = 0; i < articles.size(); i++) { RSSItem item = getItem(articles, i); channel.addItem(item); } channel.setTitle(langPropsService.get("symphonyLabel")); channel.setLastBuildDate(new Date()); channel.setLink(Latkes.getServePath()); channel.setAtomLink(Latkes.getServePath() + "/rss/" + domainURI + ".xml"); channel.setGenerator("Symphony v" + Server.VERSION + ", https://b3log.org/sym"); final String localeString = optionQueryService.getOption("miscLanguage").optString(Option.OPTION_VALUE); final String country = Locales.getCountry(localeString).toLowerCase(); final String language = Locales.getLanguage(localeString).toLowerCase(); channel.setLanguage(language + '-' + country); channel.setDescription(langPropsService.get("symDescriptionLabel")); renderer.setContent(channel.toString()); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Generates recent articles' RSS failed", e); context.getResponse().sendError(500); }
1,101
499
1,600
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/ForwardProcessor.java
ForwardProcessor
showForward
class ForwardProcessor { /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Link management service. */ @Inject private LinkMgmtService linkMgmtService; /** * Shows jump page. * * @param context the specified context */ public void showForward(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final Request request = context.getRequest(); String to = context.param(Common.GOTO); if (StringUtils.isBlank(to)) { to = Latkes.getServePath(); } final String referer = Headers.getHeader(request, "referer", ""); if (!StringUtils.startsWith(referer, Latkes.getServePath())) { context.sendRedirect(Latkes.getServePath()); return; } final String url = to; Symphonys.EXECUTOR_SERVICE.submit(() -> linkMgmtService.addLink(url)); final JSONObject user = Sessions.getUser(); if (null != user && UserExt.USER_XXX_STATUS_C_DISABLED == user.optInt(UserExt.USER_FORWARD_PAGE_STATUS)) { context.sendRedirect(to); return; } final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "forward.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put("forwardURL", to); dataModelService.fillHeaderAndFooter(context, dataModel);
123
314
437
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/ReportProcessor.java
ReportProcessor
report
class ReportProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(ReportProcessor.class); /** * Report management service. */ @Inject private ReportMgmtService reportMgmtService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Reports content or users. * * @param context the specified context */ public void report(final RequestContext context) {<FILL_FUNCTION_BODY>} }
context.renderJSON(StatusCodes.ERR); final JSONObject requestJSONObject = context.requestJSON(); final JSONObject currentUser = Sessions.getUser(); final String userId = currentUser.optString(Keys.OBJECT_ID); final String dataId = requestJSONObject.optString(Report.REPORT_DATA_ID); final int dataType = requestJSONObject.optInt(Report.REPORT_DATA_TYPE); final int type = requestJSONObject.optInt(Report.REPORT_TYPE); final String memo = StringUtils.trim(requestJSONObject.optString(Report.REPORT_MEMO)); final JSONObject report = new JSONObject(); report.put(Report.REPORT_USER_ID, userId); report.put(Report.REPORT_DATA_ID, dataId); report.put(Report.REPORT_DATA_TYPE, dataType); report.put(Report.REPORT_TYPE, type); report.put(Report.REPORT_MEMO, memo); try { reportMgmtService.addReport(report); context.renderJSONValue(Keys.CODE, StatusCodes.SUCC); } catch (final ServiceException e) { context.renderMsg(e.getMessage()); context.renderJSONValue(Keys.CODE, StatusCodes.ERR); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Adds a report failed", e); context.renderMsg(langPropsService.get("systemErrLabel")); context.renderJSONValue(Keys.CODE, StatusCodes.ERR); }
155
404
559
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/Router.java
Router
requestMapping
class Router { /** * 请求路由映射. */ public static void requestMapping() {<FILL_FUNCTION_BODY>} private static void registerProcessors() { // 活动 ActivityProcessor.register(); // 帖子 ArticleProcessor.register(); // 清风明月 BreezemoonProcessor.register(); // 验证码 CaptchaProcessor.register(); // 聊天室 ChatroomProcessor.register(); // 回帖 CommentProcessor.register(); // 文件上传 FileUploadProcessor.register(); // 关注 FollowProcessor.register(); // 首页 IndexProcessor.register(); // 登录 LoginProcessor.register(); // 通知 NotificationProcessor.register(); // 个人设置 SettingsProcessor.register(); // 标签 TagProcessor.register(); // 榜单 TopProcessor.register(); // 用户 UserProcessor.register(); // 投票 VoteProcessor.register(); final BeanManager beanManager = BeanManager.getInstance(); final LoginCheckMidware loginCheck = beanManager.getReference(LoginCheckMidware.class); final AnonymousViewCheckMidware anonymousViewCheckMidware = beanManager.getReference(AnonymousViewCheckMidware.class); // 搜索 final SearchProcessor searchProcessor = beanManager.getReference(SearchProcessor.class); Dispatcher.get("/search", searchProcessor::search); // Sitemap final SitemapProcessor sitemapProcessor = beanManager.getReference(SitemapProcessor.class); Dispatcher.get("/sitemap.xml", sitemapProcessor::sitemap); // 统计 final StatisticProcessor statisticProcessor = beanManager.getReference(StatisticProcessor.class); Dispatcher.get("/statistic", statisticProcessor::showStatistic, anonymousViewCheckMidware::handle); // 跳转页 final ForwardProcessor forwardProcessor = beanManager.getReference(ForwardProcessor.class); Dispatcher.get("/forward", forwardProcessor::showForward); // 领域 final DomainProcessor domainProcessor = beanManager.getReference(DomainProcessor.class); Dispatcher.get("/domain/{domainURI}", domainProcessor::showDomainArticles, anonymousViewCheckMidware::handle); Dispatcher.get("/domains", domainProcessor::showDomains, anonymousViewCheckMidware::handle); // RSS 订阅 final FeedProcessor feedProcessor = beanManager.getReference(FeedProcessor.class); Dispatcher.group().router().get().head().uri("/rss/recent.xml").handler(feedProcessor::genRecentRSS); Dispatcher.group().router().get().head().uri("/rss/domain/{domainURI}.xml").handler(feedProcessor::genDomainRSS); // 同城 final CityProcessor cityProcessor = beanManager.getReference(CityProcessor.class); Dispatcher.group().middlewares(loginCheck::handle).router().get().uris(new String[]{"/city/{city}", "/city/{city}/articles"}).handler(cityProcessor::showCityArticles); Dispatcher.get("/city/{city}/users", cityProcessor::showCityUsers, loginCheck::handle); // 管理后台 AdminProcessor.register(); } }
final BeanManager beanManager = BeanManager.getInstance(); // 注册 HTTP 处理器 registerProcessors(); // 注册 WebSocket 处理器 final ArticleChannel articleChannel = beanManager.getReference(ArticleChannel.class); Dispatcher.webSocket("/article-channel", articleChannel); final ArticleListChannel articleListChannel = beanManager.getReference(ArticleListChannel.class); Dispatcher.webSocket("/article-list-channel", articleListChannel); final ChatroomChannel chatroomChannel = beanManager.getReference(ChatroomChannel.class); Dispatcher.webSocket("/chat-room-channel", chatroomChannel); final GobangChannel gobangChannel = beanManager.getReference(GobangChannel.class); Dispatcher.webSocket("/gobang-game-channel", gobangChannel); final UserChannel userChannel = beanManager.getReference(UserChannel.class); Dispatcher.webSocket("/user-channel", userChannel); // 注册 HTTP 错误处理 final ErrorProcessor errorProcessor = beanManager.getReference(ErrorProcessor.class); Dispatcher.error("/error/{statusCode}", errorProcessor::handle); // 配置顶层中间件 Dispatcher.startRequestHandler = new BeforeRequestHandler(); Dispatcher.endRequestHandler = new AfterRequestHandler(); Dispatcher.mapping();
837
334
1,171
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/SearchProcessor.java
SearchProcessor
search
class SearchProcessor { /** * Search query service. */ @Inject private SearchQueryService searchQueryService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Searches. * * @param context the specified context */ public void search(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final Request request = context.getRequest(); final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "search-articles.ftl"); if (!Symphonys.ES_ENABLED && !Symphonys.ALGOLIA_ENABLED) { context.sendError(404); return; } final Map<String, Object> dataModel = renderer.getDataModel(); String keyword = context.param("key"); if (StringUtils.isBlank(keyword)) { keyword = ""; } dataModel.put(Common.KEY, Escapes.escapeHTML(keyword)); final int pageNum = Paginator.getPage(request); int pageSize = Symphonys.ARTICLE_LIST_CNT; final JSONObject user = Sessions.getUser(); if (null != user) { pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE); } final List<JSONObject> articles = new ArrayList<>(); int total = 0; if (Symphonys.ES_ENABLED) { final JSONObject result = searchQueryService.searchElasticsearch(Article.ARTICLE, keyword, pageNum, pageSize); if (null == result || 0 != result.optInt("status")) { context.sendError(404); return; } final JSONObject hitsResult = result.optJSONObject("hits"); final JSONArray hits = hitsResult.optJSONArray("hits"); for (int i = 0; i < hits.length(); i++) { final JSONObject article = hits.optJSONObject(i).optJSONObject("_source"); articles.add(article); } total = result.optInt("total"); } if (Symphonys.ALGOLIA_ENABLED) { final JSONObject result = searchQueryService.searchAlgolia(keyword, pageNum, pageSize); if (null == result) { context.sendError(404); return; } final JSONArray hits = result.optJSONArray("hits"); for (int i = 0; i < hits.length(); i++) { final JSONObject article = hits.optJSONObject(i); articles.add(article); } total = result.optInt("nbHits"); if (total > 1000) { total = 1000; // Algolia limits the maximum number of search results to 1000 } } articleQueryService.organizeArticles(articles); final Integer participantsCnt = Symphonys.ARTICLE_LIST_PARTICIPANTS_CNT; articleQueryService.genParticipants(articles, participantsCnt); dataModel.put(Article.ARTICLES, articles); final int pageCount = (int) Math.ceil(total / (double) pageSize); final List<Integer> pageNums = Paginator.paginate(pageNum, pageSize, pageCount, Symphonys.ARTICLE_LIST_WIN_SIZE); if (!pageNums.isEmpty()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum); dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); String searchEmptyLabel = langPropsService.get("searchEmptyLabel"); searchEmptyLabel = searchEmptyLabel.replace("${key}", keyword); dataModel.put("searchEmptyLabel", searchEmptyLabel);
201
1,082
1,283
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/SitemapProcessor.java
SitemapProcessor
sitemap
class SitemapProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(SitemapProcessor.class); /** * Sitemap query service. */ @Inject private SitemapQueryService sitemapQueryService; /** * Returns the sitemap. * * @param context the specified context */ public void sitemap(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final TextXmlRenderer renderer = new TextXmlRenderer(); context.setRenderer(renderer); final Sitemap sitemap = new Sitemap(); LOGGER.log(Level.DEBUG, "Generating sitemap...."); sitemapQueryService.genIndex(sitemap); sitemapQueryService.genDomains(sitemap); // sitemapQueryService.genArticles(sitemap); final String content = sitemap.toString(); LOGGER.log(Level.DEBUG, "Generated sitemap"); renderer.setContent(content);
134
148
282
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/SkinRenderer.java
SkinRenderer
getTemplate
class SkinRenderer extends AbstractFreeMarkerRenderer { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(SkinRenderer.class); /** * HTTP request context. */ private final RequestContext context; /** * Constructs a skin renderer with the specified request context and template name. * * @param context the specified request context * @param templateName the specified template name */ public SkinRenderer(final RequestContext context, final String templateName) { this.context = context; this.context.setRenderer(this); setTemplateName(templateName); } /** * Gets a template with the specified search engine bot flag and user. * * @param isSearchEngineBot the specified search engine bot flag * @param user the specified user * @return template */ public Template getTemplate(final boolean isSearchEngineBot, final JSONObject user) {<FILL_FUNCTION_BODY>} @Override protected Template getTemplate() { final boolean isSearchEngineBot = Sessions.isBot(); final JSONObject user = Sessions.getUser(); return getTemplate(isSearchEngineBot, user); } /** * Processes the specified FreeMarker template with the specified request, data model, pjax hacking. * * @param request the specified request * @param dataModel the specified data model * @param template the specified FreeMarker template * @return generated HTML * @throws Exception exception */ protected String genHTML(final Request request, final Map<String, Object> dataModel, final Template template) throws Exception { final boolean isPJAX = isPJAX(context); dataModel.put("pjax", isPJAX); if (!isPJAX) { return super.genHTML(request, dataModel, template); } final StringWriter stringWriter = new StringWriter(); template.setOutputEncoding("UTF-8"); template.process(dataModel, stringWriter); final long endTimeMillis = System.currentTimeMillis(); final String dateString = DateFormatUtils.format(endTimeMillis, "yyyy/MM/dd HH:mm:ss"); final long startTimeMillis = (Long) context.attr(Keys.HttpRequest.START_TIME_MILLIS); final String msg = String.format("\n<!-- Generated by Latke (https://github.com/88250/latke) in %1$dms, %2$s -->", endTimeMillis - startTimeMillis, dateString); final String pjaxContainer = context.header("X-PJAX-Container"); return StringUtils.substringBetween(stringWriter.toString(), "<!---- pjax {" + pjaxContainer + "} start ---->", "<!---- pjax {" + pjaxContainer + "} end ---->") + msg; } @Override protected void beforeRender(final RequestContext context) { } @Override protected void afterRender(final RequestContext context) { } /** * Determines whether the specified request is sending with pjax. * * @param context the specified request context * @return {@code true} if it is sending with pjax, otherwise returns {@code false} */ private static boolean isPJAX(final RequestContext context) { final boolean pjax = Boolean.valueOf(context.header("X-PJAX")); final String pjaxContainer = context.header("X-PJAX-Container"); return pjax && StringUtils.isNotBlank(pjaxContainer); } }
String templateDirName = Sessions.getTemplateDir(); final String templateName = getTemplateName(); try { Template ret; try { ret = Templates.getTemplate(templateDirName + "/" + templateName); } catch (final Exception e) { if (Symphonys.SKIN_DIR_NAME.equals(templateDirName) || Symphonys.MOBILE_SKIN_DIR_NAME.equals(templateDirName)) { throw e; } // Try to load default template ret = Templates.getTemplate(Symphonys.SKIN_DIR_NAME + "/" + templateName); } if (isSearchEngineBot) { return ret; } ret.setLocale(Locales.getLocale()); if (null != user) { ret.setTimeZone(TimeZone.getTimeZone(user.optString(UserExt.USER_TIMEZONE))); } else { ret.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID())); } return ret; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Get template [dir=" + templateDirName + ", name=" + templateName + "] failed", e); return null; }
936
336
1,272
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/StatisticProcessor.java
StatisticProcessor
loadStatData
class StatisticProcessor { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(StatisticProcessor.class); /** * Month days. */ private final List<String> monthDays = new ArrayList<>(); /** * User counts. */ private final List<Integer> userCnts = new ArrayList<>(); /** * Article counts. */ private final List<Integer> articleCnts = new ArrayList<>(); /** * Comment counts. */ private final List<Integer> commentCnts = new ArrayList<>(); /** * History months. */ private final List<String> months = new ArrayList<>(); /** * History user counts. */ private final List<Integer> historyUserCnts = new ArrayList<>(); /** * History article counts. */ private final List<Integer> historyArticleCnts = new ArrayList<>(); /** * History comment counts. */ private final List<Integer> historyCommentCnts = new ArrayList<>(); /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Article query service. */ @Inject private ArticleQueryService articleQueryService; /** * Comment query service. */ @Inject private CommentQueryService commentQueryService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Visit management service. */ @Inject private VisitMgmtService visitMgmtService; /** * Loads statistic data. */ public void loadStatData() {<FILL_FUNCTION_BODY>} /** * Shows data statistic. * * @param context the specified context */ public void showStatistic(final RequestContext context) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "statistic.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put("monthDays", monthDays); dataModel.put("userCnts", userCnts); dataModel.put("articleCnts", articleCnts); dataModel.put("commentCnts", commentCnts); dataModel.put("months", months); dataModel.put("historyUserCnts", historyUserCnts); dataModel.put("historyArticleCnts", historyArticleCnts); dataModel.put("historyCommentCnts", historyCommentCnts); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); dataModel.put(Common.ONLINE_VISITOR_CNT, optionQueryService.getOnlineVisitorCount()); dataModel.put(Common.ONLINE_MEMBER_CNT, optionQueryService.getOnlineMemberCount()); final JSONObject statistic = optionQueryService.getStatistic(); dataModel.put(Option.CATEGORY_C_STATISTIC, statistic); } }
try { final Date end = new Date(); final Date dayStart = DateUtils.addDays(end, -30); monthDays.clear(); userCnts.clear(); articleCnts.clear(); commentCnts.clear(); months.clear(); historyArticleCnts.clear(); historyCommentCnts.clear(); historyUserCnts.clear(); for (int i = 0; i < 31; i++) { final Date day = DateUtils.addDays(dayStart, i); monthDays.add(DateFormatUtils.format(day, "yyyy-MM-dd")); final int userCnt = userQueryService.getUserCntInDay(day); userCnts.add(userCnt); final int articleCnt = articleQueryService.getArticleCntInDay(day); articleCnts.add(articleCnt); final int commentCnt = commentQueryService.getCommentCntInDay(day); commentCnts.add(commentCnt); } final JSONObject firstAdmin = userQueryService.getAdmins().get(0); final long monthStartTime = Times.getMonthStartTime(firstAdmin.optLong(Keys.OBJECT_ID)); final Date monthStart = new Date(monthStartTime); int i = 1; while (true) { final Date month = DateUtils.addMonths(monthStart, i); if (month.after(end)) { break; } i++; months.add(DateFormatUtils.format(month, "yyyy-MM")); final int userCnt = userQueryService.getUserCntInMonth(month); historyUserCnts.add(userCnt); final int articleCnt = articleQueryService.getArticleCntInMonth(month); historyArticleCnts.add(articleCnt); final int commentCnt = commentQueryService.getCommentCntInMonth(month); historyCommentCnts.add(commentCnt); } visitMgmtService.expire(); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Loads stat data failed", e); }
902
580
1,482
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/TopProcessor.java
TopProcessor
showBalance
class TopProcessor { /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Pointtransfer query service. */ @Inject private PointtransferQueryService pointtransferQueryService; /** * Activity query service. */ @Inject private ActivityQueryService activityQueryService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Link query service. */ @Inject private LinkQueryService linkQueryService; /** * Register request handlers. */ public static void register() { final BeanManager beanManager = BeanManager.getInstance(); final AnonymousViewCheckMidware anonymousViewCheckMidware = beanManager.getReference(AnonymousViewCheckMidware.class); final TopProcessor topProcessor = beanManager.getReference(TopProcessor.class); Dispatcher.get("/top", topProcessor::showTop, anonymousViewCheckMidware::handle); Dispatcher.get("/top/link", topProcessor::showLink, anonymousViewCheckMidware::handle); Dispatcher.get("/top/balance", topProcessor::showBalance, anonymousViewCheckMidware::handle); Dispatcher.get("/top/consumption", topProcessor::showConsumption, anonymousViewCheckMidware::handle); Dispatcher.get("/top/checkin", topProcessor::showCheckin, anonymousViewCheckMidware::handle); } /** * Shows top. * * @param context the specified context */ public void showTop(final RequestContext context) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "top/index.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put(Common.SELECTED, Common.TOP); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows link ranking list. * * @param context the specified context */ public void showLink(final RequestContext context) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "top/link.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> topLinks = linkQueryService.getTopLink(Symphonys.TOP_CNT); dataModel.put(Common.TOP_LINKS, topLinks); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows balance ranking list. * * @param context the specified context */ public void showBalance(final RequestContext context) {<FILL_FUNCTION_BODY>} /** * Shows consumption ranking list. * * @param context the specified context */ public void showConsumption(final RequestContext context) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "top/consumption.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> users = pointtransferQueryService.getTopConsumptionUsers(Symphonys.TOP_CNT); dataModel.put(Common.TOP_CONSUMPTION_USERS, users); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } /** * Shows checkin ranking list. * * @param context the specified context */ public void showCheckin(final RequestContext context) { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "top/checkin.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> users = activityQueryService.getTopCheckinUsers(Symphonys.TOP_CNT); dataModel.put(Common.TOP_CHECKIN_USERS, users); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel); } }
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(context, "top/balance.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); final List<JSONObject> users = pointtransferQueryService.getTopBalanceUsers(Symphonys.TOP_CNT); dataModel.put(Common.TOP_BALANCE_USERS, users); dataModelService.fillHeaderAndFooter(context, dataModel); dataModelService.fillRandomArticles(dataModel); dataModelService.fillSideHotArticles(dataModel); dataModelService.fillSideTags(dataModel); dataModelService.fillLatestCmts(dataModel);
1,272
177
1,449
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/channel/ArticleListChannel.java
ArticleListChannel
notifyHeat
class ArticleListChannel implements WebSocketChannel { /** * Session articles &lt;session, "articleId1,articleId2"&gt;. */ public static final Map<WebSocketSession, String> SESSIONS = new ConcurrentHashMap<>(); /** * Notifies the specified article heat message to browsers. * * @param message the specified message, for example * { * "articleId": "", * "operation": "" // "+"/"-" * } */ public static void notifyHeat(final JSONObject message) {<FILL_FUNCTION_BODY>} /** * Called when the socket connection with the browser is established. * * @param session session */ @Override public void onConnect(final WebSocketSession session) { final String articleIds = session.getParameter(Article.ARTICLE_T_IDS); if (StringUtils.isBlank(articleIds)) { return; } SESSIONS.put(session, articleIds); } /** * Called when the connection closed. * * @param session session */ @Override public void onClose(final WebSocketSession session) { SESSIONS.remove(session); } /** * Called when a message received from the browser. * * @param message message */ @Override public void onMessage(final Message message) { } /** * Called when a error received. * * @param error error */ @Override public void onError(final Error error) { SESSIONS.remove(error.session); } }
final String articleId = message.optString(Article.ARTICLE_T_ID); final String msgStr = message.toString(); for (final Map.Entry<WebSocketSession, String> entry : SESSIONS.entrySet()) { final WebSocketSession session = entry.getKey(); final String articleIds = entry.getValue(); if (!StringUtils.contains(articleIds, articleId)) { continue; } session.sendText(msgStr); }
438
124
562
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/channel/ChatroomChannel.java
ChatroomChannel
notifyChat
class ChatroomChannel implements WebSocketChannel { /** * Session set. */ public static final Set<WebSocketSession> SESSIONS = Collections.newSetFromMap(new ConcurrentHashMap()); /** * Called when the socket connection with the browser is established. * * @param session session */ @Override public void onConnect(final WebSocketSession session) { SESSIONS.add(session); synchronized (SESSIONS) { final Iterator<WebSocketSession> i = SESSIONS.iterator(); while (i.hasNext()) { final WebSocketSession s = i.next(); final String msgStr = new JSONObject().put(Common.ONLINE_CHAT_CNT, SESSIONS.size()).put(Common.TYPE, "online").toString(); s.sendText(msgStr); } } } /** * Called when the connection closed. * * @param session session */ @Override public void onClose(final WebSocketSession session) { removeSession(session); } /** * Called when a message received from the browser. * * @param message message */ @Override public void onMessage(final Message message) { } /** * Called when a error received. * * @param error error */ @Override public void onError(final Error error) { removeSession(error.session); } /** * Notifies the specified chat message to browsers. * * @param message the specified message, for example, * { * "userName": "", * "content": "" * } */ public static void notifyChat(final JSONObject message) {<FILL_FUNCTION_BODY>} /** * Removes the specified session. * * @param session the specified session */ private void removeSession(final WebSocketSession session) { SESSIONS.remove(session); synchronized (SESSIONS) { final Iterator<WebSocketSession> i = SESSIONS.iterator(); while (i.hasNext()) { final WebSocketSession s = i.next(); final String msgStr = new JSONObject().put(Common.ONLINE_CHAT_CNT, SESSIONS.size()).put(Common.TYPE, "online").toString(); s.sendText(msgStr); } } } }
message.put(Common.TYPE, "msg"); final String msgStr = message.toString(); synchronized (SESSIONS) { final Iterator<WebSocketSession> i = SESSIONS.iterator(); while (i.hasNext()) { final WebSocketSession session = i.next(); session.sendText(msgStr); } }
633
93
726
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/channel/UserChannel.java
UserChannel
sendCmd
class UserChannel implements WebSocketChannel { /** * Session set. */ public static final Map<String, Set<WebSocketSession>> SESSIONS = new ConcurrentHashMap(); /** * Called when the socket connection with the browser is established. * * @param session session */ @Override public void onConnect(final WebSocketSession session) { final Session httpSession = session.getHttpSession(); final JSONObject user = new JSONObject(httpSession.getAttribute(User.USER)); if (null == user) { return; } final String userId = user.optString(Keys.OBJECT_ID); final Set<WebSocketSession> userSessions = SESSIONS.getOrDefault(userId, Collections.newSetFromMap(new ConcurrentHashMap())); userSessions.add(session); SESSIONS.put(userId, userSessions); final BeanManager beanManager = BeanManager.getInstance(); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); final String ip = httpSession.getAttribute(Common.IP); userMgmtService.updateOnlineStatus(userId, ip, true, true); } /** * Called when the connection closed. * * @param session session */ @Override public void onClose(final WebSocketSession session) { removeSession(session); } /** * Called when a message received from the browser. * * @param message message */ @Override public void onMessage(final Message message) { final Session session = message.session.getHttpSession(); final String userStr = session.getAttribute(User.USER); if (null == userStr) { return; } final JSONObject user = new JSONObject(userStr); final String userId = user.optString(Keys.OBJECT_ID); final BeanManager beanManager = BeanManager.getInstance(); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); final String ip = session.getAttribute(Common.IP); userMgmtService.updateOnlineStatus(userId, ip, true, true); } /** * Called when a error received. * * @param error error */ @Override public void onError(final Error error) { removeSession(error.session); } /** * Sends command to browsers. * * @param message the specified message, for example, * "userId": "", * "cmd": "" */ public static void sendCmd(final JSONObject message) {<FILL_FUNCTION_BODY>} /** * Removes the specified session. * * @param session the specified session */ private void removeSession(final WebSocketSession session) { final Session httpSession = session.getHttpSession(); final String userStr = httpSession.getAttribute(User.USER); if (null == userStr) { return; } final JSONObject user = new JSONObject(userStr); final String userId = user.optString(Keys.OBJECT_ID); final BeanManager beanManager = BeanManager.getInstance(); final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class); final String ip = httpSession.getAttribute(Common.IP); Set<WebSocketSession> userSessions = SESSIONS.get(userId); if (null == userSessions) { userMgmtService.updateOnlineStatus(userId, ip, false, false); return; } userSessions.remove(session); if (userSessions.isEmpty()) { userMgmtService.updateOnlineStatus(userId, ip, false, false); return; } } }
final String recvUserId = message.optString(UserExt.USER_T_ID); if (StringUtils.isBlank(recvUserId)) { return; } final String msgStr = message.toString(); for (final String userId : SESSIONS.keySet()) { if (userId.equals(recvUserId)) { final Set<WebSocketSession> sessions = SESSIONS.get(userId); for (final WebSocketSession session : sessions) { session.sendText(msgStr); } } }
1,007
147
1,154
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/AnonymousViewCheckMidware.java
AnonymousViewCheckMidware
getCookie
class AnonymousViewCheckMidware { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(AnonymousViewCheckMidware.class); /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; private static Cookie getCookie(final Request request, final String name) {<FILL_FUNCTION_BODY>} private static void addCookie(final Response response, final String name, final String value) { final Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(60 * 60 * 24); cookie.setHttpOnly(true); cookie.setSecure(StringUtils.equalsIgnoreCase(Latkes.getServerScheme(), "https")); response.addCookie(cookie); } public void handle(final RequestContext context) { final Request request = context.getRequest(); final String requestURI = context.requestURI(); final String[] skips = Symphonys.ANONYMOUS_VIEW_SKIPS.split(","); for (final String skip : skips) { if (AntPathMatcher.match(Latkes.getContextPath() + skip, requestURI)) { return; } } if (requestURI.startsWith(Latkes.getContextPath() + "/article/")) { final String articleId = StringUtils.substringAfter(requestURI, Latkes.getContextPath() + "/article/"); try { final JSONObject article = articleRepository.get(articleId); if (null == article) { context.sendError(404); context.abort(); return; } if (Article.ARTICLE_ANONYMOUS_VIEW_C_NOT_ALLOW == article.optInt(Article.ARTICLE_ANONYMOUS_VIEW) && !Sessions.isLoggedIn()) { context.sendError(401); context.abort(); return; } else if (Article.ARTICLE_ANONYMOUS_VIEW_C_ALLOW == article.optInt(Article.ARTICLE_ANONYMOUS_VIEW)) { context.handle(); return; } } catch (final RepositoryException e) { context.sendError(500); context.abort(); return; } } // Check if admin allow to anonymous view final JSONObject option = optionQueryService.getOption(Option.ID_C_MISC_ALLOW_ANONYMOUS_VIEW); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { final JSONObject currentUser = Sessions.getUser(); // https://github.com/b3log/symphony/issues/373 final String cookieNameVisits = "anonymous-visits"; final Cookie visitsCookie = getCookie(request, cookieNameVisits); if (null == currentUser) { if (null != visitsCookie) { final JSONArray uris = new JSONArray(URLs.decode(visitsCookie.getValue())); for (int i = 0; i < uris.length(); i++) { final String uri = uris.getString(i); if (uri.equals(requestURI)) { return; } } uris.put(requestURI); if (uris.length() > Symphonys.ANONYMOUS_VIEW_URIS) { context.sendError(401); context.abort(); return; } addCookie(context.getResponse(), cookieNameVisits, URLs.encode(uris.toString())); context.handle(); return; } else { final JSONArray uris = new JSONArray(); uris.put(requestURI); addCookie(context.getResponse(), cookieNameVisits, URLs.encode(uris.toString())); context.handle(); return; } } else { // logged in if (null != visitsCookie) { final Cookie cookie = new Cookie(cookieNameVisits, ""); cookie.setMaxAge(0); cookie.setPath("/"); context.getResponse().addCookie(cookie); context.handle(); return; } } } context.handle(); } }
final Set<Cookie> cookies = request.getCookies(); if (cookies.isEmpty()) { return null; } for (final Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; } } return null;
1,235
81
1,316
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/CSRFMidware.java
CSRFMidware
check
class CSRFMidware { /** * Language service. */ @Inject private LangPropsService langPropsService; public void fill(final RequestContext context) { context.handle(); final AbstractResponseRenderer renderer = context.getRenderer(); if (null == renderer) { return; } final Map<String, Object> dataModel = renderer.getRenderDataModel(); dataModel.put(Common.CSRF_TOKEN, Sessions.getCSRFToken(context)); } public void check(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final JSONObject exception = new JSONObject(); exception.put(Keys.MSG, langPropsService.get("csrfCheckFailedLabel")); exception.put(Keys.CODE, StatusCodes.ERR); // 1. Check Referer final String referer = context.header("Referer"); if (!StringUtils.startsWith(referer, StringUtils.substringBeforeLast(Latkes.getServePath(), ":"))) { context.renderJSON(exception); context.abort(); return; } // 2. Check Token final String clientToken = context.header(Common.CSRF_TOKEN); final String serverToken = Sessions.getCSRFToken(context); if (!StringUtils.equals(clientToken, serverToken)) { context.renderJSON(exception); context.abort(); return; } context.handle();
163
228
391
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/LoginCheckMidware.java
LoginCheckMidware
handle
class LoginCheckMidware { public void handle(final RequestContext context) {<FILL_FUNCTION_BODY>} }
final JSONObject currentUser = Sessions.getUser(); if (null == currentUser) { context.sendError(401); context.abort(); return; } final int point = currentUser.optInt(UserExt.USER_POINT); final int appRole = currentUser.optInt(UserExt.USER_APP_ROLE); if (UserExt.USER_APP_ROLE_C_HACKER == appRole) { currentUser.put(UserExt.USER_T_POINT_HEX, Integer.toHexString(point)); } else { currentUser.put(UserExt.USER_T_POINT_CC, UserExt.toCCString(point)); } context.attr(User.USER, currentUser); context.handle();
35
205
240
<no_super_class>
88250_symphony
symphony/src/main/java/org/b3log/symphony/processor/middleware/PermissionMidware.java
PermissionMidware
check
class PermissionMidware { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(PermissionMidware.class); /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Role query service. */ @Inject private RoleQueryService roleQueryService; public void check(final RequestContext context) {<FILL_FUNCTION_BODY>} }
Stopwatchs.start("Check Permissions"); try { final JSONObject exception = new JSONObject(); exception.put(Keys.MSG, langPropsService.get("noPermissionLabel")); exception.put(Keys.CODE, 403); final String prefix = "permission.rule.url."; final String requestURI = StringUtils.substringAfter(context.requestURI(), Latkes.getContextPath()); final String method = context.method(); String rule = prefix; try { final RouteResolution routeResolution = RouteHandler.doMatch(requestURI, method); rule += routeResolution.getMatchedUriTemplate() + "." + method; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Match method failed", e); context.sendError(500); context.abort(); return; } final Set<String> requisitePermissions = Symphonys.URL_PERMISSION_RULES.get(rule); if (null == requisitePermissions) { context.handle(); return; } final JSONObject user = Sessions.getUser(); final String roleId = null != user ? user.optString(User.USER_ROLE) : Role.ROLE_ID_C_VISITOR; final String userName = null != user ? " " + user.optString(User.USER_NAME) + " " : ""; final Set<String> grantPermissions = roleQueryService.getPermissions(roleId); if (!Permission.hasPermission(requisitePermissions, grantPermissions)) { final Map<String, Object> errDataModel = new HashMap<>(); String noPermissionLabel = langPropsService.get("noPermissionLabel"); final JSONObject role = roleQueryService.getRole(roleId); noPermissionLabel = noPermissionLabel.replace("{roleName}", role.optString(Role.ROLE_NAME)); noPermissionLabel = noPermissionLabel.replace("{user}", userName); errDataModel.put("noPermissionLabel", noPermissionLabel); context.sendError(403, errDataModel); context.abort(); return; } context.handle(); } finally { Stopwatchs.end(); }
129
580
709
<no_super_class>