Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#139 Convert usages of Optional to Kotlin nullables - WIP #181

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@
const returnPrefix = returnDirectly ? 'return' : 'val ' + instanceName + ' =';
if (!viaService) {
%>
<%- returnPrefix %> <%= entityInstance %>Repository.<% if (fieldsContainOwnerManyToMany === true) { %>findOneWithEagerRelationships(id)<% } else { %>findById(id)<% } %><% if (dto !== 'mapstruct') { %><% } else { %>
.map(<%= entityToDtoReference %>)<% } } else { %>
<%- returnPrefix %> <%= entityInstance %>Repository.<% if (fieldsContainOwnerManyToMany === true) { %>findOneWithEagerRelationships(id)<% } else { %>findByIdOrNull(id)<% } %><% if (dto !== 'mapstruct') { %><% } else { %>
?.let(<%= entityToDtoReference %>)<% } } else { %>
<%- returnPrefix %> <%= entityInstance %>Service.findOne(id)<% } %>
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ import org.springframework.stereotype.Repository
<%_ if (databaseType === 'sql' || databaseType === 'mongodb') { _%>
<%_ if (fieldsContainOwnerManyToMany) { _%>

import java.util.Optional
<%_ } _%>
<%_ } _%>
<%_ if (databaseType === 'cassandra') { _%>
Expand Down Expand Up @@ -84,7 +83,7 @@ interface <%=entityClass%>Repository : <% if (databaseType === 'sql') { %>JpaRep

@Query("select <%= 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%><%} }%> where <%=entityInstance%>.id =:id")
fun findOneWithEagerRelationships(@Param("id") id: <%= primaryKeyType %>): Optional<<%= asEntity(entityClass) %>>
fun findOneWithEagerRelationships(@Param("id") id: <%= primaryKeyType %>): <%= asEntity(entityClass) %>?
<%_
} else if (databaseType === 'mongodb') { _%>

Expand All @@ -95,7 +94,7 @@ interface <%=entityClass%>Repository : <% if (databaseType === 'sql') { %>JpaRep
fun findAllWithEagerRelationships(): MutableList<<%= asEntity(entityClass) %>>

@Query("{'id': ?0}")
fun findOneWithEagerRelationships(id: <%= primaryKeyType %>): Optional<<%= asEntity(entityClass) %>>
fun findOneWithEagerRelationships(id: <%= primaryKeyType %>): <%= asEntity(entityClass) %>?
<%_ }
} _%>
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import org.springframework.data.domain.Pageable
import reactor.core.publisher.Flux
<%_ } _%>

import java.util.Optional
<%_ if (databaseType === 'cassandra') { _%>
import java.util.UUID
<%_ } _%>
Expand Down Expand Up @@ -92,7 +91,7 @@ interface <%= entityClass %>Service {
* @param id the id of the entity.
* @return the entity.
*/
fun findOne(id: <%= primaryKeyType %>): Optional<<%= instanceType %>>
fun findOne(id: <%= primaryKeyType %>): <%= instanceType %>?

/**
* Delete the "id" <%= entityInstance %>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ package <%= packageName %>.service<% if (service === 'serviceImpl') { %>.impl<%
import <%= packageName %>.service.<%= entityClass %>Service<% } %>
import <%= packageName %>.domain.<%= asEntity(entityClass) %>
import <%= packageName %>.repository.<%= entityClass %>Repository
import org.springframework.data.repository.findByIdOrNull

<%_ if (isUsingMapsId === true) { _%>
import <%=packageName%>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository
<%_ } _%>
Expand Down Expand Up @@ -70,7 +72,6 @@ import org.springframework.transaction.annotation.Transactional
import reactor.core.publisher.Flux
<%_ } _%>

import java.util.Optional
<%_ if (databaseType === 'cassandra') { _%>
import java.util.UUID
<%_ } _%>
Expand Down Expand Up @@ -153,7 +154,7 @@ class <%= serviceClassName %>(
<%_ if (databaseType === 'sql') { _%>
@Transactional(readOnly = true)
<%_ } _%>
<% if (service === 'serviceImpl') { %>override <% } %>fun findOne(id: <%= primaryKeyType %>): Optional<<%= instanceType %>> {
<% if (service === 'serviceImpl') { %>override <% } %>fun findOne(id: <%= primaryKeyType %>): <%= instanceType %>? {
log.debug("Request to get <%= entityClass %> : {}", id)<%- include('../../common/get_template', {asEntity, asDto, viaService, returnDirectly:true}); -%>
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ import reactor.core.publisher.Flux
import javax.validation.Valid
<%_ } _%>
import java.net.URI
import java.net.URISyntaxException<% if (isUsingMapsId === true) { %>
import java.util.Objects<% } %>
import java.net.URISyntaxException
import java.util.*
<%_ if (databaseType === 'cassandra') { _%>
import java.util.UUID
<%_ } _%>
Expand Down Expand Up @@ -255,7 +255,7 @@ _%><%- include('../../common/inject_template', {viaService: viaService, construc
<%_ } _%>
fun get<%= entityClass %>(@PathVariable id: <%= primaryKeyType %>): ResponseEntity<<%= instanceType %>> {
log.debug("REST request to get <%= entityClass %> : {}", id)<%- include('../../common/get_template', {asEntity, asDto, viaService, returnDirectly:false}); -%>
return ResponseUtil.wrapOrNotFound(<%= instanceName %>)
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(<%= instanceName %>))
}
<%_ if (!readOnly) { _%>
/**
Expand Down
12 changes: 12 additions & 0 deletions generators/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,16 @@ module.exports = class extends ServerGenerator {
// Here we are not overriding this phase and hence its being handled by JHipster
return super._end();
}

/**
* Construct nullable or Mono (for reactive) type
* @param {String} classType entity name
*/
// TODO test me
nullableOrMono(classType) {
if (this.reactive) {
return `Mono<${classType}>`;
}
return `${classType}?`;
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ private const val BEARER_TOKEN_TYPE = "Bearer"
@Component
class UserFeignClientInterceptor : RequestInterceptor {

override fun apply(template: RequestTemplate) =
getCurrentUserJWT().ifPresent { s -> template.header(AUTHORIZATION_HEADER,"$BEARER_TOKEN_TYPE $s") }
override fun apply(template: RequestTemplate) {
getCurrentUserJWT()?.let { s -> template.header(AUTHORIZATION_HEADER, "$BEARER_TOKEN_TYPE $s") }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
package <%=packageName%>.config

import java.lang.reflect.Method
import java.util.Optional

import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.core.MethodParameter
Expand Down Expand Up @@ -156,29 +155,25 @@ constructor(
): Pageable {
assertPageableUniqueness(methodParameter)

val defaultOrFallback = getDefaultFromAnnotationOrFallback(methodParameter)!!.toOptional()
val defaultOrFallback = getDefaultFromAnnotationOrFallback(methodParameter)

val page = parseAndApplyBoundaries(pageString, Integer.MAX_VALUE, true)
val pageSize = parseAndApplyBoundaries(pageSizeString, maxPageSize, false)

if (!(page.isPresent && pageSize.isPresent) && !defaultOrFallback.isPresent) {
if (page != null && pageSize != null && defaultOrFallback == null) {
return Pageable.unpaged()
}

val p = page.orElseGet {
defaultOrFallback.map { it.pageNumber }.orElseThrow { IllegalStateException() }
}
var ps = pageSize.orElseGet {
defaultOrFallback.map { it.pageSize }.orElseThrow { IllegalStateException() }
}

val p = page ?: defaultOrFallback?.pageNumber ?: throw IllegalStateException()
var ps = pageSize ?: defaultOrFallback?.pageSize ?: throw IllegalStateException()

// Limit lower bound
ps =
if (ps < 1) defaultOrFallback.map { it.pageSize }.orElseThrow { IllegalStateException() } else ps
ps = if (ps < 1) defaultOrFallback?.pageSize ?: throw IllegalStateException() else ps
// Limit upper bound
ps = if (ps > maxPageSize) maxPageSize else ps

return PageRequest.of(p, ps, defaultOrFallback.map<Sort> { it.sort }.orElseGet { Sort.unsorted() })

return PageRequest.of(p, ps, defaultOrFallback?.sort ?: Sort.unsorted())

}

/**
Expand Down Expand Up @@ -218,16 +213,16 @@ constructor(
* @param shiftIndex whether to shift the index if [.oneIndexedParameters] is set to true.
* @return the parsed integer.
*/
private fun parseAndApplyBoundaries(@Nullable parameter: String?, upper: Int, shiftIndex: Boolean): Optional<Int> {
private fun parseAndApplyBoundaries(@Nullable parameter: String?, upper: Int, shiftIndex: Boolean): Int? {
if (!StringUtils.hasText(parameter)) {
return Optional.empty()
return null
}

return try {
val parsed = Integer.parseInt(parameter!!) - if (isOneIndexedParameters && shiftIndex) 1 else 0
Optional.of(if (parsed < 0) 0 else if (parsed > upper) upper else parsed)
if (parsed < 0) 0 else if (parsed > upper) upper else parsed
} catch (e: NumberFormatException) {
Optional.of(0)
0
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
-%>
package <%=packageName%>.config

import java.util.Optional

import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.core.MethodParameter
import org.springframework.core.annotation.AnnotationUtils
Expand Down Expand Up @@ -133,13 +131,10 @@ class ReactiveSortHandlerMethodArgumentResolver : SyncHandlerMethodArgumentResol
}

if (annotatedDefaults != null) {

var sort = Sort.unsorted()

for (currentAnnotatedDefault in annotatedDefaults.value) {
sort = appendOrCreateSortTo(currentAnnotatedDefault, sort)
}

return sort
}

Expand Down Expand Up @@ -200,15 +195,15 @@ class ReactiveSortHandlerMethodArgumentResolver : SyncHandlerMethodArgumentResol
val elements = part.split(delimiter.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()

val direction = if (elements.isEmpty()) {
Optional.empty()
null
} else {
Direction.fromOptionalString(elements[elements.size - 1])
Direction.fromString(elements[elements.size - 1])
}

val lastIndex = direction.map { elements.size - 1 }.orElseGet { elements.size }
val lastIndex = direction?.let { elements.size - 1 } ?: elements.size

for (i in 0 until lastIndex) {
toOrder(elements[i], direction).ifPresent { allOrders.add(it) }
toOrder(elements[i], direction)?.let { allOrders.add(it) }
}
}

Expand Down Expand Up @@ -335,11 +330,11 @@ class ReactiveSortHandlerMethodArgumentResolver : SyncHandlerMethodArgumentResol
private val SORT_DEFAULTS_NAME = SortDefaults::class.java.simpleName
private val SORT_DEFAULT_NAME = SortDefault::class.java.simpleName

private fun toOrder(property: String, direction: Optional<Direction>) =
private fun toOrder(property: String, direction: Direction?) =
if (!StringUtils.hasText(property)) {
Optional.empty()
null
} else {
Optional.of(direction.map { Order(it, property) }.orElseGet { Order.by(property) })
direction?.let { Order(it, property) } ?: Order.by(property)
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ import org.springframework.web.socket.server.HandshakeInterceptor
import org.springframework.web.socket.server.support.DefaultHandshakeHandler

import java.security.Principal
import java.util.Optional

@Configuration
@EnableWebSocketMessageBroker
Expand All @@ -49,10 +48,9 @@ class WebsocketConfiguration(private val jHipsterProperties: JHipsterProperties)
}

override fun registerStompEndpoints(registry: StompEndpointRegistry?) {
val allowedOrigins =
Optional.ofNullable(jHipsterProperties.cors.allowedOrigins)
.map { origins -> origins.toTypedArray() }
.orElse(arrayOfNulls(0))
val allowedOrigins = jHipsterProperties.cors.allowedOrigins
?.let { origins -> origins.toTypedArray() }
?: arrayOfNulls(0)

registry!!.addEndpoint("/websocket/tracker")
.setHandshakeHandler(defaultHandshakeHandler())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ class RateLimitingFilter(private val jHipsterProperties: JHipsterProperties) : Z
* The ID that will identify the limit: the user login or the user IP address.
*/
private fun getId(httpServletRequest: HttpServletRequest): String =
getCurrentUserLogin().orElse(httpServletRequest.remoteAddr)
getCurrentUserLogin() ?: httpServletRequest.remoteAddr

companion object {
const val GATEWAY_RATE_LIMITING_CACHE_NAME = "gateway-rate-limiting"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ import javax.validation.Validator
<%_ } _%>
<%_ if (databaseType === 'cassandra' || databaseType === 'couchbase') { _%>

import java.util.Optional
<%_ } _%>
<%_ if (databaseType === 'couchbase') { _%>

Expand All @@ -60,7 +59,7 @@ import <%=packageName%>.config.ID_DELIMITER
*/<% } %><% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>
interface PersistentTokenRepository : <% if (databaseType === 'sql') { %>JpaRepository<% } %><% if (databaseType === 'mongodb') { %>MongoRepository<% } %><% if (databaseType === 'couchbase') { %>N1qlCouchbaseRepository<% } %><PersistentToken, String> {
<% if (databaseType === 'couchbase') { %>
fun findBySeries(series: String): Optional<PersistentToken> {
fun findBySeries(series: String): PersistentToken? {
return findById(PersistentToken.PREFIX + ID_DELIMITER + series)
}

Expand Down Expand Up @@ -102,8 +101,7 @@ class PersistentTokenRepository (private val session: Session, private val valid
"DELETE FROM persistent_token_by_user WHERE user_id = :user_id AND persistent_token_series = :persistent_token_series"
)

fun findById(presentedSeries: String): Optional<PersistentToken> =
Optional.ofNullable(mapper.get(presentedSeries))
fun findById(presentedSeries: String): PersistentToken? = mapper.get(presentedSeries)

fun findByUser( user: <%= asEntity('User') %>): MutableList<PersistentToken> {
val stmt = findPersistentTokenSeriesByUserIdStmt.bind()
Expand Down
Loading