Skip to content

Commit

Permalink
Use single expression functions (#165)
Browse files Browse the repository at this point in the history
* Use single expression functions

Fix #153

* Fix ktlint format for maven

* Formatting

* Use single expression functions

Fix #153

* Use single expression functions - Review fixes

Fix #153
  • Loading branch information
pvliss authored and sendilkumarn committed Jul 4, 2019
1 parent c231365 commit 193ae8f
Show file tree
Hide file tree
Showing 123 changed files with 936 additions and 1,123 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,14 @@
const mapper = entityInstance + 'Mapper';
const entityListToDtoListReference = mapper + '.' + 'toDto';
const entityToDtoReference = mapper + '::'+ 'toDto';
if (jpaMetamodelFiltering) { %>
fun getAll<%= entityClassPlural %>(criteria: <%= entityClass %>Criteria<% if (pagination != 'no') { %>, pageable: Pageable, @RequestParam queryParams: MultiValueMap<String, String>, uriBuilder: UriComponentsBuilder<% } %>): ResponseEntity<MutableList<<%= instanceType %>>> {
if (jpaMetamodelFiltering) {
_%>
fun getAll<%= entityClassPlural %>(
criteria: <%= entityClass %>Criteria<% if (pagination != 'no') { %>,
pageable: Pageable,
@RequestParam queryParams: MultiValueMap<String, String>,
uriBuilder: UriComponentsBuilder<% } %>
): ResponseEntity<MutableList<<%= instanceType %>>> {
log.debug("REST request to get <%= entityClassPlural %> by criteria: {}", criteria)
<%_ if (pagination === 'no') { _%>
val entityList = <%= entityInstance %>QueryService.findByCriteria(criteria)
Expand Down Expand Up @@ -55,7 +61,13 @@
return <%= entityListToDtoListReference %>(<%= entityInstancePlural %>)<% } else { %>
return <%= entityInstance %>Repository.<% if (fieldsContainOwnerManyToMany) { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>()<% } %>
<%_ } if (pagination !== 'no') { _%>
fun getAll<%= entityClassPlural %>(pageable: Pageable, @RequestParam queryParams: MultiValueMap<String, String>, uriBuilder: UriComponentsBuilder<% if (fieldsContainNoOwnerOneToOne) { %>, @RequestParam(required = false) filter: String?<% } %><% if (fieldsContainOwnerManyToMany) { %>, @RequestParam(required = false, defaultValue = "false") eagerload: Boolean<% } %>): ResponseEntity<MutableList<<%= instanceType %>>> {<%- include('get_all_stream_template', {viaService: viaService}); -%>
fun getAll<%= entityClassPlural %>(
pageable: Pageable,
@RequestParam queryParams: MultiValueMap<String, String>,
uriBuilder: UriComponentsBuilder<% if (fieldsContainNoOwnerOneToOne) { %>,
@RequestParam(required = false) filter: String?<% } if (fieldsContainOwnerManyToMany) { %>,
@RequestParam(required = false, defaultValue = "false") eagerload: Boolean<% } %>
) : ResponseEntity<MutableList<<%= instanceType %>>> {<%- include('get_all_stream_template', {viaService: viaService}); -%>
log.debug("REST request to get a page of <%= entityClassPlural %>")
<%_ if (viaService) { _%>
<%_ if (fieldsContainOwnerManyToMany) { _%>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,11 @@ interface <%=entityClass%>Repository : <% if (databaseType === 'sql') { %>JpaRep
<%_ if (fieldsContainOwnerManyToMany === true) {
if (databaseType === 'sql') { _%>

@Query(value = "select distinct <%= entityInstance %> from <%= asEntity(entityClass) %> <%= entityInstance %><% for (idx in relationships) {
@Query(
value = "select distinct <%= entityInstance %> from <%= asEntity(entityClass) %> <%= entityInstance %><% for (idx in relationships) {
if (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) { %> left join fetch <%=entityInstance%>.<%=relationships[idx].relationshipFieldNamePlural%><%} }%>",
countQuery = "select count(distinct <%= entityInstance %>) from <%= asEntity(entityClass) %> <%= entityInstance %>")
countQuery = "select count(distinct <%= entityInstance %>) from <%= asEntity(entityClass) %> <%= entityInstance %>"
)
fun findAllWithEagerRelationships(pageable: Pageable): Page<<%= asEntity(entityClass) %>>

@Query(value = "select distinct <%= entityInstance %> from <%= asEntity(entityClass) %> <%= entityInstance %><% for (idx in relationships) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class <%= serviceClassName %>(
<%- include('../common/inject_template', {viaService: false, constructorName: serviceClassName, queryService: false, isUsingMapsId: false, mapsIdAssoc: null, isController: false}); -%>
) : QueryService<<%= asEntity(entityClass) %>>() {

private val log = LoggerFactory.getLogger(<%= serviceClassName %>::class.java)
private val log = LoggerFactory.getLogger(javaClass)

/**
* Return a [MutableList] of [<%= instanceType %>] which matches the criteria from the database.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ class <%= serviceClassName %>(
<%- include('../../common/inject_template', {asEntity, asDto, viaService: viaService, constructorName: serviceClassName, queryService: false, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: false}); -%>
)<% if (service === 'serviceImpl') { %> : <%= entityClass %>Service<% } %> {

private val log = LoggerFactory.getLogger(<%= serviceClassName %>::class.java)
private val log = LoggerFactory.getLogger(javaClass)

/**
* Save a <%= entityInstance %>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ import org.mapstruct.Mappings
if (!existingMappings.includes(relationships[idx].otherEntityNameCapitalized) && asEntity(relationships[idx].otherEntityNameCapitalized) !== entityClass) {
existingMappings.push(relationships[idx].otherEntityNameCapitalized);
} } } %><%= existingMappings.map(otherEntityNameCapitalized => otherEntityNameCapitalized + 'Mapper::class').join(', ') %>])
interface <%= entityClass %>Mapper : EntityMapper<<%= asDto(entityClass) %>, <%= asEntity(entityClass) %>> {
interface <%= entityClass %>Mapper :
EntityMapper<<%= asDto(entityClass) %>, <%= asEntity(entityClass) %>> {
<%_
// entity -> DTO mapping
var mappedRelsEnt = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ import java.util.UUID<% } %><% if (searchEngine === 'elasticsearch') { %>
import org.elasticsearch.index.query.QueryBuilders.queryStringQuery
<%_ } _%>

<%_
let entityName = entityInstance;
if (clientRootFolder && !skipUiGrouping) {
entityName = _.camelCase(`${clientRootFolder}${entityClass}`)
}
_%>
private const val ENTITY_NAME = "<%= entityName %>"

/**
* REST controller for managing [<%= packageName %>.domain.<%= asEntity(entityClass) %>].
*/
Expand All @@ -117,14 +125,10 @@ class <%= entityClass %>Resource(
_%><%- include('../../common/inject_template', {viaService: viaService, constructorName: entityClass + 'Resource', queryService: jpaMetamodelFiltering, isUsingMapsId: isUsingMapsId, mapsIdAssoc: mapsIdAssoc, isController: true}); -%>
) {

private val log = LoggerFactory.getLogger(this.javaClass)
private val log = LoggerFactory.getLogger(javaClass)

@Value("\${jhipster.clientApp.name}")
private var applicationName: String? = null
<%_ let entityName = entityInstance;
if (clientRootFolder && !skipUiGrouping) {
entityName = _.camelCase(`${clientRootFolder}${entityClass}`)
} _%>

/**
* `POST /<%= entityApiUrl %>` : Create a new <%= entityInstance %>.
Expand All @@ -137,7 +141,10 @@ _%><%- include('../../common/inject_template', {viaService: viaService, construc
fun create<%= entityClass %>(<% if (validation) { %>@Valid <% } %>@RequestBody <%= instanceName %>: <%= instanceType %>): ResponseEntity<<%= instanceType %>> {
log.debug("REST request to save <%= entityClass %> : {}", <%= instanceName %>)
if (<%= instanceName %>.id != null) {
throw BadRequestAlertException("A new <%= entityInstance %> cannot already have an ID", ENTITY_NAME, "idexists")
throw BadRequestAlertException(
"A new <%= entityInstance %> cannot already have an ID",
ENTITY_NAME, "idexists"
)
}
<%_ if (saveUserSnapshot) { %>
if (<%= instanceName %>.user != null) {
Expand Down Expand Up @@ -177,7 +184,12 @@ _%><%- include('../../common/inject_template', {viaService: viaService, construc
<%_ } _%>
<%- include('../../common/save_template', {asEntity, asDto, viaService: viaService, returnDirectly: false, isUsingMapsId: false, mapsIdAssoc: mapsIdAssoc}); -%>
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, <%= instanceName %>.id.toString()))
.headers(
HeaderUtil.createEntityUpdateAlert(
applicationName, <%= enableTranslation %>, ENTITY_NAME,
<%= instanceName %>.id.toString()
)
)
.body(result)
}

Expand Down Expand Up @@ -240,7 +252,8 @@ _%><%- include('../../common/inject_template', {viaService: viaService, construc
fun delete<%= entityClass %>(@PathVariable id: <%= pkType %>): ResponseEntity<Void> {
log.debug("REST request to delete <%= entityClass %> : {}", id)
<%- include('../../common/delete_template', {viaService: viaService}); -%>
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (pkType !== 'String') { %>.toString()<% } %>)).build()
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, <%= enableTranslation %>, ENTITY_NAME, id<% if (pkType !== 'String') { %>.toString()<% } %>)).build()
}<% if (searchEngine === 'elasticsearch') { %>

/**
Expand All @@ -254,8 +267,4 @@ _%><%- include('../../common/inject_template', {viaService: viaService, construc
* @return the result of the search.
*/
@GetMapping("/_search/<%= entityApiUrl %>")<%- include('../../common/search_template', {asEntity, asDto, viaService}); -%><% } %>

companion object {
private const val ENTITY_NAME = "<%= entityName %>"
}
}
20 changes: 13 additions & 7 deletions generators/server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -1941,7 +1941,7 @@ function writeFiles() {
</dependencies>`;
this.addMavenPlugin('org.jetbrains.kotlin', 'kotlin-maven-plugin', '${kotlin.version}', kotlinOther);

removeDefaultMavenCompilerPlugin(this);
updatePom(this);
const defaultCompileOther = ` <executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
Expand Down Expand Up @@ -2099,25 +2099,31 @@ function writeFilesToDisk(files, generator, returnFiles, prefix) {
}

/**
* remove the default <maven-compiler-plugin> configuration from pom.xml.
* Manually updates the pom.xml file to perform the following operations:
* 1. Set the Kotlin source directories as the default (Needed for the ktlint plugin to properly format the sources)
* 2. Remove the default <maven-compiler-plugin> configuration.
*/
function removeDefaultMavenCompilerPlugin(generator) {
function updatePom(generator) {
const _this = generator || this;

const fullPath = path.join(process.cwd(), 'pom.xml');
const artifactId = 'maven-compiler-plugin';

const xml = _this.fs.read(fullPath).toString();

const $ = cheerio.load(xml, { xmlMode: true });

// 1. Set the Kotlin source directories as the default
$('build > defaultGoal').after(`
<sourceDirectory>src/main/kotlin</sourceDirectory>
<testSourceDirectory>src/test/kotlin</testSourceDirectory>
`);
// 2. Remove the default <maven-compiler-plugin> configuration
$(`build > plugins > plugin > artifactId:contains('${artifactId}')`)
.parent()
.remove();

const modifiedXml = $.xml();

_this.fs.write(fullPath, modifiedXml);
_this.fs.write(fullPath, $.xml());
}

module.exports = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ import java.net.UnknownHostException
<%_ } _%>
class <%= mainClass %>(private val env: Environment) : InitializingBean {

private val log = LoggerFactory.getLogger(<%= mainClass %>::class.java)
private val log = LoggerFactory.getLogger(javaClass)

/**
* Initializes <%= baseName %>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,8 @@ open class LoggingAspect(private val env: Environment) {
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)"
)
fun springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
fun springBeanPointcut() =
Unit // Method is empty as this is just a Pointcut, the implementations are in the advices.

/**
* Pointcut that matches all Spring beans in the application's main packages.
Expand All @@ -61,9 +60,8 @@ open class LoggingAspect(private val env: Environment) {
" || within(<%=packageName%>.service..*)" +
" || within(<%=packageName%>.web.rest..*)"
)
fun applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
fun applicationPackagePointcut() =
Unit // Method is empty as this is just a Pointcut, the implementations are in the advices.

/**
* Advice that logs methods throwing exceptions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,12 @@ import feign.RequestInterceptor
import feign.RequestTemplate
import org.springframework.stereotype.Component

private const val AUTHORIZATION_HEADER = "Authorization"
private const val BEARER_TOKEN_TYPE = "Bearer"

@Component
class UserFeignClientInterceptor : RequestInterceptor {

override fun apply(template: RequestTemplate) {
override fun apply(template: RequestTemplate) =
getCurrentUserJWT().ifPresent { s -> template.header(AUTHORIZATION_HEADER,"$BEARER_TOKEN_TYPE $s") }
}

companion object {
private const val AUTHORIZATION_HEADER = "Authorization"
private const val BEARER_TOKEN_TYPE = "Bearer"
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,8 @@ import io.github.jhipster.security.uaa.LoadBalancedResourceDetails
class OAuth2InterceptedFeignConfiguration(private val loadBalancedResourceDetails: LoadBalancedResourceDetails) {

@Bean(name = ["oauth2RequestInterceptor"])
fun getOAuth2RequestInterceptor(): RequestInterceptor{
return OAuth2FeignRequestInterceptor(DefaultOAuth2ClientContext(), loadBalancedResourceDetails)
}
fun getOAuth2RequestInterceptor() =
OAuth2FeignRequestInterceptor(DefaultOAuth2ClientContext(), loadBalancedResourceDetails)
}
<%_ } _%>
<%_ if (authenticationType === 'oauth2') { _%>
Expand All @@ -44,8 +43,7 @@ import <%=packageName%>.security.oauth2.AuthorizationHeaderUtil
class OAuth2InterceptedFeignConfiguration {

@Bean(name = ["oauth2RequestInterceptor"])
fun getOAuth2RequestInterceptor(authorizationHeaderUtil: AuthorizationHeaderUtil): RequestInterceptor {
return TokenRelayRequestInterceptor(authorizationHeaderUtil)
}
fun getOAuth2RequestInterceptor(authorizationHeaderUtil: AuthorizationHeaderUtil) =
TokenRelayRequestInterceptor(authorizationHeaderUtil)
}
<%_ } _%>
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,5 @@ class OAuth2UserClientFeignConfiguration {

@Bean(name = ["userFeignClientInterceptor"])
@Throws(IOException::class)
fun getUserFeignClientInterceptor() : RequestInterceptor {
return UserFeignClientInterceptor()
}
fun getUserFeignClientInterceptor() = UserFeignClientInterceptor()
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ import org.springframework.security.oauth2.provider.authentication.OAuth2Authent
import feign.RequestInterceptor
import feign.RequestTemplate

private const val AUTHORIZATION_HEADER = "Authorization"
private const val BEARER_TOKEN_TYPE = "Bearer"

class UserFeignClientInterceptor : RequestInterceptor {

override fun apply(template: RequestTemplate) {

val securityContext = SecurityContextHolder.getContext()
val authentication = securityContext.authentication

Expand All @@ -36,9 +38,4 @@ class UserFeignClientInterceptor : RequestInterceptor {
template.header(AUTHORIZATION_HEADER, "$BEARER_TOKEN_TYPE ${details.tokenValue}")
}
}

companion object {
private const val AUTHORIZATION_HEADER = "Authorization"
private const val BEARER_TOKEN_TYPE = "Bearer"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ package <%=packageName%>.config

import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor
import org.slf4j.LoggerFactory
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties
import org.springframework.context.annotation.Bean
Expand All @@ -37,7 +36,7 @@ import java.util.concurrent.Executor
@EnableScheduling
class AsyncConfiguration(private val taskExecutionProperties: TaskExecutionProperties) : AsyncConfigurer {

private val log = LoggerFactory.getLogger(AsyncConfiguration::class.java)
private val log = LoggerFactory.getLogger(javaClass)

@Bean(name = ["taskExecutor"])
override fun getAsyncExecutor(): Executor {
Expand All @@ -51,7 +50,5 @@ class AsyncConfiguration(private val taskExecutionProperties: TaskExecutionPrope
return ExceptionHandlingAsyncTaskExecutor(executor)
}

override fun getAsyncUncaughtExceptionHandler(): AsyncUncaughtExceptionHandler {
return SimpleAsyncUncaughtExceptionHandler()
}
override fun getAsyncUncaughtExceptionHandler() = SimpleAsyncUncaughtExceptionHandler()
}
Loading

0 comments on commit 193ae8f

Please sign in to comment.